Update aosp/master clang for rebase to r230699.

Change-Id: I6a546ab3d4ae37119eebb735e102cca4f80ab520
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7f5e092..75b8075 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -83,7 +83,13 @@
 
   # 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)
+  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})
+  else()
+    set(LLVM_SHLIB_OUTPUT_INTDIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
+  endif()
 
   option(LLVM_INSTALL_TOOLCHAIN_ONLY
     "Only include toolchain files in the 'install' target." OFF)
@@ -105,8 +111,8 @@
   link_directories("${LLVM_LIBRARY_DIR}")
 
   set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
-  set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
-  set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
+  set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX} )
+  set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX} )
 
   if(LLVM_INCLUDE_TESTS)
     # Check prebuilt llvm/utils.
@@ -193,6 +199,9 @@
 set(CLANG_VENDOR_UTI "org.llvm.clang" CACHE STRING
   "Vendor-specific uti.")
 
+# The libdir suffix must exactly match whatever LLVM's configuration used.
+set(CLANG_LIBDIR_SUFFIX "${LLVM_LIBDIR_SUFFIX}")
+
 set(CLANG_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
 set(CLANG_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
 
@@ -263,10 +272,10 @@
     OUTPUT_VARIABLE LD_V_OUTPUT
   )
   if (NOT HAD_ERROR)
-    if ("${LD_V_OUTPUT}" MATCHES ".*ld64.*")
-      string(REGEX REPLACE ".*ld64-([0-9.]*).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
-    else()
-      string(REGEX REPLACE "[^0-9]*([0-9.]*).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
+    if ("${LD_V_OUTPUT}" MATCHES ".*ld64-([0-9.]+).*")
+      string(REGEX REPLACE ".*ld64-([0-9.]+).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
+    elseif ("${LD_V_OUTPUT}" MATCHES "[^0-9]*([0-9.]+).*")
+      string(REGEX REPLACE "[^0-9]*([0-9.]+).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
     endif()
   else()
     message(FATAL_ERROR "${CMAKE_LINKER} failed with status ${HAD_ERROR}")
diff --git a/CODE_OWNERS.TXT b/CODE_OWNERS.TXT
index b58014f..96c9d03 100644
--- a/CODE_OWNERS.TXT
+++ b/CODE_OWNERS.TXT
@@ -25,6 +25,10 @@
 E: dgregor@apple.com
 D: All parts of Clang not covered by someone else
 
+N: Reid Kleckner
+E: rnk@google.com
+D: Microsoft C++ ABI compatibility and general Windows support
+
 N: Anton Korobeynikov
 E: anton@korobeynikov.info
 D: Exception handling, Windows codegen, ARM EABI
diff --git a/clang-tblgen-rules.mk b/clang-tblgen-rules.mk
index 9982056..8e408a2 100644
--- a/clang-tblgen-rules.mk
+++ b/clang-tblgen-rules.mk
@@ -13,6 +13,12 @@
 	$(call transform-device-clang-td-to-out,$(1)))
 endef
 
+define transform-td-to-out
+$(if $(LOCAL_IS_HOST_MODULE),	\
+	$(call transform-host-td-to-out,$(1)),	\
+	$(call transform-device-td-to-out,$(1)))
+endef
+
 generated_sources := $(call local-generated-sources-dir)
 
 ifneq ($(findstring AttrDump.inc,$(TBLGEN_TABLES)),)
@@ -230,6 +236,13 @@
 	$(call transform-td-to-out,opt-parser-defs)
 endif
 
+ifneq ($(findstring arm_neon.h,$(TBLGEN_TABLES)),)
+LOCAL_GENERATED_SOURCES += $(generated_sources)/include/clang/Basic/arm_neon.h
+$(generated_sources)/include/clang/Basic/arm_neon.h: TBLGEN_LOCAL_MODULE := $(LOCAL_MODULE)
+$(generated_sources)/include/clang/Basic/arm_neon.h: $(CLANG_ROOT_PATH)/include/clang/Basic/arm_neon.td $(CLANG_TBLGEN)
+	$(call transform-clang-td-to-out,arm-neon)
+endif
+
 LOCAL_C_INCLUDES += $(generated_sources)/include
 
 endif
diff --git a/docs/AddressSanitizer.rst b/docs/AddressSanitizer.rst
index 122b31a..6175433 100644
--- a/docs/AddressSanitizer.rst
+++ b/docs/AddressSanitizer.rst
@@ -23,8 +23,7 @@
 How to build
 ============
 
-Follow the `clang build instructions <../get_started.html>`_. CMake build is
-supported.
+Build LLVM/Clang with `CMake <http://llvm.org/docs/CMake.html>`_.
 
 Usage
 =====
@@ -187,6 +186,7 @@
 * Linux i386/x86\_64 (tested on Ubuntu 12.04);
 * MacOS 10.6 - 10.9 (i386/x86\_64).
 * Android ARM
+* FreeBSD i386/x86\_64 (tested on FreeBSD 11-current)
 
 Ports to various other platforms are in progress.
 
diff --git a/docs/AutomaticReferenceCounting.rst b/docs/AutomaticReferenceCounting.rst
index 1457b60..2faed23 100644
--- a/docs/AutomaticReferenceCounting.rst
+++ b/docs/AutomaticReferenceCounting.rst
@@ -594,7 +594,9 @@
 * a message send, and the declared method either has the
   ``cf_returns_not_retained`` attribute or it has neither the
   ``cf_returns_retained`` attribute nor a :ref:`selector family
-  <arc.method-families>` that implies a retained result.
+  <arc.method-families>` that implies a retained result, or
+* :when-revised:`[beginning LLVM 3.6]` :revision:`a load from a` ``const``
+  :revision:`non-system global variable.`
 
 An expression is :arc-term:`known retained` if it is an rvalue of :ref:`C
 retainable pointer type <arc.misc.c-retainable>` and it is:
@@ -631,6 +633,12 @@
   to an ObjC-typed local, and then calling ``CFRelease`` when done  ---  are a
   bit too likely to be accidentally accepted, leading to mysterious behavior.
 
+  For loads from ``const`` global variables of :ref:`C retainable pointer type
+  <arc.misc.c-retainable>`, it is reasonable to assume that global system
+  constants were initialitzed with true constants (e.g. string literals), but
+  user constants might have been initialized with something dynamically
+  allocated, using a global initializer.
+
 .. _arc.objects.restrictions.conversion-exception-contextual:
 
 Conversion from retainable object pointer type in certain contexts
diff --git a/docs/ClangFormatStyleOptions.rst b/docs/ClangFormatStyleOptions.rst
index cef3f24..ce6fae1 100644
--- a/docs/ClangFormatStyleOptions.rst
+++ b/docs/ClangFormatStyleOptions.rst
@@ -150,10 +150,24 @@
 **AccessModifierOffset** (``int``)
   The extra indent or outdent of access modifiers, e.g. ``public:``.
 
+**AlignAfterOpenBracket** (``bool``)
+  If ``true``, horizontally aligns arguments after an open bracket.
+
+  This applies to round brackets (parentheses), angle brackets and square
+  brackets. This will result in formattings like
+  \code
+  someLongFunction(argument1,
+  argument2);
+  \endcode
+
 **AlignEscapedNewlinesLeft** (``bool``)
   If ``true``, aligns escaped newlines as far left as possible.
   Otherwise puts them into the right-most column.
 
+**AlignOperands** (``bool``)
+  If ``true``, horizontally align operands of binary and ternary
+  expressions.
+
 **AlignTrailingComments** (``bool``)
   If ``true``, aligns trailing comments.
 
@@ -179,6 +193,8 @@
     Never merge functions into a single line.
   * ``SFS_Inline`` (in configuration: ``Inline``)
     Only merge functions defined inside a class.
+  * ``SFS_Empty`` (in configuration: ``Empty``)
+    Only merge empty functions.
   * ``SFS_All`` (in configuration: ``All``)
     Merge all functions fitting on a single line.
 
diff --git a/docs/ControlFlowIntegrity.rst b/docs/ControlFlowIntegrity.rst
new file mode 100644
index 0000000..a4c60b3
--- /dev/null
+++ b/docs/ControlFlowIntegrity.rst
@@ -0,0 +1,74 @@
+======================
+Control Flow Integrity
+======================
+
+.. toctree::
+   :hidden:
+
+   ControlFlowIntegrityDesign
+
+.. contents::
+   :local:
+
+Introduction
+============
+
+Clang includes an implementation of a number of control flow integrity (CFI)
+schemes, which are designed to abort the program upon detecting certain forms
+of undefined behavior that can potentially allow attackers to subvert the
+program's control flow. These schemes have been optimized for performance,
+allowing developers to enable them in release builds.
+
+To enable Clang's available CFI schemes, use the flag ``-fsanitize=cfi``.
+As currently implemented, CFI relies on link-time optimization (LTO); the CFI
+schemes imply ``-flto``, and the linker used must support LTO, for example
+via the `gold plugin`_. To allow the checks to be implemented efficiently,
+the program must be structured such that certain object files are compiled
+with CFI enabled, and are statically linked into the program. This may
+preclude the use of shared libraries in some cases.
+
+Clang currently implements forward-edge CFI for virtual calls. More schemes
+are under development.
+
+.. _gold plugin: http://llvm.org/docs/GoldPlugin.html
+
+Forward-Edge CFI for Virtual Calls
+----------------------------------
+
+This scheme checks that virtual calls take place using a vptr of the correct
+dynamic type; that is, the dynamic type of the called object must be a
+derived class of the static type of the object used to make the call.
+This CFI scheme can be enabled on its own using ``-fsanitize=cfi-vptr``.
+
+For this scheme to work, all translation units containing the definition
+of a virtual member function (whether inline or not) must be compiled
+with ``-fsanitize=cfi-vptr`` enabled and be statically linked into the
+program. Classes in the C++ standard library (under namespace ``std``) are
+exempted from checking, and therefore programs may be linked against a
+pre-built standard library, but this may change in the future.
+
+Performance
+~~~~~~~~~~~
+
+A performance overhead of less than 1% has been measured by running the
+Dromaeo benchmark suite against an instrumented version of the Chromium
+web browser. Another good performance benchmark for this mechanism is the
+virtual-call-heavy SPEC 2006 xalancbmk.
+
+Note that this scheme has not yet been optimized for binary size; an increase
+of up to 15% has been observed for Chromium.
+
+Design
+------
+
+Please refer to the :doc:`design document<ControlFlowIntegrityDesign>`.
+
+Publications
+------------
+
+`Control-Flow Integrity: Principles, Implementations, and Applications <http://research.microsoft.com/pubs/64250/ccs05.pdf>`_.
+Martin Abadi, Mihai Budiu, Úlfar Erlingsson, Jay Ligatti.
+
+`Enforcing Forward-Edge Control-Flow Integrity in GCC & LLVM <http://www.pcc.me.uk/~peter/acad/usenix14.pdf>`_.
+Caroline Tice, Tom Roeder, Peter Collingbourne, Stephen Checkoway,
+Úlfar Erlingsson, Luis Lozano, Geoff Pike.
diff --git a/docs/ControlFlowIntegrityDesign.rst b/docs/ControlFlowIntegrityDesign.rst
new file mode 100644
index 0000000..86a08b6
--- /dev/null
+++ b/docs/ControlFlowIntegrityDesign.rst
@@ -0,0 +1,265 @@
+===========================================
+Control Flow Integrity Design Documentation
+===========================================
+
+This page documents the design of the :doc:`ControlFlowIntegrity` schemes
+supported by Clang.
+
+Forward-Edge CFI for Virtual Calls
+==================================
+
+This scheme works by allocating, for each static type used to make a virtual
+call, a region of read-only storage in the object file holding a bit vector
+that maps onto to the region of storage used for those virtual tables. Each
+set bit in the bit vector corresponds to the `address point`_ for a virtual
+table compatible with the static type for which the bit vector is being built.
+
+For example, consider the following three C++ classes:
+
+.. code-block:: c++
+
+  struct A {
+    virtual void f1();
+    virtual void f2();
+    virtual void f3();
+  };
+
+  struct B : A {
+    virtual void f1();
+    virtual void f2();
+    virtual void f3();
+  };
+
+  struct C : A {
+    virtual void f1();
+    virtual void f2();
+    virtual void f3();
+  };
+
+The scheme will cause the virtual tables for A, B and C to be laid out
+consecutively:
+
+.. csv-table:: Virtual Table Layout for A, B, C
+  :header: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
+
+  A::offset-to-top, &A::rtti, &A::f1, &A::f2, &A::f3, B::offset-to-top, &B::rtti, &B::f1, &B::f2, &B::f3, C::offset-to-top, &C::rtti, &C::f1, &C::f2, &C::f3
+
+The bit vector for static types A, B and C will look like this:
+
+.. csv-table:: Bit Vectors for A, B, C
+  :header: Class, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
+
+  A, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0
+  B, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0
+  C, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0
+
+To emit a virtual call, the compiler will assemble code that checks that
+the object's virtual table pointer is in-bounds and aligned and that the
+relevant bit is set in the bit vector.
+
+For example on x86 a typical virtual call may look like this:
+
+.. code-block:: none
+
+    159a:       48 8b 03                mov    (%rbx),%rax
+    159d:       48 8d 15 6c 33 00 00    lea    0x336c(%rip),%rdx
+    15a4:       48 89 c1                mov    %rax,%rcx
+    15a7:       48 29 d1                sub    %rdx,%rcx
+    15aa:       48 c1 c1 3d             rol    $0x3d,%rcx
+    15ae:       48 83 f9 51             cmp    $0x51,%rcx
+    15b2:       77 3b                   ja     15ef <main+0xcf>
+    15b4:       48 89 ca                mov    %rcx,%rdx
+    15b7:       48 c1 ea 05             shr    $0x5,%rdx
+    15bb:       48 8d 35 b8 07 00 00    lea    0x7b8(%rip),%rsi
+    15c2:       8b 14 96                mov    (%rsi,%rdx,4),%edx
+    15c5:       0f a3 ca                bt     %ecx,%edx
+    15c8:       73 25                   jae    15ef <main+0xcf>
+    15ca:       48 89 df                mov    %rbx,%rdi
+    15cd:       ff 10                   callq  *(%rax)
+    [...]
+    15ef:       0f 0b                   ud2    
+
+The compiler relies on co-operation from the linker in order to assemble
+the bit vectors for the whole program. It currently does this using LLVM's
+`bit sets`_ mechanism together with link-time optimization.
+
+.. _address point: https://mentorembedded.github.io/cxx-abi/abi.html#vtable-general
+.. _bit sets: http://llvm.org/docs/BitSets.html
+
+Optimizations
+-------------
+
+The scheme as described above is the fully general variant of the scheme.
+Most of the time we are able to apply one or more of the following
+optimizations to improve binary size or performance.
+
+In fact, if you try the above example with the current version of the
+compiler, you will probably find that it will not use the described virtual
+table layout or machine instructions. Some of the optimizations we are about
+to introduce cause the compiler to use a different layout or a different
+sequence of machine instructions.
+
+Stripping Leading/Trailing Zeros in Bit Vectors
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If a bit vector contains leading or trailing zeros, we can strip them from
+the vector. The compiler will emit code to check if the pointer is in range
+of the region covered by ones, and perform the bit vector check using a
+truncated version of the bit vector. For example, the bit vectors for our
+example class hierarchy will be emitted like this:
+
+.. csv-table:: Bit Vectors for A, B, C
+  :header: Class, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
+
+  A,  ,  , 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,  ,  
+  B,  ,  ,  ,  ,  ,  ,  , 1,  ,  ,  ,  ,  ,  ,  
+  C,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  , 1,  ,  
+
+Short Inline Bit Vectors
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+If the vector is sufficiently short, we can represent it as an inline constant
+on x86. This saves us a few instructions when reading the correct element
+of the bit vector.
+
+If the bit vector fits in 32 bits, the code looks like this:
+
+.. code-block:: none
+
+     dc2:       48 8b 03                mov    (%rbx),%rax
+     dc5:       48 8d 15 14 1e 00 00    lea    0x1e14(%rip),%rdx
+     dcc:       48 89 c1                mov    %rax,%rcx
+     dcf:       48 29 d1                sub    %rdx,%rcx
+     dd2:       48 c1 c1 3d             rol    $0x3d,%rcx
+     dd6:       48 83 f9 03             cmp    $0x3,%rcx
+     dda:       77 2f                   ja     e0b <main+0x9b>
+     ddc:       ba 09 00 00 00          mov    $0x9,%edx
+     de1:       0f a3 ca                bt     %ecx,%edx
+     de4:       73 25                   jae    e0b <main+0x9b>
+     de6:       48 89 df                mov    %rbx,%rdi
+     de9:       ff 10                   callq  *(%rax)
+    [...]
+     e0b:       0f 0b                   ud2    
+
+Or if the bit vector fits in 64 bits:
+
+.. code-block:: none
+
+    11a6:       48 8b 03                mov    (%rbx),%rax
+    11a9:       48 8d 15 d0 28 00 00    lea    0x28d0(%rip),%rdx
+    11b0:       48 89 c1                mov    %rax,%rcx
+    11b3:       48 29 d1                sub    %rdx,%rcx
+    11b6:       48 c1 c1 3d             rol    $0x3d,%rcx
+    11ba:       48 83 f9 2a             cmp    $0x2a,%rcx
+    11be:       77 35                   ja     11f5 <main+0xb5>
+    11c0:       48 ba 09 00 00 00 00    movabs $0x40000000009,%rdx
+    11c7:       04 00 00 
+    11ca:       48 0f a3 ca             bt     %rcx,%rdx
+    11ce:       73 25                   jae    11f5 <main+0xb5>
+    11d0:       48 89 df                mov    %rbx,%rdi
+    11d3:       ff 10                   callq  *(%rax)
+    [...]
+    11f5:       0f 0b                   ud2    
+
+If the bit vector consists of a single bit, there is only one possible
+virtual table, and the check can consist of a single equality comparison:
+
+.. code-block:: none
+
+     9a2:   48 8b 03                mov    (%rbx),%rax
+     9a5:   48 8d 0d a4 13 00 00    lea    0x13a4(%rip),%rcx
+     9ac:   48 39 c8                cmp    %rcx,%rax
+     9af:   75 25                   jne    9d6 <main+0x86>
+     9b1:   48 89 df                mov    %rbx,%rdi
+     9b4:   ff 10                   callq  *(%rax)
+     [...]
+     9d6:   0f 0b                   ud2
+
+Virtual Table Layout
+~~~~~~~~~~~~~~~~~~~~
+
+The compiler lays out classes of disjoint hierarchies in separate regions
+of the object file. At worst, bit vectors in disjoint hierarchies only
+need to cover their disjoint hierarchy. But the closer that classes in
+sub-hierarchies are laid out to each other, the smaller the bit vectors for
+those sub-hierarchies need to be (see "Stripping Leading/Trailing Zeros in Bit
+Vectors" above). The `GlobalLayoutBuilder`_ class is responsible for laying
+out the globals efficiently to minimize the sizes of the underlying bitsets.
+
+.. _GlobalLayoutBuilder: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Transforms/IPO/LowerBitSets.h?view=markup
+
+Alignment
+~~~~~~~~~
+
+If all gaps between address points in a particular bit vector are multiples
+of powers of 2, the compiler can compress the bit vector by strengthening
+the alignment requirements of the virtual table pointer. For example, given
+this class hierarchy:
+
+.. code-block:: c++
+
+  struct A {
+    virtual void f1();
+    virtual void f2();
+  };
+
+  struct B : A {
+    virtual void f1();
+    virtual void f2();
+    virtual void f3();
+    virtual void f4();
+    virtual void f5();
+    virtual void f6();
+  };
+
+  struct C : A {
+    virtual void f1();
+    virtual void f2();
+  };
+
+The virtual tables will be laid out like this:
+
+.. csv-table:: Virtual Table Layout for A, B, C
+  :header: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
+
+  A::offset-to-top, &A::rtti, &A::f1, &A::f2, B::offset-to-top, &B::rtti, &B::f1, &B::f2, &B::f3, &B::f4, &B::f5, &B::f6, C::offset-to-top, &C::rtti, &C::f1, &C::f2
+
+Notice that each address point for A is separated by 4 words. This lets us
+emit a compressed bit vector for A that looks like this:
+
+.. csv-table::
+  :header: 2, 6, 10, 14
+
+  1, 1, 0, 1
+
+At call sites, the compiler will strengthen the alignment requirements by
+using a different rotate count. For example, on a 64-bit machine where the
+address points are 4-word aligned (as in A from our example), the ``rol``
+instruction may look like this:
+
+.. code-block:: none
+
+     dd2:       48 c1 c1 3b             rol    $0x3b,%rcx
+
+Padding to Powers of 2
+~~~~~~~~~~~~~~~~~~~~~~
+
+Of course, this alignment scheme works best if the address points are
+in fact aligned correctly. To make this more likely to happen, we insert
+padding between virtual tables that in many cases aligns address points to
+a power of 2. Specifically, our padding aligns virtual tables to the next
+highest power of 2 bytes; because address points for specific base classes
+normally appear at fixed offsets within the virtual table, this normally
+has the effect of aligning the address points as well.
+
+This scheme introduces tradeoffs between decreased space overhead for
+instructions and bit vectors and increased overhead in the form of padding. We
+therefore limit the amount of padding so that we align to no more than 128
+bytes. This number was found experimentally to provide a good tradeoff.
+
+Eliminating Bit Vector Checks for All-Ones Bit Vectors
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If the bit vector is all ones, the bit vector check is redundant; we simply
+need to check that the address is in range and well aligned. This is more
+likely to occur if the virtual tables are padded.
diff --git a/docs/InternalsManual.rst b/docs/InternalsManual.rst
index 50a1943..7bb34b7 100644
--- a/docs/InternalsManual.rst
+++ b/docs/InternalsManual.rst
@@ -784,9 +784,24 @@
 simply check to see whether the guarding condition is defined or not.  If so,
 the preprocessor can completely ignore the include of the header.
 
+.. _Parser:
+
 The Parser Library
 ==================
 
+This library contains a recursive-descent parser that polls tokens from the
+preprocessor and notifies a client of the parsing progress.
+
+Historically, the parser used to talk to an abstract ``Action`` interface that
+had virtual methods for parse events, for example ``ActOnBinOp()``.  When Clang
+grew C++ support, the parser stopped supporting general ``Action`` clients --
+it now always talks to the :ref:`Sema libray <Sema>`.  However, the Parser
+still accesses AST objects only through opaque types like ``ExprResult`` and
+``StmtResult``.  Only :ref:`Sema <Sema>` looks at the AST node contents of these
+wrappers.
+
+.. _AST:
+
 The AST Library
 ===============
 
@@ -1308,11 +1323,13 @@
 ``DeclContext`` manages multiply-defined declaration contexts internally.  The
 function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
 a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
-maintaining the lookup table used for the semantics-centric view.  Given the
-primary context, one can follow the chain of ``DeclContext`` nodes that define
-additional declarations via ``DeclContext::getNextContext``.  Note that these
-functions are used internally within the lookup and insertion methods of the
-``DeclContext``, so the vast majority of clients can ignore them.
+maintaining the lookup table used for the semantics-centric view.  Given a
+DeclContext, one can obtain the set of declaration contexts that are semanticaly
+connected to this declaration context, in source order, including this context
+(which will be the only result, for non-namespace contexts) via
+``DeclContext::collectAllContexts``. Note that these functions are used
+internally within the lookup and insertion methods of the ``DeclContext``, so
+the vast majority of clients can ignore them.
 
 .. _CFG:
 
@@ -1582,6 +1599,23 @@
 * ``__builtin_strlen`` and ``strlen``: These are constant folded as integer
   constant expressions if the argument is a string literal.
 
+.. _Sema:
+
+The Sema Library
+================
+
+This library is called by the :ref:`Parser library <Parser>` during parsing to
+do semantic analysis of the input.  For valid programs, Sema builds an AST for
+parsed constructs.
+
+.. _CodeGen:
+
+The CodeGen Library
+===================
+
+CodeGen takes an :ref:`AST <AST>` as input and produces `LLVM IR code
+<//llvm.org/docs/LangRef.html>`_ from it.
+
 How to change Clang
 ===================
 
diff --git a/docs/LanguageExtensions.rst b/docs/LanguageExtensions.rst
index ae298af..035b50d 100644
--- a/docs/LanguageExtensions.rst
+++ b/docs/LanguageExtensions.rst
@@ -143,8 +143,8 @@
 -------------------
 
 This function-like macro takes a single identifier argument that is the name of
-an attribute.  It evaluates to 1 if the attribute is supported by the current
-compilation target, or 0 if not.  It can be used like this:
+a GNU-style attribute.  It evaluates to 1 if the attribute is supported by the
+current compilation target, or 0 if not.  It can be used like this:
 
 .. code-block:: c++
 
@@ -164,6 +164,33 @@
 (double underscore) to avoid interference from a macro with the same name.  For
 instance, ``__always_inline__`` can be used instead of ``always_inline``.
 
+
+``__has_declspec_attribute``
+----------------------------
+
+This function-like macro takes a single identifier argument that is the name of
+an attribute implemented as a Microsoft-style ``__declspec`` attribute.  It
+evaluates to 1 if the attribute is supported by the current compilation target,
+or 0 if not.  It can be used like this:
+
+.. code-block:: c++
+
+  #ifndef __has_declspec_attribute         // Optional of course.
+    #define __has_declspec_attribute(x) 0  // Compatibility with non-clang compilers.
+  #endif
+
+  ...
+  #if __has_declspec_attribute(dllexport)
+  #define DLLEXPORT __declspec(dllexport)
+  #else
+  #define DLLEXPORT
+  #endif
+  ...
+
+The attribute name can also be specified with a preceding and following ``__``
+(double underscore) to avoid interference from a macro with the same name.  For
+instance, ``__dllexport__`` can be used instead of ``dllexport``.
+
 ``__is_identifier``
 -------------------
 
@@ -543,6 +570,9 @@
 Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
 determine if support for alignment specifiers using ``alignas`` is enabled.
 
+Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
+determine if support for the ``alignof`` keyword is enabled.
+
 C++11 attributes
 ^^^^^^^^^^^^^^^^
 
@@ -857,6 +887,9 @@
 Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
 if support for alignment specifiers using ``_Alignas`` is enabled.
 
+Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
+if support for the ``_Alignof`` keyword is enabled.
+
 C11 atomic operations
 ^^^^^^^^^^^^^^^^^^^^^
 
diff --git a/docs/LibASTMatchersReference.html b/docs/LibASTMatchersReference.html
index 2eabff4..74bbf9e 100644
--- a/docs/LibASTMatchersReference.html
+++ b/docs/LibASTMatchersReference.html
@@ -307,6 +307,29 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('translationUnitDecl0')"><a name="translationUnitDecl0Anchor">translationUnitDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TranslationUnitDecl.html">TranslationUnitDecl</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="translationUnitDecl0"><pre>Matches the top declaration context.
+
+Given
+  int X;
+  namespace NS {
+  int Y;
+  }  namespace NS
+decl(hasDeclContext(translationUnitDecl()))
+  matches "int X", but not "int Y".
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('typedefDecl0')"><a name="typedefDecl0Anchor">typedefDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefDecl.html">TypedefDecl</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="typedefDecl0"><pre>Matches typedef declarations.
+
+Given
+  typedef int X;
+typedefDecl()
+  matches "typedef int X"
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('unresolvedUsingValueDecl0')"><a name="unresolvedUsingValueDecl0Anchor">unresolvedUsingValueDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingValueDecl.html">UnresolvedUsingValueDecl</a>&gt;...</td></tr>
 <tr><td colspan="4" class="doc" id="unresolvedUsingValueDecl0"><pre>Matches unresolved using value declarations.
 
@@ -339,6 +362,15 @@
   matches using namespace X </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('valueDecl0')"><a name="valueDecl0Anchor">valueDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt;...</td></tr>
+<tr><td colspan="4" class="doc" id="valueDecl0"><pre>Matches any value declaration.
+
+Example matches A, B, C and F
+  enum X { A, B, C };
+  void F();
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('varDecl0')"><a name="varDecl0Anchor">varDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;...</td></tr>
 <tr><td colspan="4" class="doc" id="varDecl0"><pre>Matches variable declarations.
 
@@ -1506,7 +1538,7 @@
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isDerivedFrom1')"><a name="isDerivedFrom1Anchor">isDerivedFrom</a></td><td>StringRef BaseName</td></tr>
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isDerivedFrom1')"><a name="isDerivedFrom1Anchor">isDerivedFrom</a></td><td>std::string BaseName</td></tr>
 <tr><td colspan="4" class="doc" id="isDerivedFrom1"><pre>Overloaded method as shortcut for isDerivedFrom(hasName(...)).
 </pre></td></tr>
 
@@ -1525,7 +1557,7 @@
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isSameOrDerivedFrom1')"><a name="isSameOrDerivedFrom1Anchor">isSameOrDerivedFrom</a></td><td>StringRef BaseName</td></tr>
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isSameOrDerivedFrom1')"><a name="isSameOrDerivedFrom1Anchor">isSameOrDerivedFrom</a></td><td>std::string BaseName</td></tr>
 <tr><td colspan="4" class="doc" id="isSameOrDerivedFrom1"><pre>Overloaded method as shortcut for
 isSameOrDerivedFrom(hasName(...)).
 </pre></td></tr>
@@ -1654,22 +1686,51 @@
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isImplicit0')"><a name="isImplicit0Anchor">isImplicit</a></td><td></td></tr>
-<tr><td colspan="4" class="doc" id="isImplicit0"><pre>Matches a declaration that has been implicitly added
-by the compiler (eg. implicit defaultcopy constructors).
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isExpansionInFileMatching0')"><a name="isExpansionInFileMatching0Anchor">isExpansionInFileMatching</a></td><td>std::string RegExp</td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInFileMatching0"><pre>Matches AST nodes that were expanded within files whose name is
+partially matching a given regex.
+
+Example matches Y but not X
+    (matcher = recordDecl(isExpansionInFileMatching("AST.*"))
+  #include "ASTMatcher.h"
+  class X {};
+ASTMatcher.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isInstantiated0')"><a name="isInstantiated0Anchor">isInstantiated</a></td><td></td></tr>
-<tr><td colspan="4" class="doc" id="isInstantiated0"><pre>Matches declarations that are template instantiations or are inside
-template instantiations.
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isExpansionInMainFile0')"><a name="isExpansionInMainFile0Anchor">isExpansionInMainFile</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInMainFile0"><pre>Matches AST nodes that were expanded within the main-file.
 
-Given
-  template&lt;typename T&gt; void A(T t) { T i; }
-  A(0);
-  A(0U);
-functionDecl(isInstantiated())
-  matches 'A(int) {...};' and 'A(unsigned) {...}'.
+Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile())
+  #include &lt;Y.h&gt;
+  class X {};
+Y.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isExpansionInSystemHeader0')"><a name="isExpansionInSystemHeader0Anchor">isExpansionInSystemHeader</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInSystemHeader0"><pre>Matches AST nodes that were expanded within system-header-files.
+
+Example matches Y but not X
+    (matcher = recordDecl(isExpansionInSystemHeader())
+  #include &lt;SystemHeader.h&gt;
+  class X {};
+SystemHeader.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isImplicit0')"><a name="isImplicit0Anchor">isImplicit</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isImplicit0"><pre>Matches a declaration that has been implicitly added
+by the compiler (eg. implicit defaultcopy constructors).
 </pre></td></tr>
 
 
@@ -1858,7 +1919,7 @@
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt;</td><td class="name" onclick="toggle('hasName0')"><a name="hasName0Anchor">hasName</a></td><td>std::string Name</td></tr>
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt;</td><td class="name" onclick="toggle('hasName0')"><a name="hasName0Anchor">hasName</a></td><td>std::string  Name</td></tr>
 <tr><td colspan="4" class="doc" id="hasName0"><pre>Matches NamedDecl nodes that have the specified name.
 
 Supports specifying enclosing namespaces or classes by prefixing the name
@@ -1990,19 +2051,45 @@
 </pre></td></tr>
 
 
-<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isInTemplateInstantiation0')"><a name="isInTemplateInstantiation0Anchor">isInTemplateInstantiation</a></td><td></td></tr>
-<tr><td colspan="4" class="doc" id="isInTemplateInstantiation0"><pre>Matches statements inside of a template instantiation.
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isExpansionInFileMatching1')"><a name="isExpansionInFileMatching1Anchor">isExpansionInFileMatching</a></td><td>std::string RegExp</td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInFileMatching1"><pre>Matches AST nodes that were expanded within files whose name is
+partially matching a given regex.
 
-Given
-  int j;
-  template&lt;typename T&gt; void A(T t) { T i; j += 42;}
-  A(0);
-  A(0U);
-declStmt(isInTemplateInstantiation())
-  matches 'int i;' and 'unsigned i'.
-unless(stmt(isInTemplateInstantiation()))
-  will NOT match j += 42; as it's shared between the template definition and
-  instantiation.
+Example matches Y but not X
+    (matcher = recordDecl(isExpansionInFileMatching("AST.*"))
+  #include "ASTMatcher.h"
+  class X {};
+ASTMatcher.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isExpansionInMainFile1')"><a name="isExpansionInMainFile1Anchor">isExpansionInMainFile</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInMainFile1"><pre>Matches AST nodes that were expanded within the main-file.
+
+Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile())
+  #include &lt;Y.h&gt;
+  class X {};
+Y.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isExpansionInSystemHeader1')"><a name="isExpansionInSystemHeader1Anchor">isExpansionInSystemHeader</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInSystemHeader1"><pre>Matches AST nodes that were expanded within system-header-files.
+
+Example matches Y but not X
+    (matcher = recordDecl(isExpansionInSystemHeader())
+  #include &lt;SystemHeader.h&gt;
+  class X {};
+SystemHeader.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
 </pre></td></tr>
 
 
@@ -2061,6 +2148,48 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('isExpansionInFileMatching2')"><a name="isExpansionInFileMatching2Anchor">isExpansionInFileMatching</a></td><td>std::string RegExp</td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInFileMatching2"><pre>Matches AST nodes that were expanded within files whose name is
+partially matching a given regex.
+
+Example matches Y but not X
+    (matcher = recordDecl(isExpansionInFileMatching("AST.*"))
+  #include "ASTMatcher.h"
+  class X {};
+ASTMatcher.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('isExpansionInMainFile2')"><a name="isExpansionInMainFile2Anchor">isExpansionInMainFile</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInMainFile2"><pre>Matches AST nodes that were expanded within the main-file.
+
+Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile())
+  #include &lt;Y.h&gt;
+  class X {};
+Y.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('isExpansionInSystemHeader2')"><a name="isExpansionInSystemHeader2Anchor">isExpansionInSystemHeader</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isExpansionInSystemHeader2"><pre>Matches AST nodes that were expanded within system-header-files.
+
+Example matches Y but not X
+    (matcher = recordDecl(isExpansionInSystemHeader())
+  #include &lt;SystemHeader.h&gt;
+  class X {};
+SystemHeader.h:
+  class Y {};
+
+Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('equalsBoundNode2')"><a name="equalsBoundNode2Anchor">equalsBoundNode</a></td><td>std::string ID</td></tr>
 <tr><td colspan="4" class="doc" id="equalsBoundNode2"><pre>Matches if a node equals a previously bound node.
 
@@ -2084,6 +2213,16 @@
 </pre></td></tr>
 
 
+<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('voidType0')"><a name="voidType0Anchor">voidType</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="voidType0"><pre>Matches type void.
+
+Given
+ struct S { void func(); };
+functionDecl(returns(voidType()))
+  matches "void func();"
+</pre></td></tr>
+
+
 <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html">UnaryExprOrTypeTraitExpr</a>&gt;</td><td class="name" onclick="toggle('ofKind0')"><a name="ofKind0Anchor">ofKind</a></td><td>UnaryExprOrTypeTrait Kind</td></tr>
 <tr><td colspan="4" class="doc" id="ofKind0"><pre>Matches unary expressions of a certain kind.
 
@@ -2178,6 +2317,35 @@
 Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;
 </pre></td></tr>
 
+
+<tr><td>Matcher&lt;internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;&gt;</td><td class="name" onclick="toggle('isInstantiated0')"><a name="isInstantiated0Anchor">isInstantiated</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isInstantiated0"><pre>Matches declarations that are template instantiations or are inside
+template instantiations.
+
+Given
+  template&lt;typename T&gt; void A(T t) { T i; }
+  A(0);
+  A(0U);
+functionDecl(isInstantiated())
+  matches 'A(int) {...};' and 'A(unsigned) {...}'.
+</pre></td></tr>
+
+
+<tr><td>Matcher&lt;internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;&gt;</td><td class="name" onclick="toggle('isInTemplateInstantiation0')"><a name="isInTemplateInstantiation0Anchor">isInTemplateInstantiation</a></td><td></td></tr>
+<tr><td colspan="4" class="doc" id="isInTemplateInstantiation0"><pre>Matches statements inside of a template instantiation.
+
+Given
+  int j;
+  template&lt;typename T&gt; void A(T t) { T i; j += 42;}
+  A(0);
+  A(0U);
+declStmt(isInTemplateInstantiation())
+  matches 'int i;' and 'unsigned i'.
+unless(stmt(isInTemplateInstantiation()))
+  will NOT match j += 42; as it's shared between the template definition and
+  instantiation.
+</pre></td></tr>
+
 <!--END_NARROWING_MATCHERS -->
 </table>
 
diff --git a/docs/MSVCCompatibility.rst b/docs/MSVCCompatibility.rst
index 32efb76..73f01fc 100644
--- a/docs/MSVCCompatibility.rst
+++ b/docs/MSVCCompatibility.rst
@@ -72,17 +72,21 @@
 .. _/vm: http://msdn.microsoft.com/en-us/library/yad46a6z.aspx
 .. _pointer to a member of a virtual base class: http://llvm.org/PR15713
 
-* Debug info: :partial:`Minimal`.  Clang emits CodeView line tables into the
-  object file, similar to what MSVC emits when given the ``/Z7`` flag.
-  Microsoft's link.exe will read this information and use it to create a PDB,
+* Debug info: :partial:`Minimal`.  Clang emits both CodeView line tables
+  (similar to what MSVC emits when given the ``/Z7`` flag) and DWARF debug
+  information into the object file.
+  Microsoft's link.exe will transform the CodeView line tables into a PDB,
   enabling stack traces in all modern Windows debuggers.  Clang does not emit
-  any type info or description of variable layout.
+  any CodeView-compatible type info or description of variable layout.
+  Binaries linked with either binutils' ld or LLVM's lld should be usable with
+  GDB however sophisticated C++ expressions are likely to fail.
 
 * RTTI: :good:`Complete`.  Generation of RTTI data structures has been
   finished, along with support for the ``/GR`` flag.
 
-* Exceptions and SEH: :none:`Unstarted`.  Clang can parse both constructs, but
-  does not know how to emit compatible handlers.
+* Exceptions and SEH: :partial:`Minimal`.  Clang can parse both constructs, but
+  does not know how to emit compatible handlers.  Clang cannot throw exceptions
+  but it can rethrow them.
 
 * Thread-safe initialization of local statics: :none:`Unstarted`.  We are ABI
   compatible with MSVC 2013, which does not support thread-safe local statics.
diff --git a/docs/MemorySanitizer.rst b/docs/MemorySanitizer.rst
index 9d6c22d..007e086 100644
--- a/docs/MemorySanitizer.rst
+++ b/docs/MemorySanitizer.rst
@@ -16,8 +16,7 @@
 How to build
 ============
 
-Follow the `clang build instructions <../get_started.html>`_. CMake
-build is supported.
+Build LLVM/Clang with `CMake <http://llvm.org/docs/CMake.html>`_.
 
 Usage
 =====
@@ -111,32 +110,12 @@
 
 MemorySanitizer can track origins of unitialized values, similar to
 Valgrind's --track-origins option. This feature is enabled by
-``-fsanitize-memory-track-origins`` Clang option. With the code from
+``-fsanitize-memory-track-origins=2`` (or simply
+``-fsanitize-memory-track-origins``) Clang option. With the code from
 the example above,
 
 .. code-block:: console
 
-    % clang -fsanitize=memory -fsanitize-memory-track-origins -fno-omit-frame-pointer -g -O2 umr.cc
-    % ./a.out
-    WARNING: MemorySanitizer: use-of-uninitialized-value
-        #0 0x7f7893912f0b in main umr2.cc:6
-        #1 0x7f789249b76c in __libc_start_main libc-start.c:226
-
-      Uninitialized value was created by a heap allocation
-        #0 0x7f7893901cbd in operator new[](unsigned long) msan_new_delete.cc:44
-        #1 0x7f7893912e06 in main umr2.cc:4
-
-Origin tracking has proved to be very useful for debugging MemorySanitizer
-reports. It slows down program execution by a factor of 1.5x-2x on top
-of the usual MemorySanitizer slowdown.
-
-MemorySanitizer can provide even more information with
-``-fsanitize-memory-track-origins=2`` flag. In this mode reports
-include information about intermediate stores the uninitialized value went
-through.
-
-.. code-block:: console
-
     % cat umr2.cc
     #include <stdio.h>
 
@@ -163,6 +142,15 @@
         #0 0x7f7893901cbd in operator new[](unsigned long) msan_new_delete.cc:44
         #1 0x7f7893912e06 in main umr2.cc:4
 
+By default, MemorySanitizer collects both allocation points and all
+intermediate stores the uninitialized value went through.  Origin
+tracking has proved to be very useful for debugging MemorySanitizer
+reports. It slows down program execution by a factor of 1.5x-2x on top
+of the usual MemorySanitizer slowdown.
+
+Clang option ``-fsanitize-memory-track-origins=1`` enabled a slightly
+faster mode when MemorySanitizer collects only allocation points but
+not intermediate stores.
 
 Handling external code
 ============================
@@ -177,15 +165,7 @@
 to run MemorySanitizer-instrumented programs linked with
 uninstrumented libc. For example, the authors were able to bootstrap
 MemorySanitizer-instrumented Clang compiler by linking it with
-self-built instrumented libcxx (as a replacement for libstdc++).
-
-In the case when rebuilding all program dependencies with
-MemorySanitizer is problematic, an experimental MSanDR tool can be
-used. It is a DynamoRio-based tool that uses dynamic instrumentation
-to avoid false positives due to uninstrumented code. The tool simply
-marks memory from instrumented libraries as fully initialized. See
-`http://code.google.com/p/memory-sanitizer/wiki/Running#Running_with_the_dynamic_tool`
-for more information.
+self-built instrumented libc++ (as a replacement for libstdc++).
 
 Supported Platforms
 ===================
diff --git a/docs/Modules.rst b/docs/Modules.rst
index df471a4..1d4c1f4 100644
--- a/docs/Modules.rst
+++ b/docs/Modules.rst
@@ -207,6 +207,15 @@
 ``-fmodules-search-all``
   If a symbol is not found, search modules referenced in the current module maps but not imported for symbols, so the error message can reference the module by name.  Note that if the global module index has not been built before, this might take some time as it needs to build all the modules.  Note that this option doesn't apply in module builds, to avoid the recursion.
 
+``-fno-modules-implicit-maps``
+  Suppresses the implicit search for files called ``module.modulemap`` and similar. Instead, module files need to be explicitly specified via ``-fmodule-map-file`` or transitively used.
+
+``-fno-implicit-modules``
+  All modules used by the build must be specified with ``-fmodule-file``.
+
+``-fmodule-file=<file>``
+  Load the given precompiled module file.
+
 Module Semantics
 ================
 
diff --git a/docs/ReleaseNotes.rst b/docs/ReleaseNotes.rst
index daab804..5727a35 100644
--- a/docs/ReleaseNotes.rst
+++ b/docs/ReleaseNotes.rst
@@ -1,5 +1,5 @@
 =====================================
-Clang 3.6 (In-Progress) Release Notes
+Clang 3.7 (In-Progress) Release Notes
 =====================================
 
 .. contents::
@@ -10,15 +10,15 @@
 
 .. warning::
 
-   These are in-progress notes for the upcoming Clang 3.6 release. You may
+   These are in-progress notes for the upcoming Clang 3.7 release. You may
    prefer the `Clang 3.5 Release Notes
-   <http://llvm.org/releases/3.5/tools/clang/docs/ReleaseNotes.html>`_.
+   <http://llvm.org/releases/3.5.0/tools/clang/docs/ReleaseNotes.html>`_.
 
 Introduction
 ============
 
 This document contains the release notes for the Clang C/C++/Objective-C
-frontend, part of the LLVM Compiler Infrastructure, release 3.6. Here we
+frontend, part of the LLVM Compiler Infrastructure, release 3.7. Here we
 describe the status of Clang in some detail, including major
 improvements from the previous release and new feature work. For the
 general LLVM release notes, see `the LLVM
@@ -36,7 +36,7 @@
 the current one. To see the release notes for a specific release, please
 see the `releases page <http://llvm.org/releases/>`_.
 
-What's New in Clang 3.6?
+What's New in Clang 3.7?
 ========================
 
 Some of the major new features and improvements to Clang are listed
@@ -47,7 +47,7 @@
 Major New Features
 ------------------
 
-- A big one.
+- Feature ...
 
 
 Improvements to Clang's diagnostics
@@ -109,7 +109,7 @@
 Internal API Changes
 --------------------
 
-These are major API changes that have happened since the 3.5 release of
+These are major API changes that have happened since the 3.6 release of
 Clang. If upgrading an external codebase that uses Clang as a library,
 this section should help get you past the largest hurdles of upgrading.
 
diff --git a/docs/ThreadSanitizer.rst b/docs/ThreadSanitizer.rst
index a1d81e9..d1aeaa8 100644
--- a/docs/ThreadSanitizer.rst
+++ b/docs/ThreadSanitizer.rst
@@ -12,8 +12,7 @@
 How to build
 ------------
 
-Follow the `Clang build instructions <../get_started.html>`_.  CMake build is
-supported.
+Build LLVM/Clang with `CMake <http://llvm.org/docs/CMake.html>`_.
 
 Supported Platforms
 -------------------
diff --git a/docs/UsersManual.rst b/docs/UsersManual.rst
index 9d8e978..1685670 100644
--- a/docs/UsersManual.rst
+++ b/docs/UsersManual.rst
@@ -637,7 +637,7 @@
 Diagnostic Mappings
 ^^^^^^^^^^^^^^^^^^^
 
-All diagnostics are mapped into one of these 5 classes:
+All diagnostics are mapped into one of these 6 classes:
 
 -  Ignored
 -  Note
@@ -957,6 +957,8 @@
       ``unsigned-integer-overflow`` and ``vptr``.
    -  ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
       flow analysis.
+   -  ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
+      checks. Implies ``-flto``.
 
    The following more fine-grained checks are also available:
 
@@ -966,6 +968,8 @@
       ``true`` nor ``false``.
    -  ``-fsanitize=bounds``: Out of bounds array indexing, in cases
       where the array bound can be statically determined.
+   -  ``-fsanitize=cfi-vptr``: Use of an object whose vptr is of the
+      wrong dynamic type. Implies ``-flto``.
    -  ``-fsanitize=enum``: Load of a value of an enumerated type which
       is not in the range of representable values for that enumerated
       type.
@@ -1026,17 +1030,14 @@
       uninitialized bits came from. Slows down execution by additional
       1.5x-2x.
 
-      Possible values for level are 0 (off), 1 (default), 2. Level 2 adds more
-      sections to MemorySanitizer reports describing the order of memory stores
-      the uninitialized value went through. Beware, this mode may use a lot of
-      extra memory.
+      Possible values for level are 0 (off), 1, 2 (default). Level 2
+      adds more sections to MemorySanitizer reports describing the
+      order of memory stores the uninitialized value went
+      through. This mode may use extra memory in programs that copy
+      uninitialized memory a lot.
 
    Extra features of UndefinedBehaviorSanitizer:
 
-   -  ``-fno-sanitize-recover``: By default, after a sanitizer diagnoses
-      an issue, it will attempt to continue executing the program if there
-      is a reasonable behavior it can give to the faulting operation. This
-      option causes the program to abort instead.
    -  ``-fsanitize-undefined-trap-on-error``: Causes traps to be emitted
       rather than calls to runtime libraries when a problem is detected.
       This option is intended for use in cases where the sanitizer runtime
@@ -1056,6 +1057,17 @@
    program. The ``-fsanitize=undefined`` checks can be combined with other
    sanitizers.
 
+**-f[no-]sanitize-recover=check1,check2,...**
+
+   Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
+   If the check is fatal, program will halt after the first error
+   of this kind is detected and error report is printed.
+
+   By default, non-fatal checks are those enabled by UndefinedBehaviorSanitizer,
+   except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
+   sanitizers (e.g. :doc:`AddressSanitizer`) may not support recovery,
+   and always crash the program after the issue is detected.
+
 .. option:: -fno-assume-sane-operator-new
 
    Don't assume that the C++'s new operator is sane.
diff --git a/docs/conf.py b/docs/conf.py
index 7c2ef2a..9030c2c 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -48,9 +48,9 @@
 # built documents.
 #
 # The short X.Y version.
-version = '3.6'
+version = '3.7'
 # The full version, including alpha/beta/rc tags.
-release = '3.6'
+release = '3.7'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
diff --git a/docs/index.rst b/docs/index.rst
index bf2de7e..67bdf68 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -27,6 +27,7 @@
    DataFlowSanitizer
    LeakSanitizer
    SanitizerSpecialCaseList
+   ControlFlowIntegrity
    Modules
    MSVCCompatibility
    FAQ
diff --git a/docs/tools/dump_format_style.py b/docs/tools/dump_format_style.py
index 66bad8b..fdf03c6 100755
--- a/docs/tools/dump_format_style.py
+++ b/docs/tools/dump_format_style.py
@@ -17,6 +17,7 @@
   return re.sub(pattern, '%s', text, flags=re.S) % replacement
 
 def doxygen2rst(text):
+  text = re.sub(r'([^/\*])\*', r'\1\\*', text)
   text = re.sub(r'<tt>\s*(.*?)\s*<\/tt>', r'``\1``', text)
   text = re.sub(r'\\c ([^ ,;\.]+)', r'``\1``', text)
   text = re.sub(r'\\\w+ ', '', text)
diff --git a/examples/PrintFunctionNames/PrintFunctionNames.cpp b/examples/PrintFunctionNames/PrintFunctionNames.cpp
index e8a361d..b554cae 100644
--- a/examples/PrintFunctionNames/PrintFunctionNames.cpp
+++ b/examples/PrintFunctionNames/PrintFunctionNames.cpp
@@ -55,7 +55,7 @@
         return false;
       }
     }
-    if (args.size() && args[0] == "help")
+    if (!args.empty() && args[0] == "help")
       PrintHelp(llvm::errs());
 
     return true;
diff --git a/include/clang-c/Index.h b/include/clang-c/Index.h
index 6e3bd07..ac8ce1c 100644
--- a/include/clang-c/Index.h
+++ b/include/clang-c/Index.h
@@ -2126,7 +2126,7 @@
    */
   CXCursor_MSAsmStmt                     = 229,
 
-  /** \brief The null satement ";": C99 6.8.3p3.
+  /** \brief The null statement ";": C99 6.8.3p3.
    *
    * This cursor kind is used to describe the null statement.
    */
@@ -2141,7 +2141,7 @@
    */
   CXCursor_OMPParallelDirective          = 232,
 
-  /** \brief OpenMP simd directive.
+  /** \brief OpenMP SIMD directive.
    */
   CXCursor_OMPSimdDirective              = 233,
 
@@ -2209,11 +2209,11 @@
    */
   CXCursor_OMPAtomicDirective            = 249,
 
-  /** \brief OpenMP for simd directive.
+  /** \brief OpenMP for SIMD directive.
    */
   CXCursor_OMPForSimdDirective           = 250,
 
-  /** \brief OpenMP parallel for simd directive.
+  /** \brief OpenMP parallel for SIMD directive.
    */
   CXCursor_OMPParallelForSimdDirective   = 251,
 
@@ -2276,7 +2276,12 @@
    */
   CXCursor_ModuleImportDecl              = 600,
   CXCursor_FirstExtraDecl                = CXCursor_ModuleImportDecl,
-  CXCursor_LastExtraDecl                 = CXCursor_ModuleImportDecl
+  CXCursor_LastExtraDecl                 = CXCursor_ModuleImportDecl,
+
+  /**
+   * \brief A code completion overload candidate.
+   */
+  CXCursor_OverloadCandidate             = 700
 };
 
 /**
@@ -2849,7 +2854,7 @@
   CXCallingConv_X86Pascal = 5,
   CXCallingConv_AAPCS = 6,
   CXCallingConv_AAPCS_VFP = 7,
-  CXCallingConv_PnaclCall = 8,
+  /* Value 8 was PnaclCall, but it was never used, so it could safely be re-used. */
   CXCallingConv_IntelOclBicc = 9,
   CXCallingConv_X86_64Win64 = 10,
   CXCallingConv_X86_64SysV = 11,
@@ -3345,7 +3350,7 @@
 
 /**
  * \brief Represents the storage classes as declared in the source. CX_SC_Invalid
- * was added for the clase that the passed cursor in not a declaration.
+ * was added for the case that the passed cursor in not a declaration.
  */
 enum CX_StorageClass {
   CX_SC_Invalid,
diff --git a/include/clang/AST/ASTConsumer.h b/include/clang/AST/ASTConsumer.h
index 736a10b..b2730e4 100644
--- a/include/clang/AST/ASTConsumer.h
+++ b/include/clang/AST/ASTConsumer.h
@@ -129,11 +129,7 @@
   /// required.
   ///
   /// \param RD The class whose vtable was used.
-  ///
-  /// \param DefinitionRequired Whether a definition of this vtable is
-  /// required in this translation unit; otherwise, it is only needed if
-  /// it was actually used.
-  virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {}
+  virtual void HandleVTable(CXXRecordDecl *RD) {}
 
   /// \brief If the consumer is interested in entities getting modified after
   /// their initial creation, it should return a pointer to
diff --git a/include/clang/AST/ASTContext.h b/include/clang/AST/ASTContext.h
index ef87fa6..0bc0330 100644
--- a/include/clang/AST/ASTContext.h
+++ b/include/clang/AST/ASTContext.h
@@ -273,8 +273,6 @@
   /// \brief Declaration for the CUDA cudaConfigureCall function.
   FunctionDecl *cudaConfigureCallDecl;
 
-  TypeSourceInfo NullTypeSourceInfo;
-
   /// \brief Keeps track of all declaration attributes.
   ///
   /// Since so few decls have attrs, we keep them in a hash map instead of
@@ -2173,8 +2171,6 @@
   getTrivialTypeSourceInfo(QualType T, 
                            SourceLocation Loc = SourceLocation()) const;
 
-  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
-
   /// \brief Add a deallocation callback that will be invoked when the 
   /// ASTContext is destroyed.
   ///
@@ -2267,8 +2263,8 @@
   static unsigned NumImplicitDestructorsDeclared;
   
 private:
-  ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
-  void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
+  ASTContext(const ASTContext &) = delete;
+  void operator=(const ASTContext &) = delete;
 
 public:
   /// \brief Initialize built-in types.
diff --git a/include/clang/AST/ASTTypeTraits.h b/include/clang/AST/ASTTypeTraits.h
index efeac56..dc3c34f 100644
--- a/include/clang/AST/ASTTypeTraits.h
+++ b/include/clang/AST/ASTTypeTraits.h
@@ -23,6 +23,7 @@
 #include "clang/AST/TemplateBase.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/LLVM.h"
+#include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Support/AlignOf.h"
 
 namespace llvm {
@@ -90,6 +91,21 @@
   static ASTNodeKind getMostDerivedCommonAncestor(ASTNodeKind Kind1,
                                                   ASTNodeKind Kind2);
 
+  /// \brief Hooks for using ASTNodeKind as a key in a DenseMap.
+  struct DenseMapInfo {
+    // ASTNodeKind() is a good empty key because it is represented as a 0.
+    static inline ASTNodeKind getEmptyKey() { return ASTNodeKind(); }
+    // NKI_NumberOfKinds is not a valid value, so it is good for a
+    // tombstone key.
+    static inline ASTNodeKind getTombstoneKey() {
+      return ASTNodeKind(NKI_NumberOfKinds);
+    }
+    static unsigned getHashValue(const ASTNodeKind &Val) { return Val.KindId; }
+    static bool isEqual(const ASTNodeKind &LHS, const ASTNodeKind &RHS) {
+      return LHS.KindId == RHS.KindId;
+    }
+  };
+
 private:
   /// \brief Kind ids.
   ///
@@ -129,6 +145,8 @@
   template <class T> struct KindToKindId {
     static const NodeKindId Id = NKI_None;
   };
+  template <class T>
+  struct KindToKindId<const T> : KindToKindId<T> {};
 
   /// \brief Per kind info.
   struct KindInfo {
@@ -205,6 +223,14 @@
     return BaseConverter<T>::get(NodeKind, Storage.buffer);
   }
 
+  /// \brief Retrieve the stored node as type \c T.
+  ///
+  /// Similar to \c get(), but asserts that the type is what we are expecting.
+  template <typename T>
+  const T &getUnchecked() const {
+    return BaseConverter<T>::getUnchecked(NodeKind, Storage.buffer);
+  }
+
   ASTNodeKind getNodeKind() const { return NodeKind; }
 
   /// \brief Returns a pointer that identifies the stored AST node.
@@ -235,14 +261,15 @@
     return getMemoizationData() < Other.getMemoizationData();
   }
   bool operator==(const DynTypedNode &Other) const {
-    if (!NodeKind.isBaseOf(Other.NodeKind) &&
-        !Other.NodeKind.isBaseOf(NodeKind))
+    // DynTypedNode::create() stores the exact kind of the node in NodeKind.
+    // If they contain the same node, their NodeKind must be the same.
+    if (!NodeKind.isSame(Other.NodeKind))
       return false;
 
     // FIXME: Implement for other types.
-    if (ASTNodeKind::getFromNodeKind<QualType>().isBaseOf(NodeKind)) {
-      return *get<QualType>() == *Other.get<QualType>();
-    }
+    if (ASTNodeKind::getFromNodeKind<QualType>().isSame(NodeKind))
+      return getUnchecked<QualType>() == Other.getUnchecked<QualType>();
+
     assert(getMemoizationData() && Other.getMemoizationData());
     return getMemoizationData() == Other.getMemoizationData();
   }
@@ -258,10 +285,14 @@
   /// \brief Converter that uses dyn_cast<T> from a stored BaseT*.
   template <typename T, typename BaseT> struct DynCastPtrConverter {
     static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
-      if (ASTNodeKind::getFromNodeKind<BaseT>().isBaseOf(NodeKind))
-        return dyn_cast<T>(*reinterpret_cast<BaseT *const *>(Storage));
+      if (ASTNodeKind::getFromNodeKind<T>().isBaseOf(NodeKind))
+        return cast<T>(*reinterpret_cast<BaseT *const *>(Storage));
       return nullptr;
     }
+    static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
+      assert(ASTNodeKind::getFromNodeKind<T>().isBaseOf(NodeKind));
+      return *cast<T>(*reinterpret_cast<BaseT *const *>(Storage));
+    }
     static DynTypedNode create(const BaseT &Node) {
       DynTypedNode Result;
       Result.NodeKind = ASTNodeKind::getFromNode(Node);
@@ -278,6 +309,10 @@
         return *reinterpret_cast<T *const *>(Storage);
       return nullptr;
     }
+    static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
+      assert(ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind));
+      return **reinterpret_cast<T *const *>(Storage);
+    }
     static DynTypedNode create(const T &Node) {
       DynTypedNode Result;
       Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
@@ -294,6 +329,10 @@
         return reinterpret_cast<const T *>(Storage);
       return nullptr;
     }
+    static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
+      assert(ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind));
+      return *reinterpret_cast<const T *>(Storage);
+    }
     static DynTypedNode create(const T &Node) {
       DynTypedNode Result;
       Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
@@ -375,4 +414,12 @@
 } // end namespace ast_type_traits
 } // end namespace clang
 
+namespace llvm {
+
+template <>
+struct DenseMapInfo<clang::ast_type_traits::ASTNodeKind>
+    : clang::ast_type_traits::ASTNodeKind::DenseMapInfo {};
+
+}  // end namespace llvm
+
 #endif
diff --git a/include/clang/AST/ASTUnresolvedSet.h b/include/clang/AST/ASTUnresolvedSet.h
index 84b0842..9078a0e 100644
--- a/include/clang/AST/ASTUnresolvedSet.h
+++ b/include/clang/AST/ASTUnresolvedSet.h
@@ -76,7 +76,7 @@
   }
 
   void append(ASTContext &C, iterator I, iterator E) {
-    Decls.append(C, I.ir, E.ir);
+    Decls.append(C, I.I, E.I);
   }
 
   DeclAccessPair &operator[](unsigned I) { return Decls[I]; }
diff --git a/include/clang/AST/CanonicalType.h b/include/clang/AST/CanonicalType.h
index aa3c846..b25800b 100644
--- a/include/clang/AST/CanonicalType.h
+++ b/include/clang/AST/CanonicalType.h
@@ -16,8 +16,8 @@
 #define LLVM_CLANG_AST_CANONICALTYPE_H
 
 #include "clang/AST/Type.h"
+#include "llvm/ADT/iterator.h"
 #include "llvm/Support/Casting.h"
-#include <iterator>
 
 namespace clang {
 
@@ -80,7 +80,7 @@
   operator QualType() const { return Stored; }
 
   /// \brief Implicit conversion to bool.
-  LLVM_EXPLICIT operator bool() const { return !isNull(); }
+  explicit operator bool() const { return !isNull(); }
   
   bool isNull() const {
     return Stored.isNull();
@@ -381,93 +381,20 @@
 
 /// \brief Iterator adaptor that turns an iterator over canonical QualTypes
 /// into an iterator over CanQualTypes.
-template<typename InputIterator>
-class CanTypeIterator {
-  InputIterator Iter;
+template <typename InputIterator>
+struct CanTypeIterator
+    : llvm::iterator_adaptor_base<
+          CanTypeIterator<InputIterator>, InputIterator,
+          typename std::iterator_traits<InputIterator>::iterator_category,
+          CanQualType,
+          typename std::iterator_traits<InputIterator>::difference_type,
+          CanProxy<Type>, CanQualType> {
+  CanTypeIterator() {}
+  explicit CanTypeIterator(InputIterator Iter)
+      : CanTypeIterator::iterator_adaptor_base(std::move(Iter)) {}
 
-public:
-  typedef CanQualType    value_type;
-  typedef value_type     reference;
-  typedef CanProxy<Type> pointer;
-  typedef typename std::iterator_traits<InputIterator>::difference_type
-    difference_type;
-  typedef typename std::iterator_traits<InputIterator>::iterator_category
-    iterator_category;
-
-  CanTypeIterator() : Iter() { }
-  explicit CanTypeIterator(InputIterator Iter) : Iter(Iter) { }
-
-  // Input iterator
-  reference operator*() const {
-    return CanQualType::CreateUnsafe(*Iter);
-  }
-
-  pointer operator->() const;
-
-  CanTypeIterator &operator++() {
-    ++Iter;
-    return *this;
-  }
-
-  CanTypeIterator operator++(int) {
-    CanTypeIterator Tmp(*this);
-    ++Iter;
-    return Tmp;
-  }
-
-  friend bool operator==(const CanTypeIterator& X, const CanTypeIterator &Y) {
-    return X.Iter == Y.Iter;
-  }
-  friend bool operator!=(const CanTypeIterator& X, const CanTypeIterator &Y) {
-    return X.Iter != Y.Iter;
-  }
-
-  // Bidirectional iterator
-  CanTypeIterator &operator--() {
-    --Iter;
-    return *this;
-  }
-
-  CanTypeIterator operator--(int) {
-    CanTypeIterator Tmp(*this);
-    --Iter;
-    return Tmp;
-  }
-
-  // Random access iterator
-  reference operator[](difference_type n) const {
-    return CanQualType::CreateUnsafe(Iter[n]);
-  }
-
-  CanTypeIterator &operator+=(difference_type n) {
-    Iter += n;
-    return *this;
-  }
-
-  CanTypeIterator &operator-=(difference_type n) {
-    Iter -= n;
-    return *this;
-  }
-
-  friend CanTypeIterator operator+(CanTypeIterator X, difference_type n) {
-    X += n;
-    return X;
-  }
-
-  friend CanTypeIterator operator+(difference_type n, CanTypeIterator X) {
-    X += n;
-    return X;
-  }
-
-  friend CanTypeIterator operator-(CanTypeIterator X, difference_type n) {
-    X -= n;
-    return X;
-  }
-
-  friend difference_type operator-(const CanTypeIterator &X,
-                                   const CanTypeIterator &Y) {
-    return X - Y;
-  }
+  CanQualType operator*() const { return CanQualType::CreateUnsafe(*this->I); }
+  CanProxy<Type> operator->() const;
 };
 
 template<>
@@ -727,9 +654,8 @@
   return CanProxy<T>(*this);
 }
 
-template<typename InputIterator>
-typename CanTypeIterator<InputIterator>::pointer
-CanTypeIterator<InputIterator>::operator->() const {
+template <typename InputIterator>
+CanProxy<Type> CanTypeIterator<InputIterator>::operator->() const {
   return CanProxy<Type>(*this);
 }
 
diff --git a/include/clang/AST/CommentCommandTraits.h b/include/clang/AST/CommentCommandTraits.h
index ec6d83c..289f2fd 100644
--- a/include/clang/AST/CommentCommandTraits.h
+++ b/include/clang/AST/CommentCommandTraits.h
@@ -166,8 +166,8 @@
   static const CommandInfo *getBuiltinCommandInfo(unsigned CommandID);
 
 private:
-  CommandTraits(const CommandTraits &) LLVM_DELETED_FUNCTION;
-  void operator=(const CommandTraits &) LLVM_DELETED_FUNCTION;
+  CommandTraits(const CommandTraits &) = delete;
+  void operator=(const CommandTraits &) = delete;
 
   const CommandInfo *getRegisteredCommandInfo(StringRef Name) const;
   const CommandInfo *getRegisteredCommandInfo(unsigned CommandID) const;
diff --git a/include/clang/AST/CommentLexer.h b/include/clang/AST/CommentLexer.h
index d995df9..f190b93 100644
--- a/include/clang/AST/CommentLexer.h
+++ b/include/clang/AST/CommentLexer.h
@@ -221,8 +221,8 @@
 /// \brief Comment lexer.
 class Lexer {
 private:
-  Lexer(const Lexer &) LLVM_DELETED_FUNCTION;
-  void operator=(const Lexer &) LLVM_DELETED_FUNCTION;
+  Lexer(const Lexer &) = delete;
+  void operator=(const Lexer &) = delete;
 
   /// Allocator for strings that are semantic values of tokens and have to be
   /// computed (for example, resolved decimal character references).
diff --git a/include/clang/AST/CommentParser.h b/include/clang/AST/CommentParser.h
index 2c444f0..42bf4c9 100644
--- a/include/clang/AST/CommentParser.h
+++ b/include/clang/AST/CommentParser.h
@@ -28,8 +28,8 @@
 
 /// Doxygen comment parser.
 class Parser {
-  Parser(const Parser &) LLVM_DELETED_FUNCTION;
-  void operator=(const Parser &) LLVM_DELETED_FUNCTION;
+  Parser(const Parser &) = delete;
+  void operator=(const Parser &) = delete;
 
   friend class TextTokenRetokenizer;
 
diff --git a/include/clang/AST/CommentSema.h b/include/clang/AST/CommentSema.h
index 4ae6fe0..9b05d39 100644
--- a/include/clang/AST/CommentSema.h
+++ b/include/clang/AST/CommentSema.h
@@ -31,8 +31,8 @@
 class CommandTraits;
 
 class Sema {
-  Sema(const Sema &) LLVM_DELETED_FUNCTION;
-  void operator=(const Sema &) LLVM_DELETED_FUNCTION;
+  Sema(const Sema &) = delete;
+  void operator=(const Sema &) = delete;
 
   /// Allocator for AST nodes.
   llvm::BumpPtrAllocator &Allocator;
diff --git a/include/clang/AST/Decl.h b/include/clang/AST/Decl.h
index b946636..63ef796 100644
--- a/include/clang/AST/Decl.h
+++ b/include/clang/AST/Decl.h
@@ -179,14 +179,17 @@
                                     const PrintingPolicy &Policy,
                                     bool Qualified) const;
 
-  /// declarationReplaces - Determine whether this declaration, if
+  /// \brief Determine whether this declaration, if
   /// known to be well-formed within its context, will replace the
   /// declaration OldD if introduced into scope. A declaration will
   /// replace another declaration if, for example, it is a
   /// redeclaration of the same variable or function, but not if it is
   /// a declaration of a different kind (function vs. class) or an
   /// overloaded function.
-  bool declarationReplaces(NamedDecl *OldD) const;
+  ///
+  /// \param IsKnownNewer \c true if this declaration is known to be newer
+  /// than \p OldD (for instance, if this declaration is newly-created).
+  bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
 
   /// \brief Determine whether this declaration has linkage.
   bool hasLinkage() const;
@@ -535,8 +538,8 @@
 
 private:
   // Copy constructor and copy assignment are disabled.
-  QualifierInfo(const QualifierInfo&) LLVM_DELETED_FUNCTION;
-  QualifierInfo& operator=(const QualifierInfo&) LLVM_DELETED_FUNCTION;
+  QualifierInfo(const QualifierInfo&) = delete;
+  QualifierInfo& operator=(const QualifierInfo&) = delete;
 };
 
 /// \brief Represents a ValueDecl that came out of a declarator.
@@ -840,7 +843,7 @@
       return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
 
     // Global Named Register (GNU extension)
-    if (getStorageClass() == SC_Register && !isLocalVarDecl())
+    if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
       return false;
 
     // Return true for:  Auto, Register.
@@ -906,6 +909,11 @@
     return false;
   }
 
+  /// \brief Similar to isLocalVarDecl but also includes parameters.
+  bool isLocalVarDeclOrParm() const {
+    return isLocalVarDecl() || getKind() == Decl::ParmVar;
+  }
+
   /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
   /// excludes variables declared in blocks.
   bool isFunctionOrMethodVarDecl() const {
@@ -1477,6 +1485,9 @@
   bool IsLateTemplateParsed : 1;
   bool IsConstexpr : 1;
 
+  /// \brief Indicates if the function uses __try.
+  bool UsesSEHTry : 1;
+
   /// \brief Indicates if the function was a definition but its body was
   /// skipped.
   unsigned HasSkippedBody : 1;
@@ -1565,8 +1576,8 @@
       HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
       IsDefaulted(false), IsExplicitlyDefaulted(false),
       HasImplicitReturnZero(false), IsLateTemplateParsed(false),
-      IsConstexpr(isConstexprSpecified), HasSkippedBody(false),
-      EndRangeLoc(NameInfo.getEndLoc()),
+      IsConstexpr(isConstexprSpecified), UsesSEHTry(false),
+      HasSkippedBody(false), EndRangeLoc(NameInfo.getEndLoc()),
       TemplateOrSpecialization(),
       DNLoc(NameInfo.getInfo()) {}
 
@@ -1746,6 +1757,10 @@
   bool isConstexpr() const { return IsConstexpr; }
   void setConstexpr(bool IC) { IsConstexpr = IC; }
 
+  /// Whether this is a (C++11) constexpr function or constexpr constructor.
+  bool usesSEHTry() const { return UsesSEHTry; }
+  void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
+
   /// \brief Whether this function has been deleted.
   ///
   /// A function that is "deleted" (via the C++0x "= delete" syntax)
@@ -3274,6 +3289,10 @@
   /// intra-object-overflow bugs.
   bool mayInsertExtraPadding(bool EmitRemark = false) const;
 
+  /// Finds the first data member which has a name.
+  /// nullptr is returned if no named data member exists.
+  const FieldDecl *findFirstNamedDataMember() const;  
+
 private:
   /// \brief Deserialize just the fields.
   void LoadFieldsFromExternalStorage() const;
diff --git a/include/clang/AST/DeclBase.h b/include/clang/AST/DeclBase.h
index 984ab13..121bd00 100644
--- a/include/clang/AST/DeclBase.h
+++ b/include/clang/AST/DeclBase.h
@@ -18,6 +18,7 @@
 #include "clang/AST/DeclarationName.h"
 #include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/iterator.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/PrettyStackTrace.h"
@@ -1005,9 +1006,62 @@
   void print(raw_ostream &OS) const override;
 };
 
-typedef MutableArrayRef<NamedDecl *> DeclContextLookupResult;
+/// \brief The results of name lookup within a DeclContext. This is either a
+/// single result (with no stable storage) or a collection of results (with
+/// stable storage provided by the lookup table).
+class DeclContextLookupResult {
+  typedef ArrayRef<NamedDecl *> ResultTy;
+  ResultTy Result;
+  // If there is only one lookup result, it would be invalidated by
+  // reallocations of the name table, so store it separately.
+  NamedDecl *Single;
 
-typedef ArrayRef<NamedDecl *> DeclContextLookupConstResult;
+  static NamedDecl *const SingleElementDummyList;
+
+public:
+  DeclContextLookupResult() : Result(), Single() {}
+  DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
+      : Result(Result), Single() {}
+  DeclContextLookupResult(NamedDecl *Single)
+      : Result(SingleElementDummyList), Single(Single) {}
+
+  class iterator;
+  typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
+                                      std::random_access_iterator_tag,
+                                      NamedDecl *const> IteratorBase;
+  class iterator : public IteratorBase {
+    value_type SingleElement;
+
+  public:
+    iterator() : IteratorBase(), SingleElement() {}
+    explicit iterator(pointer Pos, value_type Single = nullptr)
+        : IteratorBase(Pos), SingleElement(Single) {}
+
+    reference operator*() const {
+      return SingleElement ? SingleElement : IteratorBase::operator*();
+    }
+  };
+  typedef iterator const_iterator;
+  typedef iterator::pointer pointer;
+  typedef iterator::reference reference;
+
+  iterator begin() const { return iterator(Result.begin(), Single); }
+  iterator end() const { return iterator(Result.end(), Single); }
+
+  bool empty() const { return Result.empty(); }
+  pointer data() const { return Single ? &Single : Result.data(); }
+  size_t size() const { return Single ? 1 : Result.size(); }
+  reference front() const { return Single ? Single : Result.front(); }
+  reference back() const { return Single ? Single : Result.back(); }
+  reference operator[](size_t N) const { return Single ? Single : Result[N]; }
+
+  // FIXME: Remove this from the interface
+  DeclContextLookupResult slice(size_t N) const {
+    DeclContextLookupResult Sliced = Result.slice(N);
+    Sliced.Single = Single;
+    return Sliced;
+  }
+};
 
 /// DeclContext - This is used only as base class of specific decl types that
 /// can act as declaration contexts. These decls are (only the top classes
@@ -1520,26 +1574,15 @@
   /// @brief Checks whether a declaration is in this context.
   bool containsDecl(Decl *D) const;
 
-  /// lookup_iterator - An iterator that provides access to the results
-  /// of looking up a name within this context.
-  typedef NamedDecl **lookup_iterator;
-
-  /// lookup_const_iterator - An iterator that provides non-mutable
-  /// access to the results of lookup up a name within this context.
-  typedef NamedDecl * const * lookup_const_iterator;
-
   typedef DeclContextLookupResult lookup_result;
-  typedef DeclContextLookupConstResult lookup_const_result;
+  typedef lookup_result::iterator lookup_iterator;
 
   /// lookup - Find the declarations (if any) with the given Name in
   /// this context. Returns a range of iterators that contains all of
   /// the declarations with this name, with object, function, member,
   /// and enumerator names preceding any tag name. Note that this
   /// routine will not look into parent contexts.
-  lookup_result lookup(DeclarationName Name);
-  lookup_const_result lookup(DeclarationName Name) const {
-    return const_cast<DeclContext*>(this)->lookup(Name);
-  }
+  lookup_result lookup(DeclarationName Name) const;
 
   /// \brief Find the declarations with the given name that are visible
   /// within this context; don't attempt to retrieve anything from an
@@ -1593,7 +1636,16 @@
   all_lookups_iterator noload_lookups_begin() const;
   all_lookups_iterator noload_lookups_end() const;
 
-  typedef llvm::iterator_range<UsingDirectiveDecl * const *> udir_range;
+  struct udir_iterator;
+  typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
+                                      std::random_access_iterator_tag,
+                                      UsingDirectiveDecl *> udir_iterator_base;
+  struct udir_iterator : udir_iterator_base {
+    udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
+    UsingDirectiveDecl *operator*() const;
+  };
+
+  typedef llvm::iterator_range<udir_iterator> udir_range;
 
   udir_range using_directives() const;
 
@@ -1672,7 +1724,7 @@
 
   template<decl_iterator (DeclContext::*Begin)() const,
            decl_iterator (DeclContext::*End)() const>
-  void buildLookupImpl(DeclContext *DCtx);
+  void buildLookupImpl(DeclContext *DCtx, bool Internal);
   void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
                                          bool Rediscoverable);
   void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
diff --git a/include/clang/AST/DeclCXX.h b/include/clang/AST/DeclCXX.h
index 062c152..ed6e2dc 100644
--- a/include/clang/AST/DeclCXX.h
+++ b/include/clang/AST/DeclCXX.h
@@ -826,7 +826,11 @@
   /// This value is used for lazy creation of default constructors.
   bool needsImplicitDefaultConstructor() const {
     return !data().UserDeclaredConstructor &&
-           !(data().DeclaredSpecialMembers & SMF_DefaultConstructor);
+           !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
+           // C++14 [expr.prim.lambda]p20:
+           //   The closure type associated with a lambda-expression has no
+           //   default constructor.
+           !isLambda();
   }
 
   /// \brief Determine whether this class has any user-declared constructors.
@@ -1089,8 +1093,7 @@
 
   /// \brief Get all conversion functions visible in current class,
   /// including conversion function templates.
-  std::pair<conversion_iterator, conversion_iterator>
-    getVisibleConversionFunctions();
+  llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
 
   /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
   /// which is a class with no user-declared constructors, no private
diff --git a/include/clang/AST/DeclContextInternals.h b/include/clang/AST/DeclContextInternals.h
index 9068c00..ff37758 100644
--- a/include/clang/AST/DeclContextInternals.h
+++ b/include/clang/AST/DeclContextInternals.h
@@ -142,31 +142,29 @@
   /// represents.
   DeclContext::lookup_result getLookupResult() {
     if (isNull())
-      return DeclContext::lookup_result(DeclContext::lookup_iterator(nullptr),
-                                        DeclContext::lookup_iterator(nullptr));
+      return DeclContext::lookup_result();
 
     // If we have a single NamedDecl, return it.
-    if (getAsDecl()) {
+    if (NamedDecl *ND = getAsDecl()) {
       assert(!isNull() && "Empty list isn't allowed");
 
       // Data is a raw pointer to a NamedDecl*, return it.
-      void *Ptr = &Data;
-      return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1);
+      return DeclContext::lookup_result(ND);
     }
 
     assert(getAsVector() && "Must have a vector at this point");
     DeclsTy &Vector = *getAsVector();
 
     // Otherwise, we have a range result.
-    return DeclContext::lookup_result(Vector.begin(), Vector.end());
+    return DeclContext::lookup_result(Vector);
   }
 
   /// HandleRedeclaration - If this is a redeclaration of an existing decl,
   /// replace the old one with D and return true.  Otherwise return false.
-  bool HandleRedeclaration(NamedDecl *D) {
+  bool HandleRedeclaration(NamedDecl *D, bool IsKnownNewer) {
     // Most decls only have one entry in their list, special case it.
     if (NamedDecl *OldD = getAsDecl()) {
-      if (!D->declarationReplaces(OldD))
+      if (!D->declarationReplaces(OldD, IsKnownNewer))
         return false;
       setOnlyValue(D);
       return true;
@@ -177,7 +175,7 @@
     for (DeclsTy::iterator OD = Vec.begin(), ODEnd = Vec.end();
          OD != ODEnd; ++OD) {
       NamedDecl *OldD = *OD;
-      if (D->declarationReplaces(OldD)) {
+      if (D->declarationReplaces(OldD, IsKnownNewer)) {
         *OD = D;
         return true;
       }
diff --git a/include/clang/AST/DeclLookups.h b/include/clang/AST/DeclLookups.h
index d2016af..eba2266 100644
--- a/include/clang/AST/DeclLookups.h
+++ b/include/clang/AST/DeclLookups.h
@@ -75,7 +75,10 @@
   if (StoredDeclsMap *Map = Primary->buildLookup())
     return lookups_range(all_lookups_iterator(Map->begin(), Map->end()),
                          all_lookups_iterator(Map->end(), Map->end()));
-  return lookups_range();
+
+  // Synthesize an empty range. This requires that two default constructed
+  // versions of these iterators form a valid empty range.
+  return lookups_range(all_lookups_iterator(), all_lookups_iterator());
 }
 
 inline DeclContext::all_lookups_iterator DeclContext::lookups_begin() const {
@@ -91,7 +94,10 @@
   if (StoredDeclsMap *Map = Primary->getLookupPtr())
     return lookups_range(all_lookups_iterator(Map->begin(), Map->end()),
                          all_lookups_iterator(Map->end(), Map->end()));
-  return lookups_range();
+
+  // Synthesize an empty range. This requires that two default constructed
+  // versions of these iterators form a valid empty range.
+  return lookups_range(all_lookups_iterator(), all_lookups_iterator());
 }
 
 inline
diff --git a/include/clang/AST/DeclObjC.h b/include/clang/AST/DeclObjC.h
index 55d4b0f..97ce132 100644
--- a/include/clang/AST/DeclObjC.h
+++ b/include/clang/AST/DeclObjC.h
@@ -33,8 +33,8 @@
 class CXXCtorInitializer;
 
 class ObjCListBase {
-  ObjCListBase(const ObjCListBase &) LLVM_DELETED_FUNCTION;
-  void operator=(const ObjCListBase &) LLVM_DELETED_FUNCTION;
+  ObjCListBase(const ObjCListBase &) = delete;
+  void operator=(const ObjCListBase &) = delete;
 protected:
   /// List is an array of pointers to objects that are not owned by this object.
   void **List;
diff --git a/include/clang/AST/DeclTemplate.h b/include/clang/AST/DeclTemplate.h
index 9283d2d..39b5208 100644
--- a/include/clang/AST/DeclTemplate.h
+++ b/include/clang/AST/DeclTemplate.h
@@ -158,8 +158,8 @@
   /// argument list.
   unsigned NumArguments;
 
-  TemplateArgumentList(const TemplateArgumentList &Other) LLVM_DELETED_FUNCTION;
-  void operator=(const TemplateArgumentList &Other) LLVM_DELETED_FUNCTION;
+  TemplateArgumentList(const TemplateArgumentList &Other) = delete;
+  void operator=(const TemplateArgumentList &Other) = delete;
 
   TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs,
                        bool Owned)
@@ -545,47 +545,32 @@
   template <typename EntryType> struct SpecEntryTraits {
     typedef EntryType DeclType;
 
-    static DeclType *getMostRecentDecl(EntryType *D) {
-      return D->getMostRecentDecl();
+    static DeclType *getDecl(EntryType *D) {
+      return D;
+    }
+    static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
+      return D->getTemplateArgs().asArray();
     }
   };
 
-  template <typename EntryType,
-            typename _SETraits = SpecEntryTraits<EntryType>,
-            typename _DeclType = typename _SETraits::DeclType>
-  class SpecIterator : public std::iterator<std::forward_iterator_tag,
-                                            _DeclType*, ptrdiff_t,
-                                            _DeclType*, _DeclType*> {
-    typedef _SETraits SETraits;
-    typedef _DeclType DeclType;
-
-    typedef typename llvm::FoldingSetVector<EntryType>::iterator
-      SetIteratorType;
-
-    SetIteratorType SetIter;
-
-  public:
-    SpecIterator() : SetIter() {}
-    SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
+  template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
+            typename DeclType = typename SETraits::DeclType>
+  struct SpecIterator
+      : llvm::iterator_adaptor_base<
+            SpecIterator<EntryType, SETraits, DeclType>,
+            typename llvm::FoldingSetVector<EntryType>::iterator,
+            typename std::iterator_traits<typename llvm::FoldingSetVector<
+                EntryType>::iterator>::iterator_category,
+            DeclType *, ptrdiff_t, DeclType *, DeclType *> {
+    SpecIterator() {}
+    explicit SpecIterator(
+        typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
+        : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
 
     DeclType *operator*() const {
-      return SETraits::getMostRecentDecl(&*SetIter);
+      return SETraits::getDecl(&*this->I)->getMostRecentDecl();
     }
     DeclType *operator->() const { return **this; }
-
-    SpecIterator &operator++() { ++SetIter; return *this; }
-    SpecIterator operator++(int) {
-      SpecIterator tmp(*this);
-      ++(*this);
-      return tmp;
-    }
-
-    bool operator==(SpecIterator Other) const {
-      return SetIter == Other.SetIter;
-    }
-    bool operator!=(SpecIterator Other) const {
-      return SetIter != Other.SetIter;
-    }
   };
 
   template <typename EntryType>
@@ -598,6 +583,10 @@
   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
                          ArrayRef<TemplateArgument> Args, void *&InsertPos);
 
+  template <class Derived, class EntryType>
+  void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
+                             EntryType *Entry, void *InsertPos);
+
   struct CommonBase {
     CommonBase() : InstantiatedFromMember(nullptr, false) { }
 
@@ -737,9 +726,12 @@
 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
   typedef FunctionDecl DeclType;
 
-  static DeclType *
-  getMostRecentDecl(FunctionTemplateSpecializationInfo *I) {
-    return I->Function->getMostRecentDecl();
+  static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
+    return I->Function;
+  }
+  static ArrayRef<TemplateArgument>
+  getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
+    return I->TemplateArguments->asArray();
   }
 };
 
@@ -788,9 +780,6 @@
 
   friend class FunctionDecl;
 
-  /// \brief Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
-
   /// \brief Retrieve the set of function template specializations of this
   /// function template.
   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
@@ -804,6 +793,9 @@
                          void *InsertPos);
 
 public:
+  /// \brief Load any lazily-loaded specializations from the external source.
+  void LoadLazySpecializations() const;
+
   /// Get the underlying function declaration of the template.
   FunctionDecl *getTemplatedDecl() const {
     return static_cast<FunctionDecl*>(TemplatedDecl);
@@ -843,6 +835,15 @@
        static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   }
 
+  FunctionTemplateDecl *getMostRecentDecl() {
+    return cast<FunctionTemplateDecl>(
+        static_cast<RedeclarableTemplateDecl *>(this)
+            ->getMostRecentDecl());
+  }
+  const FunctionTemplateDecl *getMostRecentDecl() const {
+    return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
+  }
+
   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
     return cast_or_null<FunctionTemplateDecl>(
              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
@@ -903,7 +904,7 @@
 /// This class is inheritedly privately by different kinds of template
 /// parameters and is not part of the Decl hierarchy. Just a facility.
 class TemplateParmPosition {
-  TemplateParmPosition() LLVM_DELETED_FUNCTION;
+  TemplateParmPosition() = delete;
 
 protected:
   TemplateParmPosition(unsigned D, unsigned P)
@@ -1827,9 +1828,6 @@
     uint32_t *LazySpecializations;
   };
 
-  /// \brief Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
-
   /// \brief Retrieve the set of specializations of this class template.
   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
   getSpecializations() const;
@@ -1851,6 +1849,9 @@
   }
 
 public:
+  /// \brief Load any lazily-loaded specializations from the external source.
+  void LoadLazySpecializations() const;
+
   /// \brief Get the underlying class declarations of the template.
   CXXRecordDecl *getTemplatedDecl() const {
     return static_cast<CXXRecordDecl *>(TemplatedDecl);
@@ -2662,9 +2663,6 @@
     uint32_t *LazySpecializations;
   };
 
-  /// \brief Load any lazily-loaded specializations from the external source.
-  void LoadLazySpecializations() const;
-
   /// \brief Retrieve the set of specializations of this variable template.
   llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
   getSpecializations() const;
@@ -2686,6 +2684,9 @@
   }
 
 public:
+  /// \brief Load any lazily-loaded specializations from the external source.
+  void LoadLazySpecializations() const;
+
   /// \brief Get the underlying variable declarations of the template.
   VarDecl *getTemplatedDecl() const {
     return static_cast<VarDecl *>(TemplatedDecl);
@@ -2739,6 +2740,14 @@
               this)->getPreviousDecl());
   }
 
+  VarTemplateDecl *getMostRecentDecl() {
+    return cast<VarTemplateDecl>(
+        static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
+  }
+  const VarTemplateDecl *getMostRecentDecl() const {
+    return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
+  }
+
   VarTemplateDecl *getInstantiatedFromMemberTemplate() {
     return cast_or_null<VarTemplateDecl>(
         RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
diff --git a/include/clang/AST/DeclarationName.h b/include/clang/AST/DeclarationName.h
index 49e51e0..ec0fb0b 100644
--- a/include/clang/AST/DeclarationName.h
+++ b/include/clang/AST/DeclarationName.h
@@ -184,7 +184,7 @@
 
   // operator bool() - Evaluates true when this declaration name is
   // non-empty.
-  LLVM_EXPLICIT operator bool() const {
+  explicit operator bool() const {
     return ((Ptr & PtrMask) != 0) ||
            (reinterpret_cast<IdentifierInfo *>(Ptr & ~PtrMask));
   }
@@ -344,8 +344,8 @@
   CXXOperatorIdName *CXXOperatorNames; // Operator names
   void *CXXLiteralOperatorNames; // Actually a CXXOperatorIdName*
 
-  DeclarationNameTable(const DeclarationNameTable&) LLVM_DELETED_FUNCTION;
-  void operator=(const DeclarationNameTable&) LLVM_DELETED_FUNCTION;
+  DeclarationNameTable(const DeclarationNameTable&) = delete;
+  void operator=(const DeclarationNameTable&) = delete;
 
 public:
   DeclarationNameTable(const ASTContext &C);
diff --git a/include/clang/AST/DependentDiagnostic.h b/include/clang/AST/DependentDiagnostic.h
index 6306679..8e038c8 100644
--- a/include/clang/AST/DependentDiagnostic.h
+++ b/include/clang/AST/DependentDiagnostic.h
@@ -178,7 +178,8 @@
     = static_cast<DependentStoredDeclsMap*>(getPrimaryContext()->getLookupPtr());
 
   if (!Map)
-    return ddiag_range();
+    // Return an empty range using the always-end default constructor.
+    return ddiag_range(ddiag_iterator(), ddiag_iterator());
 
   return ddiag_range(ddiag_iterator(Map->FirstDiagnostic), ddiag_iterator());
 }
diff --git a/include/clang/AST/EvaluatedExprVisitor.h b/include/clang/AST/EvaluatedExprVisitor.h
index 12c4fcc..59de104 100644
--- a/include/clang/AST/EvaluatedExprVisitor.h
+++ b/include/clang/AST/EvaluatedExprVisitor.h
@@ -56,6 +56,17 @@
     return this->Visit(E->getChosenSubExpr());
   }
 
+  void VisitGenericSelectionExpr(GenericSelectionExpr *E) {
+    // The controlling expression of a generic selection is not evaluated.
+
+    // Don't visit either child expression if the condition is type-dependent.
+    if (E->isResultDependent())
+      return;
+    // Only the selected subexpression matters; the other subexpressions and the
+    // controlling expression are not evaluated.
+    return this->Visit(E->getResultExpr());
+  }
+
   void VisitDesignatedInitExpr(DesignatedInitExpr *E) {
     // Only the actual initializer matters; the designators are all constant
     // expressions.
diff --git a/include/clang/AST/Expr.h b/include/clang/AST/Expr.h
index d94e225..c8f121b 100644
--- a/include/clang/AST/Expr.h
+++ b/include/clang/AST/Expr.h
@@ -586,8 +586,13 @@
 
   /// HasSideEffects - This routine returns true for all those expressions
   /// which have any effect other than producing a value. Example is a function
-  /// call, volatile variable read, or throwing an exception.
-  bool HasSideEffects(const ASTContext &Ctx) const;
+  /// call, volatile variable read, or throwing an exception. If
+  /// IncludePossibleEffects is false, this call treats certain expressions with
+  /// potential side effects (such as function call-like expressions,
+  /// instantiation-dependent expressions, or invocations from a macro) as not
+  /// having side effects.
+  bool HasSideEffects(const ASTContext &Ctx,
+                      bool IncludePossibleEffects = true) const;
 
   /// \brief Determine whether this expression involves a call to any function
   /// that is not trivial.
@@ -886,9 +891,9 @@
 ///   DeclRefExprBits.HasTemplateKWAndArgsInfo:
 ///       Specifies when this declaration reference expression has an explicit
 ///       C++ template keyword and/or template argument list.
-///   DeclRefExprBits.RefersToEnclosingLocal
+///   DeclRefExprBits.RefersToEnclosingVariableOrCapture
 ///       Specifies when this declaration reference expression (validly)
-///       refers to a local variable from a different function.
+///       refers to an enclosed local or a captured variable.
 class DeclRefExpr : public Expr {
   /// \brief The declaration that we are referencing.
   ValueDecl *D;
@@ -933,7 +938,7 @@
   DeclRefExpr(const ASTContext &Ctx,
               NestedNameSpecifierLoc QualifierLoc,
               SourceLocation TemplateKWLoc,
-              ValueDecl *D, bool refersToEnclosingLocal,
+              ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
               const DeclarationNameInfo &NameInfo,
               NamedDecl *FoundD,
               const TemplateArgumentListInfo *TemplateArgs,
@@ -948,7 +953,7 @@
   void computeDependence(const ASTContext &C);
 
 public:
-  DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T,
+  DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
               ExprValueKind VK, SourceLocation L,
               const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
     : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
@@ -957,20 +962,22 @@
     DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
     DeclRefExprBits.HasFoundDecl = 0;
     DeclRefExprBits.HadMultipleCandidates = 0;
-    DeclRefExprBits.RefersToEnclosingLocal = refersToEnclosingLocal;
+    DeclRefExprBits.RefersToEnclosingVariableOrCapture =
+        RefersToEnclosingVariableOrCapture;
     computeDependence(D->getASTContext());
   }
 
   static DeclRefExpr *
   Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
-         SourceLocation TemplateKWLoc, ValueDecl *D, bool isEnclosingLocal,
-         SourceLocation NameLoc, QualType T, ExprValueKind VK,
-         NamedDecl *FoundD = nullptr,
+         SourceLocation TemplateKWLoc, ValueDecl *D,
+         bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
+         QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
          const TemplateArgumentListInfo *TemplateArgs = nullptr);
 
   static DeclRefExpr *
   Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
-         SourceLocation TemplateKWLoc, ValueDecl *D, bool isEnclosingLocal,
+         SourceLocation TemplateKWLoc, ValueDecl *D,
+         bool RefersToEnclosingVariableOrCapture,
          const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
          NamedDecl *FoundD = nullptr,
          const TemplateArgumentListInfo *TemplateArgs = nullptr);
@@ -1144,10 +1151,10 @@
     DeclRefExprBits.HadMultipleCandidates = V;
   }
 
-  /// Does this DeclRefExpr refer to a local declaration from an
-  /// enclosing function scope?
-  bool refersToEnclosingLocal() const {
-    return DeclRefExprBits.RefersToEnclosingLocal;
+  /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
+  /// variable?
+  bool refersToEnclosingVariableOrCapture() const {
+    return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
   }
 
   static bool classof(const Stmt *T) {
@@ -1232,8 +1239,8 @@
 
   bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
 
-  APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION;
-  void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION;
+  APNumericStorage(const APNumericStorage &) = delete;
+  void operator=(const APNumericStorage &) = delete;
 
 protected:
   APNumericStorage() : VAL(0), BitWidth(0) { }
@@ -1990,18 +1997,7 @@
 
   UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
                            QualType resultType, SourceLocation op,
-                           SourceLocation rp) :
-      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
-           false, // Never type-dependent (C++ [temp.dep.expr]p3).
-           // Value-dependent if the argument is type-dependent.
-           E->isTypeDependent(),
-           E->isInstantiationDependent(),
-           E->containsUnexpandedParameterPack()),
-      OpLoc(op), RParenLoc(rp) {
-    UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
-    UnaryExprOrTypeTraitExprBits.IsType = false;
-    Argument.Ex = E;
-  }
+                           SourceLocation rp);
 
   /// \brief Construct an empty sizeof/alignof expression.
   explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
@@ -2280,7 +2276,7 @@
   /// getCallReturnType - Get the return type of the call expr. This is not
   /// always the type of the expr itself, if the return type is a reference
   /// type.
-  QualType getCallReturnType() const;
+  QualType getCallReturnType(const ASTContext &Ctx) const;
 
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
diff --git a/include/clang/AST/ExprCXX.h b/include/clang/AST/ExprCXX.h
index 040fbe7..d1a6063 100644
--- a/include/clang/AST/ExprCXX.h
+++ b/include/clang/AST/ExprCXX.h
@@ -17,10 +17,10 @@
 
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/LambdaCapture.h"
 #include "clang/AST/TemplateBase.h"
 #include "clang/AST/UnresolvedSet.h"
 #include "clang/Basic/ExpressionTraits.h"
-#include "clang/AST/LambdaCapture.h"
 #include "clang/Basic/TypeTraits.h"
 #include "llvm/Support/Compiler.h"
 
@@ -86,6 +86,13 @@
   /// of the right bracket.
   SourceLocation getOperatorLoc() const { return getRParenLoc(); }
 
+  SourceLocation getExprLoc() const LLVM_READONLY {
+    return (Operator < OO_Plus || Operator >= OO_Arrow ||
+            Operator == OO_PlusPlus || Operator == OO_MinusMinus)
+               ? getLocStart()
+               : getOperatorLoc();
+  }
+
   SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
   SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
   SourceRange getSourceRange() const { return Range; }
@@ -1127,7 +1134,7 @@
                                   ConstructionKind ConstructKind,
                                   SourceRange ParenOrBraceRange);
 
-  CXXConstructorDecl* getConstructor() const { return Constructor; }
+  CXXConstructorDecl *getConstructor() const { return Constructor; }
   void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
 
   SourceLocation getLocation() const { return Loc; }
@@ -1404,14 +1411,13 @@
   unsigned *getArrayIndexStarts() const {
     return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
   }
-  
+
   /// \brief Retrieve the complete set of array-index variables.
   VarDecl **getArrayIndexVars() const {
-    unsigned ArrayIndexSize =
-        llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
-                                 llvm::alignOf<VarDecl*>());
+    unsigned ArrayIndexSize = llvm::RoundUpToAlignment(
+        sizeof(unsigned) * (NumCaptures + 1), llvm::alignOf<VarDecl *>());
     return reinterpret_cast<VarDecl **>(
-        reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
+        reinterpret_cast<char *>(getArrayIndexStarts()) + ArrayIndexSize);
   }
 
 public:
@@ -1686,6 +1692,10 @@
   ///   not be done, the deallocation function shall not be called,
   ///   and the value of the new-expression shall be null.
   ///
+  /// C++ DR1748:
+  ///   If the allocation function is a reserved placement allocation
+  ///   function that returns null, the behavior is undefined.
+  ///
   /// An allocation function is not allowed to return null unless it
   /// has a non-throwing exception-specification.  The '03 rule is
   /// identical except that the definition of a non-throwing
@@ -2915,8 +2925,9 @@
 
   SourceLocation getLocStart() const LLVM_READONLY;
   SourceLocation getLocEnd() const LLVM_READONLY {
-    assert(RParenLoc.isValid() || NumArgs == 1);
-    return RParenLoc.isValid() ? RParenLoc : getArg(0)->getLocEnd();
+    if (!RParenLoc.isValid() && NumArgs > 0)
+      return getArg(NumArgs - 1)->getLocEnd();
+    return RParenLoc;
   }
 
   static bool classof(const Stmt *T) {
diff --git a/include/clang/AST/ExprObjC.h b/include/clang/AST/ExprObjC.h
index 817c0cc..f296e8f 100644
--- a/include/clang/AST/ExprObjC.h
+++ b/include/clang/AST/ExprObjC.h
@@ -124,6 +124,15 @@
   
   // Iterators
   child_range children() { return child_range(&SubExpr, &SubExpr+1); }
+
+  typedef ConstExprIterator const_arg_iterator;
+
+  const_arg_iterator arg_begin() const {
+    return reinterpret_cast<Stmt const * const*>(&SubExpr);
+  }
+  const_arg_iterator arg_end() const {
+    return reinterpret_cast<Stmt const * const*>(&SubExpr + 1);
+  }
   
   friend class ASTStmtReader;
 };
diff --git a/include/clang/AST/ExternalASTSource.h b/include/clang/AST/ExternalASTSource.h
index ff1d180..f35639c 100644
--- a/include/clang/AST/ExternalASTSource.h
+++ b/include/clang/AST/ExternalASTSource.h
@@ -344,7 +344,7 @@
   /// \brief Whether this pointer is non-NULL.
   ///
   /// This operation does not require the AST node to be deserialized.
-  LLVM_EXPLICIT operator bool() const { return Ptr != 0; }
+  explicit operator bool() const { return Ptr != 0; }
 
   /// \brief Whether this pointer is non-NULL.
   ///
diff --git a/include/clang/AST/Mangle.h b/include/clang/AST/Mangle.h
index cbe08a1..20ce32e 100644
--- a/include/clang/AST/Mangle.h
+++ b/include/clang/AST/Mangle.h
@@ -132,12 +132,18 @@
   virtual void mangleDynamicAtExitDestructor(const VarDecl *D,
                                              raw_ostream &) = 0;
 
+  virtual void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
+                                         raw_ostream &Out) = 0;
+
   /// Generates a unique string for an externally visible type for use with TBAA
   /// or type uniquing.
   /// TODO: Extend this to internal types by generating names that are unique
   /// across translation units so it can be used with LTO.
   virtual void mangleTypeName(QualType T, raw_ostream &) = 0;
 
+  virtual void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
+                                     raw_ostream &) = 0;
+
   /// @}
 };
 
diff --git a/include/clang/AST/NestedNameSpecifier.h b/include/clang/AST/NestedNameSpecifier.h
index 518f123..4da17b0 100644
--- a/include/clang/AST/NestedNameSpecifier.h
+++ b/include/clang/AST/NestedNameSpecifier.h
@@ -102,7 +102,7 @@
       Specifier(Other.Specifier) {
   }
 
-  void operator=(const NestedNameSpecifier &) LLVM_DELETED_FUNCTION;
+  void operator=(const NestedNameSpecifier &) = delete;
 
   /// \brief Either find or insert the given nested name specifier
   /// mockup in the given context.
@@ -245,7 +245,7 @@
 
   /// \brief Evalutes true when this nested-name-specifier location is
   /// non-empty.
-  LLVM_EXPLICIT operator bool() const { return Qualifier; }
+  explicit operator bool() const { return Qualifier; }
 
   /// \brief Evalutes true when this nested-name-specifier location is
   /// empty.
diff --git a/include/clang/AST/RecordLayout.h b/include/clang/AST/RecordLayout.h
index 7b77998..f9240f2 100644
--- a/include/clang/AST/RecordLayout.h
+++ b/include/clang/AST/RecordLayout.h
@@ -163,8 +163,8 @@
 
   void Destroy(ASTContext &Ctx);
   
-  ASTRecordLayout(const ASTRecordLayout &) LLVM_DELETED_FUNCTION;
-  void operator=(const ASTRecordLayout &) LLVM_DELETED_FUNCTION;
+  ASTRecordLayout(const ASTRecordLayout &) = delete;
+  void operator=(const ASTRecordLayout &) = delete;
 public:
 
   /// getAlignment - Get the record alignment in characters.
diff --git a/include/clang/AST/RecursiveASTVisitor.h b/include/clang/AST/RecursiveASTVisitor.h
index a1d3618..ff8e74b 100644
--- a/include/clang/AST/RecursiveASTVisitor.h
+++ b/include/clang/AST/RecursiveASTVisitor.h
@@ -2032,12 +2032,20 @@
 // to the syntactic form.
 template <typename Derived>
 bool RecursiveASTVisitor<Derived>::TraverseInitListExpr(InitListExpr *S) {
-  if (InitListExpr *Syn = S->getSyntacticForm())
-    S = Syn;
-  TRY_TO(WalkUpFromInitListExpr(S));
-  // All we need are the default actions.  FIXME: use a helper function.
-  for (Stmt::child_range range = S->children(); range; ++range) {
-    TRY_TO(TraverseStmt(*range));
+  InitListExpr *Syn = S->isSemanticForm() ? S->getSyntacticForm() : S;
+  if (Syn) {
+    TRY_TO(WalkUpFromInitListExpr(Syn));
+    // All we need are the default actions.  FIXME: use a helper function.
+    for (Stmt::child_range range = Syn->children(); range; ++range) {
+      TRY_TO(TraverseStmt(*range));
+    }
+  }
+  InitListExpr *Sem = S->isSemanticForm() ? S : S->getSemanticForm();
+  if (Sem) {
+    TRY_TO(WalkUpFromInitListExpr(Sem));
+    for (Stmt::child_range range = Sem->children(); range; ++range) {
+      TRY_TO(TraverseStmt(*range));
+    }
   }
   return true;
 }
diff --git a/include/clang/AST/Stmt.h b/include/clang/AST/Stmt.h
index 380c3b9..465bcea 100644
--- a/include/clang/AST/Stmt.h
+++ b/include/clang/AST/Stmt.h
@@ -212,7 +212,7 @@
     unsigned HasTemplateKWAndArgsInfo : 1;
     unsigned HasFoundDecl : 1;
     unsigned HadMultipleCandidates : 1;
-    unsigned RefersToEnclosingLocal : 1;
+    unsigned RefersToEnclosingVariableOrCapture : 1;
   };
 
   class CastExprBitfields {
@@ -583,6 +583,7 @@
   body_range body() { return body_range(body_begin(), body_end()); }
   body_iterator body_begin() { return Body; }
   body_iterator body_end() { return Body + size(); }
+  Stmt *body_front() { return !body_empty() ? Body[0] : nullptr; }
   Stmt *body_back() { return !body_empty() ? Body[size()-1] : nullptr; }
 
   void setLastStmt(Stmt *S) {
@@ -598,6 +599,9 @@
   }
   const_body_iterator body_begin() const { return Body; }
   const_body_iterator body_end() const { return Body + size(); }
+  const Stmt *body_front() const {
+    return !body_empty() ? Body[0] : nullptr;
+  }
   const Stmt *body_back() const {
     return !body_empty() ? Body[size() - 1] : nullptr;
   }
@@ -1015,7 +1019,7 @@
 
   SourceLocation getLocStart() const LLVM_READONLY { return SwitchLoc; }
   SourceLocation getLocEnd() const LLVM_READONLY {
-    return SubExprs[BODY]->getLocEnd();
+    return SubExprs[BODY] ? SubExprs[BODY]->getLocEnd() : SubExprs[COND]->getLocEnd();
   }
 
   // Iterators
diff --git a/include/clang/AST/StmtIterator.h b/include/clang/AST/StmtIterator.h
index 6ffe74f..ec7329a 100644
--- a/include/clang/AST/StmtIterator.h
+++ b/include/clang/AST/StmtIterator.h
@@ -148,7 +148,7 @@
     : std::pair<StmtIterator,StmtIterator>(begin, end) {}
 
   bool empty() const { return first == second; }
-  LLVM_EXPLICIT operator bool() const { return !empty(); }
+  explicit operator bool() const { return !empty(); }
 
   Stmt *operator->() const { return first.operator->(); }
   Stmt *&operator*() const { return first.operator*(); }
@@ -191,7 +191,7 @@
     : std::pair<ConstStmtIterator,ConstStmtIterator>(begin, end) {}
 
   bool empty() const { return first == second; }
-  LLVM_EXPLICIT operator bool() const { return !empty(); }
+  explicit operator bool() const { return !empty(); }
 
   const Stmt *operator->() const { return first.operator->(); }
   const Stmt *operator*() const { return first.operator*(); }
diff --git a/include/clang/AST/StmtOpenMP.h b/include/clang/AST/StmtOpenMP.h
index 6a2832c..aed7691 100644
--- a/include/clang/AST/StmtOpenMP.h
+++ b/include/clang/AST/StmtOpenMP.h
@@ -254,6 +254,13 @@
   unsigned CollapsedNum;
 
   /// \brief Offsets to the stored exprs.
+  /// This enumeration contains offsets to all the pointers to children
+  /// expressions stored in OMPLoopDirective.
+  /// The first 9 children are nesessary for all the loop directives, and
+  /// the next 7 are specific to the worksharing ones.
+  /// After the fixed children, three arrays of length CollapsedNum are
+  /// allocated: loop counters, their updates and final values.
+  ///
   enum {
     AssociatedStmtOffset = 0,
     IterationVariableOffset = 1,
@@ -264,27 +271,43 @@
     SeparatedCondOffset = 6,
     InitOffset = 7,
     IncOffset = 8,
-    ArraysOffset = 9
+    // The '...End' enumerators do not correspond to child expressions - they
+    // specify the offset to the end (and start of the following counters/
+    // updates/finals arrays).
+    DefaultEnd = 9,
+    // The following 7 exprs are used by worksharing loops only.
+    IsLastIterVariableOffset = 9,
+    LowerBoundVariableOffset = 10,
+    UpperBoundVariableOffset = 11,
+    StrideVariableOffset = 12,
+    EnsureUpperBoundOffset = 13,
+    NextLowerBoundOffset = 14,
+    NextUpperBoundOffset = 15,
+    // Offset to the end (and start of the following counters/updates/finals
+    // arrays) for worksharing loop directives.
+    WorksharingEnd = 16,
   };
 
   /// \brief Get the counters storage.
   MutableArrayRef<Expr *> getCounters() {
-    Expr **Storage =
-        reinterpret_cast<Expr **>(&(*(std::next(child_begin(), ArraysOffset))));
+    Expr **Storage = reinterpret_cast<Expr **>(
+        &(*(std::next(child_begin(), getArraysOffset(getDirectiveKind())))));
     return MutableArrayRef<Expr *>(Storage, CollapsedNum);
   }
 
   /// \brief Get the updates storage.
   MutableArrayRef<Expr *> getUpdates() {
     Expr **Storage = reinterpret_cast<Expr **>(
-        &*std::next(child_begin(), ArraysOffset + CollapsedNum));
+        &*std::next(child_begin(),
+                    getArraysOffset(getDirectiveKind()) + CollapsedNum));
     return MutableArrayRef<Expr *>(Storage, CollapsedNum);
   }
 
   /// \brief Get the final counter updates storage.
   MutableArrayRef<Expr *> getFinals() {
     Expr **Storage = reinterpret_cast<Expr **>(
-        &*std::next(child_begin(), ArraysOffset + 2 * CollapsedNum));
+        &*std::next(child_begin(),
+                    getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum));
     return MutableArrayRef<Expr *>(Storage, CollapsedNum);
   }
 
@@ -305,13 +328,21 @@
                    unsigned CollapsedNum, unsigned NumClauses,
                    unsigned NumSpecialChildren = 0)
       : OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses,
-                               numLoopChildren(CollapsedNum) +
+                               numLoopChildren(CollapsedNum, Kind) +
                                    NumSpecialChildren),
         CollapsedNum(CollapsedNum) {}
 
+  /// \brief Offset to the start of children expression arrays.
+  static unsigned getArraysOffset(OpenMPDirectiveKind Kind) {
+    return isOpenMPWorksharingDirective(Kind) ? WorksharingEnd
+                                              : DefaultEnd;
+  }
+
   /// \brief Children number.
-  static unsigned numLoopChildren(unsigned CollapsedNum) {
-    return ArraysOffset + 3 * CollapsedNum; // Counters, Updates and Finals
+  static unsigned numLoopChildren(unsigned CollapsedNum,
+                                  OpenMPDirectiveKind Kind) {
+    return getArraysOffset(Kind) +
+           3 * CollapsedNum; // Counters, Updates and Finals
   }
 
   void setIterationVariable(Expr *IV) {
@@ -332,11 +363,123 @@
   }
   void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; }
   void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; }
+  void setIsLastIterVariable(Expr *IL) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), IsLastIterVariableOffset) = IL;
+  }
+  void setLowerBoundVariable(Expr *LB) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), LowerBoundVariableOffset) = LB;
+  }
+  void setUpperBoundVariable(Expr *UB) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), UpperBoundVariableOffset) = UB;
+  }
+  void setStrideVariable(Expr *ST) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), StrideVariableOffset) = ST;
+  }
+  void setEnsureUpperBound(Expr *EUB) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), EnsureUpperBoundOffset) = EUB;
+  }
+  void setNextLowerBound(Expr *NLB) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), NextLowerBoundOffset) = NLB;
+  }
+  void setNextUpperBound(Expr *NUB) {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    *std::next(child_begin(), NextUpperBoundOffset) = NUB;
+  }
   void setCounters(ArrayRef<Expr *> A);
   void setUpdates(ArrayRef<Expr *> A);
   void setFinals(ArrayRef<Expr *> A);
 
 public:
+  /// \brief The expressions built for the OpenMP loop CodeGen for the
+  /// whole collapsed loop nest.
+  struct HelperExprs {
+    /// \brief Loop iteration variable.
+    Expr *IterationVarRef;
+    /// \brief Loop last iteration number.
+    Expr *LastIteration;
+    /// \brief Calculation of last iteration.
+    Expr *CalcLastIteration;
+    /// \brief Loop pre-condition.
+    Expr *PreCond;
+    /// \brief Loop condition.
+    Expr *Cond;
+    /// \brief A condition with 1 iteration separated.
+    Expr *SeparatedCond;
+    /// \brief Loop iteration variable init.
+    Expr *Init;
+    /// \brief Loop increment.
+    Expr *Inc;
+    /// \brief IsLastIteration - local flag variable passed to runtime.
+    Expr *IL;
+    /// \brief LowerBound - local variable passed to runtime.
+    Expr *LB;
+    /// \brief UpperBound - local variable passed to runtime.
+    Expr *UB;
+    /// \brief Stride - local variable passed to runtime.
+    Expr *ST;
+    /// \brief EnsureUpperBound -- expression LB = min(LB, NumIterations).
+    Expr *EUB;
+    /// \brief Update of LowerBound for statically sheduled 'omp for' loops.
+    Expr *NLB;
+    /// \brief Update of UpperBound for statically sheduled 'omp for' loops.
+    Expr *NUB;
+    /// \brief Counters Loop counters.
+    SmallVector<Expr *, 4> Counters;
+    /// \brief Expressions for loop counters update for CodeGen.
+    SmallVector<Expr *, 4> Updates;
+    /// \brief Final loop counter values for GodeGen.
+    SmallVector<Expr *, 4> Finals;
+
+    /// \brief Check if all the expressions are built (does not check the
+    /// worksharing ones).
+    bool builtAll() {
+      return IterationVarRef != nullptr && LastIteration != nullptr &&
+             PreCond != nullptr && Cond != nullptr &&
+             SeparatedCond != nullptr && Init != nullptr && Inc != nullptr;
+    }
+
+    /// \brief Initialize all the fields to null.
+    /// \param Size Number of elements in the counters/finals/updates arrays.
+    void clear(unsigned Size) {
+      IterationVarRef = nullptr;
+      LastIteration = nullptr;
+      CalcLastIteration = nullptr;
+      PreCond = nullptr;
+      Cond = nullptr;
+      SeparatedCond = nullptr;
+      Init = nullptr;
+      Inc = nullptr;
+      IL = nullptr;
+      LB = nullptr;
+      UB = nullptr;
+      ST = nullptr;
+      EUB = nullptr;
+      NLB = nullptr;
+      NUB = nullptr;
+      Counters.resize(Size);
+      Updates.resize(Size);
+      Finals.resize(Size);
+      for (unsigned i = 0; i < Size; ++i) {
+        Counters[i] = nullptr;
+        Updates[i] = nullptr;
+        Finals[i] = nullptr;
+      }
+    }
+  };
+
   /// \brief Get number of collapsed loops.
   unsigned getCollapsedNumber() const { return CollapsedNum; }
 
@@ -369,6 +512,48 @@
     return const_cast<Expr *>(
         reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset)));
   }
+  Expr *getIsLastIterVariable() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), IsLastIterVariableOffset)));
+  }
+  Expr *getLowerBoundVariable() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), LowerBoundVariableOffset)));
+  }
+  Expr *getUpperBoundVariable() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), UpperBoundVariableOffset)));
+  }
+  Expr *getStrideVariable() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), StrideVariableOffset)));
+  }
+  Expr *getEnsureUpperBound() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), EnsureUpperBoundOffset)));
+  }
+  Expr *getNextLowerBound() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), NextLowerBoundOffset)));
+  }
+  Expr *getNextUpperBound() const {
+    assert(isOpenMPWorksharingDirective(getDirectiveKind()) &&
+           "expected worksharing loop directive");
+    return const_cast<Expr *>(reinterpret_cast<const Expr *>(
+        *std::next(child_begin(), NextUpperBoundOffset)));
+  }
   const Stmt *getBody() const {
     // This relies on the loop form is already checked by Sema.
     Stmt *Body = getAssociatedStmt()->IgnoreContainers(true);
@@ -449,24 +634,13 @@
   /// \param CollapsedNum Number of collapsed loops.
   /// \param Clauses List of clauses.
   /// \param AssociatedStmt Statement, associated with the directive.
-  /// \param IV Loop iteration variable for CodeGen.
-  /// \param LastIteration Loop last iteration number for CodeGen.
-  /// \param CalcLastIteration Calculation of last iteration.
-  /// \param PreCond Pre-condition.
-  /// \param Cond Condition.
-  /// \param SeparatedCond Condition with 1 iteration separated.
-  /// \param Inc Loop increment.
-  /// \param Counters Loop counters.
-  /// \param Updates Expressions for loop counters update for CodeGen.
-  /// \param Finals Final loop counter values for GodeGen.
+  /// \param Exprs Helper expressions for CodeGen.
   ///
-  static OMPSimdDirective *
-  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
-         unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
-         Stmt *AssociatedStmt, Expr *IV, Expr *LastIteration,
-         Expr *CalcLastIteration, Expr *PreCond, Expr *Cond,
-         Expr *SeparatedCond, Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-         ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals);
+  static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc,
+                                  SourceLocation EndLoc, unsigned CollapsedNum,
+                                  ArrayRef<OMPClause *> Clauses,
+                                  Stmt *AssociatedStmt,
+                                  const HelperExprs &Exprs);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -524,24 +698,13 @@
   /// \param CollapsedNum Number of collapsed loops.
   /// \param Clauses List of clauses.
   /// \param AssociatedStmt Statement, associated with the directive.
-  /// \param IV Loop iteration variable for CodeGen.
-  /// \param LastIteration Loop last iteration number for CodeGen.
-  /// \param CalcLastIteration Calculation of last iteration.
-  /// \param PreCond Pre-condition.
-  /// \param Cond Condition.
-  /// \param SeparatedCond Condition with 1 iteration separated.
-  /// \param Inc Loop increment.
-  /// \param Counters Loop counters.
-  /// \param Updates Expressions for loop counters update for CodeGen.
-  /// \param Finals Final loop counter values for GodeGen.
+  /// \param Exprs Helper expressions for CodeGen.
   ///
-  static OMPForDirective *
-  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
-         unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
-         Stmt *AssociatedStmt, Expr *IV, Expr *LastIteration,
-         Expr *CalcLastIteration, Expr *PreCond, Expr *Cond,
-         Expr *SeparatedCond, Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-         ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals);
+  static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc,
+                                 SourceLocation EndLoc, unsigned CollapsedNum,
+                                 ArrayRef<OMPClause *> Clauses,
+                                 Stmt *AssociatedStmt,
+                                 const HelperExprs &Exprs);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -600,24 +763,12 @@
   /// \param CollapsedNum Number of collapsed loops.
   /// \param Clauses List of clauses.
   /// \param AssociatedStmt Statement, associated with the directive.
-  /// \param IV Loop iteration variable for CodeGen.
-  /// \param LastIteration Loop last iteration number for CodeGen.
-  /// \param CalcLastIteration Calculation of last iteration.
-  /// \param PreCond Pre-condition.
-  /// \param Cond Condition.
-  /// \param SeparatedCond Condition with 1 iteration separated.
-  /// \param Inc Loop increment.
-  /// \param Counters Loop counters.
-  /// \param Updates Expressions for loop counters update for CodeGen.
-  /// \param Finals Final loop counter values for GodeGen.
+  /// \param Exprs Helper expressions for CodeGen.
   ///
   static OMPForSimdDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
          unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
-         Stmt *AssociatedStmt, Expr *IV, Expr *LastIteration,
-         Expr *CalcLastIteration, Expr *PreCond, Expr *Cond,
-         Expr *SeparatedCond, Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-         ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals);
+         Stmt *AssociatedStmt, const HelperExprs &Exprs);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -949,24 +1100,12 @@
   /// \param CollapsedNum Number of collapsed loops.
   /// \param Clauses List of clauses.
   /// \param AssociatedStmt Statement, associated with the directive.
-  /// \param IV Loop iteration variable for CodeGen.
-  /// \param LastIteration Loop last iteration number for CodeGen.
-  /// \param CalcLastIteration Calculation of last iteration.
-  /// \param PreCond Pre-condition.
-  /// \param Cond Condition.
-  /// \param SeparatedCond Condition with 1 iteration separated.
-  /// \param Inc Loop increment.
-  /// \param Counters Loop counters.
-  /// \param Updates Expressions for loop counters update for CodeGen.
-  /// \param Finals Final loop counter values for GodeGen.
+  /// \param Exprs Helper expressions for CodeGen.
   ///
   static OMPParallelForDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
          unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
-         Stmt *AssociatedStmt, Expr *IV, Expr *LastIteration,
-         Expr *CalcLastIteration, Expr *PreCond, Expr *Cond,
-         Expr *SeparatedCond, Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-         ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals);
+         Stmt *AssociatedStmt, const HelperExprs &Exprs);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
@@ -1030,24 +1169,12 @@
   /// \param CollapsedNum Number of collapsed loops.
   /// \param Clauses List of clauses.
   /// \param AssociatedStmt Statement, associated with the directive.
-  /// \param IV Loop iteration variable for CodeGen.
-  /// \param LastIteration Loop last iteration number for CodeGen.
-  /// \param CalcLastIteration Calculation of last iteration.
-  /// \param PreCond Pre-condition.
-  /// \param Cond Condition.
-  /// \param SeparatedCond Condition with 1 iteration separated.
-  /// \param Inc Loop increment.
-  /// \param Counters Loop counters.
-  /// \param Updates Expressions for loop counters update for CodeGen.
-  /// \param Finals Final loop counter values for GodeGen.
+  /// \param Exprs Helper expressions for CodeGen.
   ///
   static OMPParallelForSimdDirective *
   Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
          unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
-         Stmt *AssociatedStmt, Expr *IV, Expr *LastIteration,
-         Expr *CalcLastIteration, Expr *PreCond, Expr *Cond,
-         Expr *SeparatedCond, Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-         ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals);
+         Stmt *AssociatedStmt, const HelperExprs &Exprs);
 
   /// \brief Creates an empty directive with the place
   /// for \a NumClauses clauses.
diff --git a/include/clang/AST/TemplateBase.h b/include/clang/AST/TemplateBase.h
index f3c6440..1d01753 100644
--- a/include/clang/AST/TemplateBase.h
+++ b/include/clang/AST/TemplateBase.h
@@ -18,8 +18,8 @@
 #include "clang/AST/TemplateName.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/APSInt.h"
-#include "llvm/ADT/iterator_range.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 
@@ -114,7 +114,7 @@
     struct TV TypeOrValue;
   };
 
-  TemplateArgument(TemplateName, bool) LLVM_DELETED_FUNCTION;
+  TemplateArgument(TemplateName, bool) = delete;
   
 public:
   /// \brief Construct an empty, invalid template argument.
diff --git a/include/clang/AST/Type.h b/include/clang/AST/Type.h
index 4f194b0..b252d48 100644
--- a/include/clang/AST/Type.h
+++ b/include/clang/AST/Type.h
@@ -16,6 +16,7 @@
 
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/TemplateName.h"
+#include "clang/Basic/AddressSpaces.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/ExceptionSpecificationType.h"
 #include "clang/Basic/LLVM.h"
@@ -25,11 +26,11 @@
 #include "clang/Basic/Visibility.h"
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/FoldingSet.h"
-#include "llvm/ADT/iterator_range.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/Twine.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/ErrorHandling.h"
 
 namespace clang {
@@ -400,21 +401,36 @@
     Mask |= qs.Mask;
   }
 
+  /// \brief Returns true if this address space is a superset of the other one.
+  /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
+  /// overlapping address spaces.
+  /// CL1.1 or CL1.2:
+  ///   every address space is a superset of itself.
+  /// CL2.0 adds:
+  ///   __generic is a superset of any address space except for __constant.
+  bool isAddressSpaceSupersetOf(Qualifiers other) const {
+    return
+        // Address spaces must match exactly.
+        getAddressSpace() == other.getAddressSpace() ||
+        // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
+        // for __constant can be used as __generic.
+        (getAddressSpace() == LangAS::opencl_generic &&
+         other.getAddressSpace() != LangAS::opencl_constant);
+  }
+
   /// \brief Determines if these qualifiers compatibly include another set.
   /// Generally this answers the question of whether an object with the other
   /// qualifiers can be safely used as an object with these qualifiers.
   bool compatiblyIncludes(Qualifiers other) const {
-    return
-      // Address spaces must match exactly.
-      getAddressSpace() == other.getAddressSpace() &&
-      // ObjC GC qualifiers can match, be added, or be removed, but can't be
-      // changed.
-      (getObjCGCAttr() == other.getObjCGCAttr() ||
-       !hasObjCGCAttr() || !other.hasObjCGCAttr()) &&
-      // ObjC lifetime qualifiers must match exactly.
-      getObjCLifetime() == other.getObjCLifetime() &&
-      // CVR qualifiers may subset.
-      (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
+    return isAddressSpaceSupersetOf(other) &&
+           // ObjC GC qualifiers can match, be added, or be removed, but can't
+           // be changed.
+           (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
+            !other.hasObjCGCAttr()) &&
+           // ObjC lifetime qualifiers must match exactly.
+           getObjCLifetime() == other.getObjCLifetime() &&
+           // CVR qualifiers may subset.
+           (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
   }
 
   /// \brief Determines if these qualifiers compatibly include another set of
@@ -440,7 +456,7 @@
   bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
   bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
 
-  LLVM_EXPLICIT operator bool() const { return hasQualifiers(); }
+  explicit operator bool() const { return hasQualifiers(); }
 
   Qualifiers &operator+=(Qualifiers R) {
     addQualifiers(R);
@@ -1163,8 +1179,8 @@
   };
 
 private:
-  Type(const Type &) LLVM_DELETED_FUNCTION;
-  void operator=(const Type &) LLVM_DELETED_FUNCTION;
+  Type(const Type &) = delete;
+  void operator=(const Type &) = delete;
 
   /// Bitfields required by the Type class.
   class TypeBitfields {
@@ -1691,6 +1707,11 @@
   /// type of a class template or class template partial specialization.
   CXXRecordDecl *getAsCXXRecordDecl() const;
 
+  /// \brief Retrieves the TagDecl that this type refers to, either
+  /// because the type is a TagType or because it is the injected-class-name
+  /// type of a class template or class template partial specialization.
+  TagDecl *getAsTagDecl() const;
+
   /// If this is a pointer or reference to a RecordType, return the
   /// CXXRecordDecl that that type refers to.
   ///
@@ -1988,6 +2009,22 @@
 
   QualType getPointeeType() const { return PointeeType; }
 
+  /// \brief Returns true if address spaces of pointers overlap.
+  /// OpenCL v2.0 defines conversion rules for pointers to different
+  /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
+  /// address spaces.
+  /// CL1.1 or CL1.2:
+  ///   address spaces overlap iff they are they same.
+  /// CL2.0 adds:
+  ///   __generic overlaps with any address space except for __constant.
+  bool isAddressSpaceOverlapping(const PointerType &other) const {
+    Qualifiers thisQuals = PointeeType.getQualifiers();
+    Qualifiers otherQuals = other.getPointeeType().getQualifiers();
+    // Address spaces overlap if at least one of them is a superset of another
+    return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
+           otherQuals.isAddressSpaceSupersetOf(thisQuals);
+  }
+
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
 
@@ -3435,7 +3472,6 @@
     attr_thiscall,
     attr_pascal,
     attr_vectorcall,
-    attr_pnaclcall,
     attr_inteloclbicc,
     attr_ms_abi,
     attr_sysv_abi,
diff --git a/include/clang/AST/TypeLoc.h b/include/clang/AST/TypeLoc.h
index 4f3c811..e29fa49 100644
--- a/include/clang/AST/TypeLoc.h
+++ b/include/clang/AST/TypeLoc.h
@@ -93,7 +93,7 @@
   }
 
   bool isNull() const { return !Ty; }
-  LLVM_EXPLICIT operator bool() const { return Ty; }
+  explicit operator bool() const { return Ty; }
 
   /// \brief Returns the size of type source info data block for the given type.
   static unsigned getFullDataSizeForType(QualType Ty);
diff --git a/include/clang/AST/TypeNodes.def b/include/clang/AST/TypeNodes.def
index 3b2665b..2549f0b 100644
--- a/include/clang/AST/TypeNodes.def
+++ b/include/clang/AST/TypeNodes.def
@@ -11,7 +11,7 @@
 //  enumerated by providing its name (e.g., "Builtin" or "Enum") and
 //  base class (e.g., "Type" or "TagType"). Depending on where in the
 //  abstract syntax tree the type will show up, the enumeration uses
-//  one of four different macros:
+//  one of five different macros:
 //
 //    TYPE(Class, Base) - A type that can show up anywhere in the AST,
 //    and might be dependent, canonical, or non-canonical. All clients
diff --git a/include/clang/AST/UnresolvedSet.h b/include/clang/AST/UnresolvedSet.h
index a11f22d..26ee1cf 100644
--- a/include/clang/AST/UnresolvedSet.h
+++ b/include/clang/AST/UnresolvedSet.h
@@ -19,74 +19,36 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
-#include <iterator>
+#include "llvm/ADT/iterator.h"
 
 namespace clang {
 
 /// The iterator over UnresolvedSets.  Serves as both the const and
 /// non-const iterator.
-class UnresolvedSetIterator {
-private:
-  typedef MutableArrayRef<DeclAccessPair> DeclsTy;
-  typedef DeclsTy::iterator IteratorTy;
-
-  IteratorTy ir;
-
+class UnresolvedSetIterator : public llvm::iterator_adaptor_base<
+                                  UnresolvedSetIterator, DeclAccessPair *,
+                                  std::random_access_iterator_tag, NamedDecl *,
+                                  std::ptrdiff_t, NamedDecl *, NamedDecl *> {
   friend class UnresolvedSetImpl;
   friend class ASTUnresolvedSet;
   friend class OverloadExpr;
-  explicit UnresolvedSetIterator(DeclsTy::iterator ir) : ir(ir) {}
-  explicit UnresolvedSetIterator(DeclsTy::const_iterator ir) :
-    ir(const_cast<DeclsTy::iterator>(ir)) {}
-  
-  IteratorTy getIterator() const { return ir; }
-  
+
+  explicit UnresolvedSetIterator(DeclAccessPair *Iter)
+      : iterator_adaptor_base(Iter) {}
+  explicit UnresolvedSetIterator(const DeclAccessPair *Iter)
+      : iterator_adaptor_base(const_cast<DeclAccessPair *>(Iter)) {}
+
 public:
   UnresolvedSetIterator() {}
 
-  typedef std::iterator_traits<IteratorTy>::difference_type difference_type;
-  typedef NamedDecl *value_type;
-  typedef NamedDecl **pointer;
-  typedef NamedDecl *reference;
-  typedef std::iterator_traits<IteratorTy>::iterator_category iterator_category;
-
-  NamedDecl *getDecl() const { return ir->getDecl(); }
-  void setDecl(NamedDecl *ND) const { return ir->setDecl(ND); }
-  AccessSpecifier getAccess() const { return ir->getAccess(); }
-  void setAccess(AccessSpecifier AS) { ir->setAccess(AS); }
-  DeclAccessPair getPair() const { return *ir; }
+  NamedDecl *getDecl() const { return I->getDecl(); }
+  void setDecl(NamedDecl *ND) const { return I->setDecl(ND); }
+  AccessSpecifier getAccess() const { return I->getAccess(); }
+  void setAccess(AccessSpecifier AS) { I->setAccess(AS); }
+  const DeclAccessPair &getPair() const { return *I; }
 
   NamedDecl *operator*() const { return getDecl(); }
-  
-  UnresolvedSetIterator &operator++() { ++ir; return *this; }
-  UnresolvedSetIterator operator++(int) { return UnresolvedSetIterator(ir++); }
-  UnresolvedSetIterator &operator--() { --ir; return *this; }
-  UnresolvedSetIterator operator--(int) { return UnresolvedSetIterator(ir--); }
-
-  UnresolvedSetIterator &operator+=(difference_type d) {
-    ir += d; return *this;
-  }
-  UnresolvedSetIterator operator+(difference_type d) const {
-    return UnresolvedSetIterator(ir + d);
-  }
-  UnresolvedSetIterator &operator-=(difference_type d) {
-    ir -= d; return *this;
-  }
-  UnresolvedSetIterator operator-(difference_type d) const {
-    return UnresolvedSetIterator(ir - d);
-  }
-  value_type operator[](difference_type d) const { return *(*this + d); }
-
-  difference_type operator-(const UnresolvedSetIterator &o) const {
-    return ir - o.ir;
-  }
-
-  bool operator==(const UnresolvedSetIterator &o) const { return ir == o.ir; }
-  bool operator!=(const UnresolvedSetIterator &o) const { return ir != o.ir; }
-  bool operator<(const UnresolvedSetIterator &o) const { return ir < o.ir; }
-  bool operator<=(const UnresolvedSetIterator &o) const { return ir <= o.ir; }
-  bool operator>=(const UnresolvedSetIterator &o) const { return ir >= o.ir; }
-  bool operator>(const UnresolvedSetIterator &o) const { return ir > o.ir; }
+  NamedDecl *operator->() const { return **this; }
 };
 
 /// \brief A set of unresolved declarations.
@@ -132,21 +94,17 @@
 
   /// Replaces the declaration at the given iterator with the new one,
   /// preserving the original access bits.
-  void replace(iterator I, NamedDecl *New) {
-    I.ir->setDecl(New);
-  }
+  void replace(iterator I, NamedDecl *New) { I.I->setDecl(New); }
 
   void replace(iterator I, NamedDecl *New, AccessSpecifier AS) {
-    I.ir->set(New, AS);
+    I.I->set(New, AS);
   }
 
   void erase(unsigned I) { decls()[I] = decls().pop_back_val(); }
 
-  void erase(iterator I) { *I.ir = decls().pop_back_val(); }
+  void erase(iterator I) { *I.I = decls().pop_back_val(); }
 
-  void setAccess(iterator I, AccessSpecifier AS) {
-    I.ir->setAccess(AS);
-  }
+  void setAccess(iterator I, AccessSpecifier AS) { I.I->setAccess(AS); }
 
   void clear() { decls().clear(); }
   void set_size(unsigned N) { decls().set_size(N); }
@@ -154,9 +112,7 @@
   bool empty() const { return decls().empty(); }
   unsigned size() const { return decls().size(); }
 
-  void append(iterator I, iterator E) {
-    decls().append(I.ir, E.ir);
-  }
+  void append(iterator I, iterator E) { decls().append(I.I, E.I); }
 
   DeclAccessPair &operator[](unsigned I) { return decls()[I]; }
   const DeclAccessPair &operator[](unsigned I) const { return decls()[I]; }
diff --git a/include/clang/ASTMatchers/ASTMatchFinder.h b/include/clang/ASTMatchers/ASTMatchFinder.h
index e5fc44c..ce2674e 100644
--- a/include/clang/ASTMatchers/ASTMatchFinder.h
+++ b/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -199,9 +199,9 @@
   /// \brief For each \c Matcher<> a \c MatchCallback that will be called
   /// when it matches.
   struct MatchersByType {
-    std::vector<std::pair<DeclarationMatcher, MatchCallback *>> Decl;
+    std::vector<std::pair<internal::DynTypedMatcher, MatchCallback *>>
+        DeclOrStmt;
     std::vector<std::pair<TypeMatcher, MatchCallback *>> Type;
-    std::vector<std::pair<StatementMatcher, MatchCallback *>> Stmt;
     std::vector<std::pair<NestedNameSpecifierMatcher, MatchCallback *>>
         NestedNameSpecifier;
     std::vector<std::pair<NestedNameSpecifierLocMatcher, MatchCallback *>>
diff --git a/include/clang/ASTMatchers/ASTMatchers.h b/include/clang/ASTMatchers/ASTMatchers.h
index 37c7b16..f317981 100644
--- a/include/clang/ASTMatchers/ASTMatchers.h
+++ b/include/clang/ASTMatchers/ASTMatchers.h
@@ -45,6 +45,7 @@
 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
 
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclFriend.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/ASTMatchers/ASTMatchersInternal.h"
@@ -142,6 +143,111 @@
 /// Usable as: Any Matcher
 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
 
+/// \brief Matches the top declaration context.
+///
+/// Given
+/// \code
+///   int X;
+///   namespace NS {
+///   int Y;
+///   }  // namespace NS
+/// \endcode
+/// decl(hasDeclContext(translationUnitDecl()))
+///   matches "int X", but not "int Y".
+const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
+    translationUnitDecl;
+
+/// \brief Matches typedef declarations.
+///
+/// Given
+/// \code
+///   typedef int X;
+/// \endcode
+/// typedefDecl()
+///   matches "typedef int X"
+const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
+
+/// \brief Matches AST nodes that were expanded within the main-file.
+///
+/// Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile())
+/// \code
+///   #include <Y.h>
+///   class X {};
+/// \endcode
+/// Y.h:
+/// \code
+///   class Y {};
+/// \endcode
+///
+/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
+AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
+                        AST_POLYMORPHIC_SUPPORTED_TYPES_3(Decl, Stmt,
+                                                          TypeLoc)) {
+  auto &SourceManager = Finder->getASTContext().getSourceManager();
+  return SourceManager.isInMainFile(
+      SourceManager.getExpansionLoc(Node.getLocStart()));
+}
+
+/// \brief Matches AST nodes that were expanded within system-header-files.
+///
+/// Example matches Y but not X
+///     (matcher = recordDecl(isExpansionInSystemHeader())
+/// \code
+///   #include <SystemHeader.h>
+///   class X {};
+/// \endcode
+/// SystemHeader.h:
+/// \code
+///   class Y {};
+/// \endcode
+///
+/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
+AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
+                        AST_POLYMORPHIC_SUPPORTED_TYPES_3(Decl, Stmt,
+                                                          TypeLoc)) {
+  auto &SourceManager = Finder->getASTContext().getSourceManager();
+  auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
+  if (ExpansionLoc.isInvalid()) {
+    return false;
+  }
+  return SourceManager.isInSystemHeader(ExpansionLoc);
+}
+
+/// \brief Matches AST nodes that were expanded within files whose name is
+/// partially matching a given regex.
+///
+/// Example matches Y but not X
+///     (matcher = recordDecl(isExpansionInFileMatching("AST.*"))
+/// \code
+///   #include "ASTMatcher.h"
+///   class X {};
+/// \endcode
+/// ASTMatcher.h:
+/// \code
+///   class Y {};
+/// \endcode
+///
+/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
+AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
+                          AST_POLYMORPHIC_SUPPORTED_TYPES_3(Decl, Stmt,
+                                                            TypeLoc),
+                          std::string, RegExp) {
+  auto &SourceManager = Finder->getASTContext().getSourceManager();
+  auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
+  if (ExpansionLoc.isInvalid()) {
+    return false;
+  }
+  auto FileEntry =
+      SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
+  if (!FileEntry) {
+    return false;
+  }
+
+  auto Filename = FileEntry->getName();
+  llvm::Regex RE(RegExp);
+  return RE.match(Filename);
+}
+
 /// \brief Matches declarations.
 ///
 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
@@ -1682,7 +1788,7 @@
 }
 
 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
-AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, StringRef, BaseName, 1) {
+AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
   assert(!BaseName.empty());
   return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
 }
@@ -1697,8 +1803,8 @@
 
 /// \brief Overloaded method as shortcut for
 /// \c isSameOrDerivedFrom(hasName(...)).
-AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, StringRef, BaseName,
-                       1) {
+AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
+                       BaseName, 1) {
   assert(!BaseName.empty());
   return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
 }
@@ -3067,12 +3173,10 @@
 /// \endcode
 /// functionDecl(isInstantiated())
 ///   matches 'A(int) {...};' and 'A(unsigned) {...}'.
-AST_MATCHER(Decl, isInstantiated) {
+AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
   auto IsInstantiation = decl(anyOf(recordDecl(isTemplateInstantiation()),
                                     functionDecl(isTemplateInstantiation())));
-  auto InnerMatcher =
-      decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
-  return InnerMatcher.matches(Node, Finder, Builder);
+  return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
 }
 
 /// \brief Matches statements inside of a template instantiation.
@@ -3089,11 +3193,10 @@
 /// unless(stmt(isInTemplateInstantiation()))
 ///   will NOT match j += 42; as it's shared between the template definition and
 ///   instantiation.
-AST_MATCHER(Stmt, isInTemplateInstantiation) {
-  auto InnerMatcher =
-      stmt(hasAncestor(decl(anyOf(recordDecl(isTemplateInstantiation()),
-                                  functionDecl(isTemplateInstantiation())))));
-  return InnerMatcher.matches(Node, Finder, Builder);
+AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
+  return stmt(
+      hasAncestor(decl(anyOf(recordDecl(isTemplateInstantiation()),
+                             functionDecl(isTemplateInstantiation())))));
 }
 
 /// \brief Matches explicit template specializations of function, class, or
@@ -3122,6 +3225,18 @@
       new internal::TypeLocTypeMatcher(InnerMatcher));
 }
 
+/// \brief Matches type \c void.
+///
+/// Given
+/// \code
+///  struct S { void func(); };
+/// \endcode
+/// functionDecl(returns(voidType()))
+///   matches "void func();"
+AST_MATCHER(Type, voidType) {
+  return Node.isVoidType();
+}
+
 /// \brief Matches builtin Types.
 ///
 /// Given
diff --git a/include/clang/ASTMatchers/ASTMatchersInternal.h b/include/clang/ASTMatchers/ASTMatchersInternal.h
index 1b8040c..86a31ea 100644
--- a/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ b/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -44,6 +44,7 @@
 #include "clang/AST/Type.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/VariadicFunction.h"
+#include "llvm/Support/ManagedStatic.h"
 #include <map>
 #include <string>
 #include <vector>
@@ -218,10 +219,7 @@
   bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
                   ASTMatchFinder *Finder,
                   BoundNodesTreeBuilder *Builder) const override {
-    if (const T *Node = DynNode.get<T>()) {
-      return matches(*Node, Finder, Builder);
-    }
-    return false;
+    return matches(DynNode.getUnchecked<T>(), Finder, Builder);
   }
 };
 
@@ -289,6 +287,11 @@
 
   void setAllowBind(bool AB) { AllowBind = AB; }
 
+  /// \brief Check whether this matcher could ever match a node of kind \p Kind.
+  /// \return \c false if this matcher will never match such a node. Otherwise,
+  /// return \c true.
+  bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
+
   /// \brief Return a matcher that points to the same implementation, but
   ///   restricts the node types for \p Kind.
   DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
@@ -297,6 +300,14 @@
   bool matches(const ast_type_traits::DynTypedNode &DynNode,
                ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
 
+  /// \brief Same as matches(), but skips the kind check.
+  ///
+  /// It is faster, but the caller must ensure the node is valid for the
+  /// kind of this matcher.
+  bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
+                          ASTMatchFinder *Finder,
+                          BoundNodesTreeBuilder *Builder) const;
+
   /// \brief Bind the specified \p ID to the matcher.
   /// \return A new matcher with the \p ID bound to it if this matcher supports
   ///   binding. Otherwise, returns an empty \c Optional<>.
@@ -836,19 +847,11 @@
 
 /// \brief A type-list implementation.
 ///
-/// A list is declared as a tree of type list nodes, where the leafs are the
-/// types.
-/// However, it is used as a "linked list" of types, by using the ::head and
-/// ::tail typedefs.
-/// Each node supports up to 4 children (instead of just 2) to reduce the
-/// nesting required by large lists.
-template <typename T1 = void, typename T2 = void, typename T3 = void,
-          typename T4 = void>
-struct TypeList {
-  /// \brief Implementation detail. Combined with the specializations below,
-  ///   this typedef allows for flattening of nested structures.
-  typedef TypeList<T1, T2, T3, T4> self;
+/// A "linked list" of types, accessible by using the ::head and ::tail
+/// typedefs.
+template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
 
+template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
   /// \brief The first type on the list.
   typedef T1 head;
 
@@ -856,24 +859,7 @@
   ///
   /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
   /// end of the list.
-  typedef typename TypeList<T2, T3, T4>::self tail;
-};
-
-/// \brief Template specialization to allow nested lists.
-///
-/// First element is a typelist. Pop its first element.
-template <typename Sub1, typename Sub2, typename Sub3, typename Sub4,
-          typename T2, typename T3, typename T4>
-struct TypeList<TypeList<Sub1, Sub2, Sub3, Sub4>, T2, T3,
-                T4> : public TypeList<Sub1,
-                                      typename TypeList<Sub2, Sub3, Sub4>::self,
-                                      typename TypeList<T2, T3, T4>::self> {};
-
-/// \brief Template specialization to allow nested lists.
-///
-/// First element is an empty typelist. Skip it.
-template <typename T2, typename T3, typename T4>
-struct TypeList<TypeList<>, T2, T3, T4> : public TypeList<T2, T3, T4> {
+  typedef TypeList<Ts...> tail;
 };
 
 /// \brief The empty type list.
@@ -895,9 +881,8 @@
 /// \brief A "type list" that contains all types.
 ///
 /// Useful for matchers like \c anything and \c unless.
-typedef TypeList<
-    TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc>,
-    TypeList<QualType, Type, TypeLoc, CXXCtorInitializer> > AllNodeBaseTypes;
+typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
+                 QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes;
 
 /// \brief Helper meta-function to extract the argument out of a function of
 ///   type void(Arg).
@@ -910,17 +895,15 @@
 
 /// \brief Default type lists for ArgumentAdaptingMatcher matchers.
 typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
-typedef TypeList<TypeList<Decl, Stmt, NestedNameSpecifier>,
-                 TypeList<NestedNameSpecifierLoc, TypeLoc, QualType> >
-AdaptativeDefaultToTypes;
+typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
+                 TypeLoc, QualType> AdaptativeDefaultToTypes;
 
 /// \brief All types that are supported by HasDeclarationMatcher above.
-typedef TypeList<TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType>,
-                 TypeList<InjectedClassNameType, LabelStmt, MemberExpr>,
-                 TypeList<QualType, RecordType, TagType>,
-                 TypeList<TemplateSpecializationType, TemplateTypeParmType,
-                          TypedefType, UnresolvedUsingType> >
-HasDeclarationSupportedTypes;
+typedef TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType,
+                 InjectedClassNameType, LabelStmt, MemberExpr, QualType,
+                 RecordType, TagType, TemplateSpecializationType,
+                 TemplateTypeParmType, TypedefType,
+                 UnresolvedUsingType> HasDeclarationSupportedTypes;
 
 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
 /// "adapting" a \c To into a \c T.
@@ -1133,153 +1116,45 @@
 /// \brief VariadicOperatorMatcher related types.
 /// @{
 
-/// \brief "No argument" placeholder to use as template paratemers.
-struct VariadicOperatorNoArg {};
-
 /// \brief Polymorphic matcher object that uses a \c
 /// DynTypedMatcher::VariadicOperator operator.
 ///
 /// Input matchers can have any type (including other polymorphic matcher
 /// types), and the actual Matcher<T> is generated on demand with an implicit
 /// coversion operator.
-template <typename P1, typename P2 = VariadicOperatorNoArg,
-          typename P3 = VariadicOperatorNoArg,
-          typename P4 = VariadicOperatorNoArg,
-          typename P5 = VariadicOperatorNoArg,
-          typename P6 = VariadicOperatorNoArg,
-          typename P7 = VariadicOperatorNoArg,
-          typename P8 = VariadicOperatorNoArg,
-          typename P9 = VariadicOperatorNoArg>
-class VariadicOperatorMatcher {
+template <typename... Ps> class VariadicOperatorMatcher {
 public:
-  VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op,
-                          const P1 &Param1,
-                          const P2 &Param2 = VariadicOperatorNoArg(),
-                          const P3 &Param3 = VariadicOperatorNoArg(),
-                          const P4 &Param4 = VariadicOperatorNoArg(),
-                          const P5 &Param5 = VariadicOperatorNoArg(),
-                          const P6 &Param6 = VariadicOperatorNoArg(),
-                          const P7 &Param7 = VariadicOperatorNoArg(),
-                          const P8 &Param8 = VariadicOperatorNoArg(),
-                          const P9 &Param9 = VariadicOperatorNoArg())
-      : Op(Op), Param1(Param1), Param2(Param2), Param3(Param3),
-        Param4(Param4), Param5(Param5), Param6(Param6), Param7(Param7),
-        Param8(Param8), Param9(Param9) {}
+  VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
+      : Op(Op), Params(std::forward<Ps>(Params)...) {}
 
   template <typename T> operator Matcher<T>() const {
-    std::vector<DynTypedMatcher> Matchers;
-    addMatcher<T>(Param1, Matchers);
-    addMatcher<T>(Param2, Matchers);
-    addMatcher<T>(Param3, Matchers);
-    addMatcher<T>(Param4, Matchers);
-    addMatcher<T>(Param5, Matchers);
-    addMatcher<T>(Param6, Matchers);
-    addMatcher<T>(Param7, Matchers);
-    addMatcher<T>(Param8, Matchers);
-    addMatcher<T>(Param9, Matchers);
-    return DynTypedMatcher::constructVariadic(Op, std::move(Matchers))
+    return DynTypedMatcher::constructVariadic(
+               Op, getMatchers<T>(llvm::index_sequence_for<Ps...>()))
         .template unconditionalConvertTo<T>();
   }
 
 private:
-  template <typename T>
-  static void addMatcher(const Matcher<T> &M,
-                         std::vector<DynTypedMatcher> &Matchers) {
-    Matchers.push_back(M);
+  // Helper method to unpack the tuple into a vector.
+  template <typename T, std::size_t... Is>
+  std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const {
+    return {Matcher<T>(std::get<Is>(Params))...};
   }
 
-  /// \brief Overload to ignore \c VariadicOperatorNoArg arguments.
-  template <typename T>
-  static void addMatcher(VariadicOperatorNoArg,
-                         std::vector<DynTypedMatcher> &Matchers) {}
-
   const DynTypedMatcher::VariadicOperator Op;
-  const P1 Param1;
-  const P2 Param2;
-  const P3 Param3;
-  const P4 Param4;
-  const P5 Param5;
-  const P6 Param6;
-  const P7 Param7;
-  const P8 Param8;
-  const P9 Param9;
+  std::tuple<Ps...> Params;
 };
 
 /// \brief Overloaded function object to generate VariadicOperatorMatcher
 ///   objects from arbitrary matchers.
-///
-/// It supports 1-9 argument overloaded operator(). More can be added if needed.
 template <unsigned MinCount, unsigned MaxCount>
 struct VariadicOperatorMatcherFunc {
   DynTypedMatcher::VariadicOperator Op;
 
-  template <unsigned Count, typename T>
-  struct EnableIfValidArity
-      : public std::enable_if<MinCount <= Count && Count <= MaxCount, T> {};
-
-  template <typename M1>
-  typename EnableIfValidArity<1, VariadicOperatorMatcher<M1> >::type
-  operator()(const M1 &P1) const {
-    return VariadicOperatorMatcher<M1>(Op, P1);
-  }
-  template <typename M1, typename M2>
-  typename EnableIfValidArity<2, VariadicOperatorMatcher<M1, M2> >::type
-  operator()(const M1 &P1, const M2 &P2) const {
-    return VariadicOperatorMatcher<M1, M2>(Op, P1, P2);
-  }
-  template <typename M1, typename M2, typename M3>
-  typename EnableIfValidArity<3, VariadicOperatorMatcher<M1, M2, M3> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3) const {
-    return VariadicOperatorMatcher<M1, M2, M3>(Op, P1, P2, P3);
-  }
-  template <typename M1, typename M2, typename M3, typename M4>
-  typename EnableIfValidArity<4, VariadicOperatorMatcher<M1, M2, M3, M4> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) const {
-    return VariadicOperatorMatcher<M1, M2, M3, M4>(Op, P1, P2, P3, P4);
-  }
-  template <typename M1, typename M2, typename M3, typename M4, typename M5>
-  typename EnableIfValidArity<
-      5, VariadicOperatorMatcher<M1, M2, M3, M4, M5> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
-             const M5 &P5) const {
-    return VariadicOperatorMatcher<M1, M2, M3, M4, M5>(Op, P1, P2, P3, P4, P5);
-  }
-  template <typename M1, typename M2, typename M3, typename M4, typename M5,
-            typename M6>
-  typename EnableIfValidArity<
-      6, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
-             const M5 &P5, const M6 &P6) const {
-    return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6>(
-        Op, P1, P2, P3, P4, P5, P6);
-  }
-  template <typename M1, typename M2, typename M3, typename M4, typename M5,
-            typename M6, typename M7>
-  typename EnableIfValidArity<
-      7, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
-             const M5 &P5, const M6 &P6, const M7 &P7) const {
-    return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7>(
-        Op, P1, P2, P3, P4, P5, P6, P7);
-  }
-  template <typename M1, typename M2, typename M3, typename M4, typename M5,
-            typename M6, typename M7, typename M8>
-  typename EnableIfValidArity<
-      8, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
-             const M5 &P5, const M6 &P6, const M7 &P7, const M8 &P8) const {
-    return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8>(
-        Op, P1, P2, P3, P4, P5, P6, P7, P8);
-  }
-  template <typename M1, typename M2, typename M3, typename M4, typename M5,
-            typename M6, typename M7, typename M8, typename M9>
-  typename EnableIfValidArity<
-      9, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8, M9> >::type
-  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
-             const M5 &P5, const M6 &P6, const M7 &P7, const M8 &P8,
-             const M9 &P9) const {
-    return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8, M9>(
-        Op, P1, P2, P3, P4, P5, P6, P7, P8, P9);
+  template <typename... Ms>
+  VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
+    static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
+                  "invalid number of parameters for variadic matcher");
+    return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
   }
 };
 
@@ -1445,6 +1320,32 @@
   const ValueT ExpectedValue;
 };
 
+/// \brief Template specializations to easily write matchers for floating point
+/// literals.
+template <>
+inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
+    const FloatingLiteral &Node) const {
+  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
+    return Node.getValue().convertToFloat() == ExpectedValue;
+  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
+    return Node.getValue().convertToDouble() == ExpectedValue;
+  return false;
+}
+template <>
+inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
+    const FloatingLiteral &Node) const {
+  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
+    return Node.getValue().convertToFloat() == ExpectedValue;
+  if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
+    return Node.getValue().convertToDouble() == ExpectedValue;
+  return false;
+}
+template <>
+inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
+    const FloatingLiteral &Node) const {
+  return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
+}
+
 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
 /// variadic functor that takes a number of Matcher<TargetT> and returns a
 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
@@ -1610,6 +1511,23 @@
   const Matcher<InnerTBase> InnerMatcher;
 };
 
+/// \brief A simple memoizer of T(*)() functions.
+///
+/// It will call the passed 'Func' template parameter at most once.
+/// Used to support AST_MATCHER_FUNCTION() macro.
+template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
+  struct Wrapper {
+    Wrapper() : M(Func()) {}
+    Matcher M;
+  };
+
+public:
+  static const Matcher &getInstance() {
+    static llvm::ManagedStatic<Wrapper> Instance;
+    return Instance->M;
+  }
+};
+
 // Define the create() method out of line to silence a GCC warning about
 // the struct "Func" having greater visibility than its base, which comes from
 // using the flag -fvisibility-inlines-hidden.
diff --git a/include/clang/ASTMatchers/ASTMatchersMacros.h b/include/clang/ASTMatchers/ASTMatchersMacros.h
index 4d57b94..7167dfb 100644
--- a/include/clang/ASTMatchers/ASTMatchersMacros.h
+++ b/include/clang/ASTMatchers/ASTMatchersMacros.h
@@ -37,6 +37,17 @@
 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSMACROS_H
 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSMACROS_H
 
+/// \brief AST_MATCHER_FUNCTION(ReturnType, DefineMatcher) {
+/// defines a zero parameter function named DefineMatcher() that returns a
+/// ReturnType object.
+#define AST_MATCHER_FUNCTION(ReturnType, DefineMatcher)                        \
+  inline ReturnType DefineMatcher##_getInstance();                             \
+  inline ReturnType DefineMatcher() {                                          \
+    return internal::MemoizedMatcher<                                          \
+        ReturnType, DefineMatcher##_getInstance>::getInstance();               \
+  }                                                                            \
+  inline ReturnType DefineMatcher##_getInstance()
+
 /// \brief AST_MATCHER_FUNCTION_P(ReturnType, DefineMatcher, ParamType, Param) {
 /// defines a single-parameter function named DefineMatcher() that returns a
 /// ReturnType object.
@@ -190,7 +201,7 @@
 #define AST_POLYMORPHIC_SUPPORTED_TYPES_4(t1, t2, t3, t4)                      \
   void(internal::TypeList<t1, t2, t3, t4>)
 #define AST_POLYMORPHIC_SUPPORTED_TYPES_5(t1, t2, t3, t4, t5)                  \
-  void(internal::TypeList<t1, t2, t3, internal::TypeList<t4, t5> >)
+  void(internal::TypeList<t1, t2, t3, t4, t5>)
 
 /// \brief AST_POLYMORPHIC_MATCHER(DefineMatcher) { ... }
 /// defines a single-parameter function named DefineMatcher() that is
diff --git a/include/clang/ASTMatchers/Dynamic/Registry.h b/include/clang/ASTMatchers/Dynamic/Registry.h
index ad24a8d..fc1e783 100644
--- a/include/clang/ASTMatchers/Dynamic/Registry.h
+++ b/include/clang/ASTMatchers/Dynamic/Registry.h
@@ -123,7 +123,7 @@
                                               Diagnostics *Error);
 
 private:
-  Registry() LLVM_DELETED_FUNCTION;
+  Registry() = delete;
 };
 
 }  // namespace dynamic
diff --git a/include/clang/ASTMatchers/Dynamic/VariantValue.h b/include/clang/ASTMatchers/Dynamic/VariantValue.h
index a9bd3d5..ae22e37 100644
--- a/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -258,7 +258,7 @@
   VariantValue(const VariantMatcher &Matchers);
 
   /// \brief Returns true iff this is not an empty value.
-  LLVM_EXPLICIT operator bool() const { return hasValue(); }
+  explicit operator bool() const { return hasValue(); }
   bool hasValue() const { return Type != VT_Nothing; }
 
   /// \brief Unsigned value functions.
diff --git a/include/clang/Analysis/Analyses/FormatString.h b/include/clang/Analysis/Analyses/FormatString.h
index 174cce4..d67aa51 100644
--- a/include/clang/Analysis/Analyses/FormatString.h
+++ b/include/clang/Analysis/Analyses/FormatString.h
@@ -49,7 +49,7 @@
   const char *toString() const { return representation; }
 
   // Overloaded operators for bool like qualities
-  LLVM_EXPLICIT operator bool() const { return flag; }
+  explicit operator bool() const { return flag; }
   OptionalFlag& operator=(const bool &rhs) {
     flag = rhs;
     return *this;  // Return a reference to myself.
@@ -161,6 +161,12 @@
     ObjCObjArg,  // '@'
     ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg,
 
+    // FreeBSD kernel specific specifiers.
+    FreeBSDbArg,
+    FreeBSDDArg,
+    FreeBSDrArg,
+    FreeBSDyArg,
+
     // GlibC specific specifiers.
     PrintErrno,   // 'm'
 
@@ -204,7 +210,8 @@
     return EndScanList ? EndScanList - Position : 1;
   }
 
-  bool isIntArg() const { return kind >= IntArgBeg && kind <= IntArgEnd; }
+  bool isIntArg() const { return (kind >= IntArgBeg && kind <= IntArgEnd) ||
+    kind == FreeBSDrArg || kind == FreeBSDyArg; }
   bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; }
   bool isAnyIntArg() const { return kind >= IntArgBeg && kind <= UIntArgEnd; }
   const char *toString() const;
@@ -646,7 +653,7 @@
 
 bool ParsePrintfString(FormatStringHandler &H,
                        const char *beg, const char *end, const LangOptions &LO,
-                       const TargetInfo &Target);
+                       const TargetInfo &Target, bool isFreeBSDKPrintf);
   
 bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO,
                               const TargetInfo &Target);
diff --git a/include/clang/Analysis/Analyses/ThreadSafety.h b/include/clang/Analysis/Analyses/ThreadSafety.h
index 458bb57..eeadb77 100644
--- a/include/clang/Analysis/Analyses/ThreadSafety.h
+++ b/include/clang/Analysis/Analyses/ThreadSafety.h
@@ -26,6 +26,8 @@
 namespace clang {
 namespace threadSafety {
 
+class BeforeSet;
+
 /// This enum distinguishes between different kinds of operations that may
 /// need to be protected by locks. We use this enum in error handling.
 enum ProtectedOperationKind {
@@ -183,6 +185,14 @@
   virtual void handleFunExcludesLock(StringRef Kind, Name FunName,
                                      Name LockName, SourceLocation Loc) {}
 
+
+  /// Warn that L1 cannot be acquired before L2.
+  virtual void handleLockAcquiredBefore(StringRef Kind, Name L1Name,
+                                        Name L2Name, SourceLocation Loc) {}
+
+  /// Warn that there is a cycle in acquired_before/after dependencies.
+  virtual void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) {}
+
   /// Called by the analysis when starting analysis of a function.
   /// Used to issue suggestions for changes to annotations.
   virtual void enterFunction(const FunctionDecl *FD) {}
@@ -203,7 +213,8 @@
 /// at the end of each block, and issue warnings for thread safety violations.
 /// Each block in the CFG is traversed exactly once.
 void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
-                             ThreadSafetyHandler &Handler);
+                             ThreadSafetyHandler &Handler,
+                             BeforeSet **Bset);
 
 /// \brief Helper function that returns a LockKind required for the given level
 /// of access.
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyCommon.h b/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
index 76d8389..9b7725a 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
@@ -27,7 +27,6 @@
 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Basic/OperatorKinds.h"
-
 #include <memory>
 #include <ostream>
 #include <sstream>
@@ -287,6 +286,14 @@
             sx::partiallyMatches(CapExpr, other.CapExpr);
   }
 
+  const ValueDecl* valueDecl() const {
+    if (Negated)
+      return nullptr;
+    if (auto *P = dyn_cast<til::Project>(CapExpr))
+      return P->clangDecl();
+    return nullptr;
+  }
+
   std::string toString() const {
     if (Negated)
       return "!" + sx::toString(CapExpr);
@@ -423,8 +430,8 @@
     }
 
   private:
-    BlockInfo(const BlockInfo &) LLVM_DELETED_FUNCTION;
-    void operator=(const BlockInfo &) LLVM_DELETED_FUNCTION;
+    BlockInfo(const BlockInfo &) = delete;
+    void operator=(const BlockInfo &) = delete;
   };
 
   // We implement the CFGVisitor API
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyTIL.h b/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
index e06593c..4b59466 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
@@ -50,11 +50,10 @@
 // All clang include dependencies for this file must be put in
 // ThreadSafetyUtil.h.
 #include "ThreadSafetyUtil.h"
-
-#include <stdint.h>
 #include <algorithm>
 #include <cassert>
 #include <cstddef>
+#include <stdint.h>
 #include <utility>
 
 
@@ -283,7 +282,7 @@
   /// SExpr objects cannot be deleted.
   // This declaration is public to workaround a gcc bug that breaks building
   // with REQUIRES_EH=1.
-  void operator delete(void *) LLVM_DELETED_FUNCTION;
+  void operator delete(void *) = delete;
 
   /// Returns the instruction ID for this expression.
   /// All basic block instructions have a unique ID (i.e. virtual register).
@@ -310,10 +309,10 @@
   BasicBlock* Block;
 
 private:
-  SExpr() LLVM_DELETED_FUNCTION;
+  SExpr() = delete;
 
   /// SExpr objects must be created in an arena.
-  void *operator new(size_t) LLVM_DELETED_FUNCTION;
+  void *operator new(size_t) = delete;
 };
 
 
@@ -425,7 +424,7 @@
   Future() : SExpr(COP_Future), Status(FS_pending), Result(nullptr) {}
 
 private:
-  virtual ~Future() LLVM_DELETED_FUNCTION;
+  virtual ~Future() = delete;
 
 public:
   // A lazy rewriting strategy should subclass Future and override this method.
@@ -1369,7 +1368,7 @@
   ArrayRef<BasicBlock*> successors();
 
   ArrayRef<BasicBlock*> successors() const {
-    return const_cast<const Terminator*>(this)->successors();
+    return const_cast<Terminator*>(this)->successors();
   }
 };
 
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h b/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
index 541f0bf..705fe91 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
@@ -18,7 +18,6 @@
 #define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H
 
 #include "ThreadSafetyTIL.h"
-
 #include <ostream>
 
 namespace clang {
diff --git a/include/clang/Analysis/Analyses/ThreadSafetyUtil.h b/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
index 5a75724..42808a8 100644
--- a/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
+++ b/include/clang/Analysis/Analyses/ThreadSafetyUtil.h
@@ -14,17 +14,16 @@
 #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYUTIL_H
 #define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYUTIL_H
 
+#include "clang/AST/ExprCXX.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/AlignOf.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Compiler.h"
-#include "clang/AST/ExprCXX.h"
-
 #include <cassert>
 #include <cstddef>
-#include <vector>
-#include <utility>
 #include <ostream>
+#include <utility>
+#include <vector>
 
 namespace clang {
 namespace threadSafety {
@@ -227,7 +226,7 @@
 
   static const size_t InitialCapacity = 4;
 
-  SimpleArray(const SimpleArray<T> &A) LLVM_DELETED_FUNCTION;
+  SimpleArray(const SimpleArray<T> &A) = delete;
 
   T *Data;
   size_t Size;
@@ -256,8 +255,8 @@
   };
 
   // No copy constructor or copy assignment.  Use clone() with move assignment.
-  CopyOnWriteVector(const CopyOnWriteVector &V) LLVM_DELETED_FUNCTION;
-  void operator=(const CopyOnWriteVector &V) LLVM_DELETED_FUNCTION;
+  CopyOnWriteVector(const CopyOnWriteVector &V) = delete;
+  void operator=(const CopyOnWriteVector &V) = delete;
 
 public:
   CopyOnWriteVector() : Data(nullptr) {}
diff --git a/include/clang/Analysis/AnalysisContext.h b/include/clang/Analysis/AnalysisContext.h
index 0ebdf15..a20fc51 100644
--- a/include/clang/Analysis/AnalysisContext.h
+++ b/include/clang/Analysis/AnalysisContext.h
@@ -173,8 +173,8 @@
 
   typedef const VarDecl * const * referenced_decls_iterator;
 
-  std::pair<referenced_decls_iterator, referenced_decls_iterator>
-    getReferencedBlockVars(const BlockDecl *BD);
+  llvm::iterator_range<referenced_decls_iterator>
+  getReferencedBlockVars(const BlockDecl *BD);
 
   /// Return the ImplicitParamDecl* associated with 'self' if this
   /// AnalysisDeclContext wraps an ObjCMethodDecl.  Returns NULL otherwise.
diff --git a/include/clang/Analysis/CFG.h b/include/clang/Analysis/CFG.h
index beea867..3fddbb9 100644
--- a/include/clang/Analysis/CFG.h
+++ b/include/clang/Analysis/CFG.h
@@ -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.
diff --git a/include/clang/Basic/AddressSpaces.h b/include/clang/Basic/AddressSpaces.h
index 4b1cea5..8dd7566 100644
--- a/include/clang/Basic/AddressSpaces.h
+++ b/include/clang/Basic/AddressSpaces.h
@@ -30,6 +30,7 @@
   opencl_global = Offset,
   opencl_local,
   opencl_constant,
+  opencl_generic,
 
   cuda_device,
   cuda_constant,
diff --git a/include/clang/Basic/Attr.td b/include/clang/Basic/Attr.td
index 2450bdd..82e7a3b 100644
--- a/include/clang/Basic/Attr.td
+++ b/include/clang/Basic/Attr.td
@@ -115,6 +115,10 @@
 def FunctionLike : SubsetSubject<DeclBase,
                                   [{S->getFunctionType(false) != NULL}]>;
 
+def OpenCLKernelFunction : SubsetSubject<Function, [{
+  S->hasAttr<OpenCLKernelAttr>()
+}]>;
+
 // HasFunctionProto is a more strict version of FunctionLike, so it should
 // never be specified in a Subjects list along with FunctionLike (due to the
 // inclusive nature of subject testing).
@@ -220,12 +224,14 @@
   string CustomDiag = customDiag;
 }
 
-class LangOpt<string name> {
+class LangOpt<string name, bit negated = 0> {
   string Name = name;
+  bit Negated = negated;
 }
 def MicrosoftExt : LangOpt<"MicrosoftExt">;
 def Borland : LangOpt<"Borland">;
 def CUDA : LangOpt<"CUDA">;
+def COnly : LangOpt<"CPlusPlus", 1>;
 
 // Defines targets for target-specific attributes. The list of strings should
 // specify architectures for which the target applies, based off the ArchType
@@ -339,6 +345,8 @@
 def Alias : Attr {
   let Spellings = [GCC<"alias">];
   let Args = [StringArgument<"Aliasee">];
+  let Subjects = SubjectList<[Function, GlobalVar], ErrorDiag,
+                             "ExpectedFunctionGlobalVarMethodOrProperty">;
   let Documentation = [Undocumented];
 }
 
@@ -624,22 +632,27 @@
 
 def OpenCLPrivateAddressSpace : TypeAttr {
   let Spellings = [Keyword<"__private">, Keyword<"private">];
-  let Documentation = [Undocumented];
+  let Documentation = [OpenCLAddressSpacePrivateDocs];
 }
 
 def OpenCLGlobalAddressSpace : TypeAttr {
   let Spellings = [Keyword<"__global">, Keyword<"global">];
-  let Documentation = [Undocumented];
+  let Documentation = [OpenCLAddressSpaceGlobalDocs];
 }
 
 def OpenCLLocalAddressSpace : TypeAttr {
   let Spellings = [Keyword<"__local">, Keyword<"local">];
-  let Documentation = [Undocumented];
+  let Documentation = [OpenCLAddressSpaceLocalDocs];
 }
 
 def OpenCLConstantAddressSpace : TypeAttr {
   let Spellings = [Keyword<"__constant">, Keyword<"constant">];
-  let Documentation = [Undocumented];
+  let Documentation = [OpenCLAddressSpaceConstantDocs];
+}
+
+def OpenCLGenericAddressSpace : TypeAttr {
+  let Spellings = [Keyword<"__generic">, Keyword<"generic">];
+  let Documentation = [OpenCLAddressSpaceGenericDocs];
 }
 
 def Kernel : Attr {
@@ -703,6 +716,25 @@
   let Documentation = [Undocumented];
 }
 
+def FlagEnum : InheritableAttr {
+  let Spellings = [GNU<"flag_enum">];
+  let Subjects = SubjectList<[Enum]>;
+  let Documentation = [FlagEnumDocs];
+  let LangOpts = [COnly];
+  let AdditionalMembers = [{
+private:
+    llvm::APInt FlagBits;
+public:
+    llvm::APInt &getFlagBits() {
+      return FlagBits;
+    }
+
+    const llvm::APInt &getFlagBits() const {
+      return FlagBits;
+    }
+}];
+}
+
 def Flatten : InheritableAttr {
   let Spellings = [GCC<"flatten">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
@@ -763,9 +795,9 @@
   let Documentation = [Undocumented];
 }
 
-def Malloc : InheritableAttr {
-  let Spellings = [GCC<"malloc">];
-//  let Subjects = [Function];
+def Restrict : InheritableAttr {
+  let Spellings = [Declspec<"restrict">, GCC<"malloc">];
+  let Subjects = SubjectList<[Function]>;
   let Documentation = [Undocumented];
 }
 
@@ -864,6 +896,38 @@
   let Documentation = [Undocumented];
 }
 
+// This is not a TargetSpecificAttr so that is silently accepted and
+// ignored on other targets as encouraged by the OpenCL spec.
+//
+// See OpenCL 1.2 6.11.5: "It is our intention that a particular
+// implementation of OpenCL be free to ignore all attributes and the
+// resulting executable binary will produce the same result."
+//
+// However, only AMD GPU targets will emit the corresponding IR
+// attribute.
+//
+// FIXME: This provides a sub-optimal error message if you attempt to
+// use this in CUDA, since CUDA does not use the same terminology.
+def AMDGPUNumVGPR : InheritableAttr {
+  let Spellings = [GNU<"amdgpu_num_vgpr">];
+  let Args = [UnsignedArgument<"NumVGPR">];
+  let Documentation = [AMDGPUNumVGPRDocs];
+
+// FIXME: This should be for OpenCLKernelFunction, but is not to
+// workaround needing to see kernel attribute before others to know if
+// this should be rejected on non-kernels.
+  let Subjects = SubjectList<[Function], ErrorDiag,
+                             "ExpectedKernelFunction">;
+}
+
+def AMDGPUNumSGPR : InheritableAttr {
+  let Spellings = [GNU<"amdgpu_num_sgpr">];
+  let Args = [UnsignedArgument<"NumSGPR">];
+  let Documentation = [AMDGPUNumSGPRDocs];
+  let Subjects = SubjectList<[Function], ErrorDiag,
+                              "ExpectedKernelFunction">;
+}
+
 def NoSplitStack : InheritableAttr {
   let Spellings = [GCC<"no_split_stack">];
   let Subjects = SubjectList<[Function], ErrorDiag>;
@@ -922,7 +986,8 @@
 
 def ObjCBridge : InheritableAttr {
   let Spellings = [GNU<"objc_bridge">];
-  let Subjects = SubjectList<[Record], ErrorDiag>;
+  let Subjects = SubjectList<[Record, TypedefName], ErrorDiag,
+                             "ExpectedStructOrUnionOrTypedef">;
   let Args = [IdentifierArgument<"BridgedType">];
   let Documentation = [Undocumented];
 }
@@ -1082,12 +1147,6 @@
   let Documentation = [Undocumented];
 }
 
-def PnaclCall : InheritableAttr {
-  let Spellings = [GNU<"pnaclcall">];
-//  let Subjects = [Function, ObjCMethod];
-  let Documentation = [Undocumented];
-}
-
 def IntelOclBicc : InheritableAttr {
   let Spellings = [GNU<"intel_ocl_bicc">];
 //  let Subjects = [Function, ObjCMethod];
@@ -1707,11 +1766,17 @@
 
 // Microsoft-related attributes
 
-def MsProperty : IgnoredAttr {
+def MSNoVTable : InheritableAttr {
+  let Spellings = [Declspec<"novtable">];
+  let Subjects = SubjectList<[CXXRecord]>;
+  let Documentation = [MSNoVTableDocs];
+}
+
+def : IgnoredAttr {
   let Spellings = [Declspec<"property">];
 }
 
-def MsStruct : InheritableAttr {
+def MSStruct : InheritableAttr {
   let Spellings = [GCC<"ms_struct">];
   let Subjects = SubjectList<[Record]>;
   let Documentation = [Undocumented];
diff --git a/include/clang/Basic/AttrDocs.td b/include/clang/Basic/AttrDocs.td
index cf8b662..64e4cea 100644
--- a/include/clang/Basic/AttrDocs.td
+++ b/include/clang/Basic/AttrDocs.td
@@ -673,6 +673,66 @@
   }];
 }
 
+def DocCatAMDGPURegisterAttributes :
+  DocumentationCategory<"AMD GPU Register Attributes"> {
+  let Content = [{
+Clang supports attributes for controlling register usage on AMD GPU
+targets. These attributes may be attached to a kernel function
+definition and is an optimization hint to the backend for the maximum
+number of registers to use. This is useful in cases where register
+limited occupancy is known to be an important factor for the
+performance for the kernel.
+
+The semantics are as follows:
+
+- The backend will attempt to limit the number of used registers to
+  the specified value, but the exact number used is not
+  guaranteed. The number used may be rounded up to satisfy the
+  allocation requirements or ABI constraints of the subtarget. For
+  example, on Southern Islands VGPRs may only be allocated in
+  increments of 4, so requesting a limit of 39 VGPRs will really
+  attempt to use up to 40. Requesting more registers than the
+  subtarget supports will truncate to the maximum allowed. The backend
+  may also use fewer registers than requested whenever possible.
+
+- 0 implies the default no limit on register usage.
+
+- Ignored on older VLIW subtargets which did not have separate scalar
+  and vector registers, R600 through Northern Islands.
+
+}];
+}
+
+
+def AMDGPUNumVGPRDocs : Documentation {
+  let Category = DocCatAMDGPURegisterAttributes;
+  let Content = [{
+Clang supports the
+``__attribute__((amdgpu_num_vgpr(<num_registers>)))`` attribute on AMD
+Southern Islands GPUs and later for controlling the number of vector
+registers. A typical value would be between 4 and 256 in increments
+of 4.
+}];
+}
+
+def AMDGPUNumSGPRDocs : Documentation {
+  let Category = DocCatAMDGPURegisterAttributes;
+  let Content = [{
+
+Clang supports the
+``__attribute__((amdgpu_num_sgpr(<num_registers>)))`` attribute on AMD
+Southern Islands GPUs and later for controlling the number of scalar
+registers. A typical value would be between 8 and 104 in increments of
+8.
+
+Due to common instruction constraints, an additional 2-4 SGPRs are
+typically required for internal use depending on features used. This
+value is a hint for the total number of SGPRs to use, and not the
+number of user SGPRs, so no special consideration needs to be given
+for these.
+}];
+}
+
 def DocCatCallingConvs : DocumentationCategory<"Calling Conventions"> {
   let Content = [{
 Clang supports several different calling conventions, depending on the target
@@ -1136,6 +1196,16 @@
   }];
 }
 
+def FlagEnumDocs : Documentation {
+  let Category = DocCatType;
+  let Content = [{
+This attribute can be added to an enumerator to signal to the compiler that it
+is intended to be used as a flag type. This will cause the compiler to assume
+that the range of the type includes all of the values that you can get by
+manipulating bits of the enumerator when issuing warnings.
+  }];
+}
+
 def MSInheritanceDocs : Documentation {
   let Category = DocCatType;
   let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
@@ -1183,6 +1253,15 @@
 }];
 }
 
+def MSNoVTableDocs : Documentation {
+  let Category = DocCatType;
+  let Content = [{
+This attribute can be added to a class declaration or definition to signal to
+the compiler that constructors and destructors will not reference the virtual
+function table.
+  }];
+}
+
 def OptnoneDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
@@ -1194,7 +1273,8 @@
 specified function can improve the quality of the debugging information
 for that function.
 
-This attribute is incompatible with the ``always_inline`` attribute.
+This attribute is incompatible with the ``always_inline`` and ``minsize``
+attributes.
   }];
 }
 
@@ -1265,3 +1345,88 @@
   }];
 }
 
+def DocOpenCLAddressSpaces : DocumentationCategory<"OpenCL Address Spaces"> {
+  let Content = [{
+The address space qualifier may be used to specify the region of memory that is
+used to allocate the object. OpenCL supports the following address spaces:
+__generic(generic), __global(global), __local(local), __private(private),
+__constant(constant).
+
+  .. code-block:: c
+
+    __constant int c = ...;
+
+    __generic int* foo(global int* g) {
+      __local int* l;
+      private int p;
+      ...
+      return l;
+    }
+
+More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
+  }];
+}
+
+def OpenCLAddressSpaceGenericDocs : Documentation {
+  let Category = DocOpenCLAddressSpaces;
+  let Heading = "__generic(generic)";
+  let Content = [{
+The generic address space attribute is only available with OpenCL v2.0 and later.
+It can be used with pointer types. Variables in global and local scope and
+function parameters in non-kernel functions can have the generic address space
+type attribute. It is intended to be a placeholder for any other address space
+except for '__constant' in OpenCL code which can be used with multiple address
+spaces.
+  }];
+}
+
+def OpenCLAddressSpaceConstantDocs : Documentation {
+  let Category = DocOpenCLAddressSpaces;
+  let Heading = "__constant(constant)";
+  let Content = [{
+The constant address space attribute signals that an object is located in
+a constant (non-modifiable) memory region. It is available to all work items.
+Any type can be annotated with the constant address space attribute. Objects
+with the constant address space qualifier can be declared in any scope and must
+have an initializer.
+  }];
+}
+
+def OpenCLAddressSpaceGlobalDocs : Documentation {
+  let Category = DocOpenCLAddressSpaces;
+  let Heading = "__global(global)";
+  let Content = [{
+The global address space attribute specifies that an object is allocated in
+global memory, which is accessible by all work items. The content stored in this
+memory area persists between kernel executions. Pointer types to the global
+address space are allowed as function parameters or local variables. Starting
+with OpenCL v2.0, the global address space can be used with global (program
+scope) variables and static local variable as well.
+  }];
+}
+
+def OpenCLAddressSpaceLocalDocs : Documentation {
+  let Category = DocOpenCLAddressSpaces;
+  let Heading = "__local(local)";
+  let Content = [{
+The local address space specifies that an object is allocated in the local (work
+group) memory area, which is accessible to all work items in the same work
+group. The content stored in this memory region is not accessible after
+the kernel execution ends. In a kernel function scope, any variable can be in
+the local address space. In other scopes, only pointer types to the local address
+space are allowed. Local address space variables cannot have an initializer.
+  }];
+}
+
+def OpenCLAddressSpacePrivateDocs : Documentation {
+  let Category = DocOpenCLAddressSpaces;
+  let Heading = "__private(private)";
+  let Content = [{
+The private address space specifies that an object is allocated in the private
+(work item) memory. Other work items cannot access the same memory area and its
+content is destroyed after work item execution ends. Local variables can be
+declared in the private address space. Function arguments are always in the
+private address space. Kernel function arguments of a pointer or an array type
+cannot point to the private address space.
+  }];
+}
diff --git a/include/clang/Basic/Attributes.h b/include/clang/Basic/Attributes.h
index 982e12d..a64dd56 100644
--- a/include/clang/Basic/Attributes.h
+++ b/include/clang/Basic/Attributes.h
@@ -10,16 +10,14 @@
 #ifndef LLVM_CLANG_BASIC_ATTRIBUTES_H
 #define LLVM_CLANG_BASIC_ATTRIBUTES_H
 
-#include "llvm/ADT/Triple.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/Triple.h"
 
 namespace clang {
 
 class IdentifierInfo;
 
 enum class AttrSyntax {
-  /// Is the attribute identifier generally known for any syntax?
-  Generic,
   /// Is the identifier known as a GNU-style attribute?
   GNU,
   /// Is the identifier known as a __declspec-style attribute?
diff --git a/include/clang/Basic/Builtins.def b/include/clang/Basic/Builtins.def
index dc668a1..632509b 100644
--- a/include/clang/Basic/Builtins.def
+++ b/include/clang/Basic/Builtins.def
@@ -448,8 +448,8 @@
 BUILTIN(__builtin_frame_address, "v*IUi", "n")
 BUILTIN(__builtin___clear_cache, "vc*c*", "n")
 BUILTIN(__builtin_flt_rounds, "i", "nc")
-BUILTIN(__builtin_setjmp, "iv**", "j")
-BUILTIN(__builtin_longjmp, "vv**i", "r")
+BUILTIN(__builtin_setjmp, "iv**", "Fj")
+BUILTIN(__builtin_longjmp, "vv**i", "Fr")
 BUILTIN(__builtin_unwind_init, "v", "")
 BUILTIN(__builtin_eh_return_data_regno, "iIi", "nc")
 BUILTIN(__builtin_snprintf, "ic*zcC*.", "nFp:2:")
@@ -497,6 +497,7 @@
 BUILTIN(__builtin_shufflevector, "v."   , "nc")
 BUILTIN(__builtin_convertvector, "v."   , "nct")
 BUILTIN(__builtin_alloca, "v*z"   , "n")
+BUILTIN(__builtin_call_with_static_chain, "v.", "nt")
 
 // "Overloaded" Atomic operator builtins.  These are overloaded to support data
 // types of i8, i16, i32, i64, and i128.  The front-end sees calls to the
@@ -691,19 +692,28 @@
 BUILTIN(__builtin_rindex, "c*cC*i", "Fn")
 
 // Microsoft builtins.  These are only active with -fms-extensions.
-LANGBUILTIN(_alloca,      "v*z", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(__assume,     "vb",  "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(__noop,       "i.",  "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(__debugbreak, "v",   "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(__va_start,   "vc**.", "nt", ALL_MS_LANGUAGES)
+LANGBUILTIN(_alloca,          "v*z", "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__assume,         "vb",  "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__debugbreak,     "v",   "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__exception_code, "ULi", "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_exception_code,  "ULi", "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__exception_info, "v*",  "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_exception_info,  "v*",  "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__abnormal_termination, "i", "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_abnormal_termination,  "i", "n", ALL_MS_LANGUAGES)
 LANGBUILTIN(_InterlockedCompareExchange, "LiLiD*LiLi", "n", ALL_MS_LANGUAGES)
 LANGBUILTIN(_InterlockedCompareExchangePointer, "v*v*D*v*v*", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(_InterlockedIncrement, "LiLiD*", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(_InterlockedDecrement, "LiLiD*", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(_InterlockedExchangeAdd, "LiLiD*Li", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(_InterlockedExchangePointer, "v*v*D*v*", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(_InterlockedExchange, "LiLiD*Li", "n", ALL_MS_LANGUAGES)
-LANGBUILTIN(__readfsdword, "ULiULi", "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_InterlockedDecrement,       "LiLiD*",     "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_InterlockedExchangeAdd,     "LiLiD*Li",   "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_InterlockedExchange,        "LiLiD*Li",   "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_InterlockedExchangePointer, "v*v*D*v*",   "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(_InterlockedIncrement,       "LiLiD*",     "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__noop,           "i.",  "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__readfsdword,    "ULiULi", "n", ALL_MS_LANGUAGES)
+LANGBUILTIN(__va_start,       "vc**.", "nt", ALL_MS_LANGUAGES)
+
+// Microsoft library builtins.
+LIBBUILTIN(_setjmpex, "iJ", "fj",   "setjmpex.h", ALL_MS_LANGUAGES)
 
 // C99 library functions
 // C99 stdlib.h
diff --git a/include/clang/Basic/Builtins.h b/include/clang/Basic/Builtins.h
index f9d30e4..3ce2255 100644
--- a/include/clang/Basic/Builtins.h
+++ b/include/clang/Basic/Builtins.h
@@ -29,7 +29,7 @@
   class ASTContext;
   class QualType;
   class LangOptions;
-  
+
   enum LanguageID {
     GNU_LANG = 0x1,  // builtin requires GNU mode.
     C_LANG = 0x2,    // builtin for c only.
@@ -40,7 +40,7 @@
     ALL_GNU_LANGUAGES = ALL_LANGUAGES | GNU_LANG,  // builtin requires GNU mode.
     ALL_MS_LANGUAGES = ALL_LANGUAGES | MS_LANG     // builtin requires MS mode.
   };
-  
+
 namespace Builtin {
 enum ID {
   NotBuiltin  = 0,      // This is not a builtin function.
diff --git a/include/clang/Basic/BuiltinsARM.def b/include/clang/Basic/BuiltinsARM.def
index 1f2f9a3..98d5ab7 100644
--- a/include/clang/Basic/BuiltinsARM.def
+++ b/include/clang/Basic/BuiltinsARM.def
@@ -85,6 +85,8 @@
 BUILTIN(__builtin_arm_prefetch, "vvC*UiUi", "nc")
 
 // MSVC
+LANGBUILTIN(__emit, "vIUiC", "", ALL_MS_LANGUAGES)
+
 LANGBUILTIN(__yield, "v", "", ALL_MS_LANGUAGES)
 LANGBUILTIN(__wfe, "v", "", ALL_MS_LANGUAGES)
 LANGBUILTIN(__wfi, "v", "", ALL_MS_LANGUAGES)
@@ -94,7 +96,7 @@
 LANGBUILTIN(__dmb, "vUi", "nc", ALL_MS_LANGUAGES)
 LANGBUILTIN(__dsb, "vUi", "nc", ALL_MS_LANGUAGES)
 LANGBUILTIN(__isb, "vUi", "nc", ALL_MS_LANGUAGES)
-LANGBUILTIN(__ldrexd, "WiCDWi*", "", ALL_MS_LANGUAGES)
+LANGBUILTIN(__ldrexd, "WiWiCD*", "", ALL_MS_LANGUAGES)
 LANGBUILTIN(_MoveFromCoprocessor, "UiUiUiUiUiUi", "", ALL_MS_LANGUAGES)
 LANGBUILTIN(_MoveFromCoprocessor2, "UiUiUiUiUiUi", "", ALL_MS_LANGUAGES)
 LANGBUILTIN(_MoveToCoprocessor, "vUiUiUiUiUiUi", "", ALL_MS_LANGUAGES)
diff --git a/include/clang/Basic/BuiltinsNVPTX.def b/include/clang/Basic/BuiltinsNVPTX.def
index 7e9b5ee..9c920dc 100644
--- a/include/clang/Basic/BuiltinsNVPTX.def
+++ b/include/clang/Basic/BuiltinsNVPTX.def
@@ -139,8 +139,8 @@
 
 // Sad
 
-BUILTIN(__nvvm_sad_i, "iii", "")
-BUILTIN(__nvvm_sad_ui, "UiUiUi", "")
+BUILTIN(__nvvm_sad_i, "iiii", "")
+BUILTIN(__nvvm_sad_ui, "UiUiUiUi", "")
 
 // Floor, Ceil
 
@@ -255,19 +255,19 @@
 
 // Add
 
-BUILTIN(__nvvm_add_rn_ftz_f, "ff", "")
-BUILTIN(__nvvm_add_rn_f, "ff", "")
-BUILTIN(__nvvm_add_rz_ftz_f, "ff", "")
-BUILTIN(__nvvm_add_rz_f, "ff", "")
-BUILTIN(__nvvm_add_rm_ftz_f, "ff", "")
-BUILTIN(__nvvm_add_rm_f, "ff", "")
-BUILTIN(__nvvm_add_rp_ftz_f, "ff", "")
-BUILTIN(__nvvm_add_rp_f, "ff", "")
+BUILTIN(__nvvm_add_rn_ftz_f, "fff", "")
+BUILTIN(__nvvm_add_rn_f, "fff", "")
+BUILTIN(__nvvm_add_rz_ftz_f, "fff", "")
+BUILTIN(__nvvm_add_rz_f, "fff", "")
+BUILTIN(__nvvm_add_rm_ftz_f, "fff", "")
+BUILTIN(__nvvm_add_rm_f, "fff", "")
+BUILTIN(__nvvm_add_rp_ftz_f, "fff", "")
+BUILTIN(__nvvm_add_rp_f, "fff", "")
 
-BUILTIN(__nvvm_add_rn_d, "dd", "")
-BUILTIN(__nvvm_add_rz_d, "dd", "")
-BUILTIN(__nvvm_add_rm_d, "dd", "")
-BUILTIN(__nvvm_add_rp_d, "dd", "")
+BUILTIN(__nvvm_add_rn_d, "ddd", "")
+BUILTIN(__nvvm_add_rz_d, "ddd", "")
+BUILTIN(__nvvm_add_rm_d, "ddd", "")
+BUILTIN(__nvvm_add_rp_d, "ddd", "")
 
 // Convert
 
diff --git a/include/clang/Basic/BuiltinsR600.def b/include/clang/Basic/BuiltinsR600.def
index 79a82f7..84fc4fa 100644
--- a/include/clang/Basic/BuiltinsR600.def
+++ b/include/clang/Basic/BuiltinsR600.def
@@ -30,5 +30,7 @@
 BUILTIN(__builtin_amdgpu_rsq_clampedf, "ff", "nc")
 BUILTIN(__builtin_amdgpu_ldexp, "ddi", "nc")
 BUILTIN(__builtin_amdgpu_ldexpf, "ffi", "nc")
+BUILTIN(__builtin_amdgpu_class, "bdi", "nc")
+BUILTIN(__builtin_amdgpu_classf, "bfi", "nc")
 
 #undef BUILTIN
diff --git a/include/clang/Basic/BuiltinsX86.def b/include/clang/Basic/BuiltinsX86.def
index 79bfd4b..4ed8f48 100644
--- a/include/clang/Basic/BuiltinsX86.def
+++ b/include/clang/Basic/BuiltinsX86.def
@@ -187,13 +187,45 @@
 BUILTIN(__builtin_ia32_ucomisdge, "iV2dV2d", "")
 BUILTIN(__builtin_ia32_ucomisdneq, "iV2dV2d", "")
 BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "")
+BUILTIN(__builtin_ia32_cmpeqps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpltps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpleps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpunordps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpneqps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpnltps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpnleps, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpordps, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "")
+BUILTIN(__builtin_ia32_cmpeqss, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpltss, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpless, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpunordss, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpneqss, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpnltss, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpnless, "V4fV4fV4f", "")
+BUILTIN(__builtin_ia32_cmpordss, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "")
+BUILTIN(__builtin_ia32_cmpeqpd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpltpd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmplepd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpunordpd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpneqpd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpnltpd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpnlepd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpordpd, "V2dV2dV2d", "")
 BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "")
+BUILTIN(__builtin_ia32_cmpeqsd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpltsd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmplesd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpunordsd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpneqsd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpnltsd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpnlesd, "V2dV2dV2d", "")
+BUILTIN(__builtin_ia32_cmpordsd, "V2dV2dV2d", "")
 BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "")
 BUILTIN(__builtin_ia32_maxpd, "V2dV2dV2d", "")
 BUILTIN(__builtin_ia32_minsd, "V2dV2dV2d", "")
@@ -284,8 +316,6 @@
 BUILTIN(__builtin_ia32_psrad128, "V4iV4iV4i", "")
 BUILTIN(__builtin_ia32_psrlw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_psrld128, "V4iV4iV4i", "")
-BUILTIN(__builtin_ia32_pslldqi128, "V2LLiV2LLiIi", "")
-BUILTIN(__builtin_ia32_psrldqi128, "V2LLiV2LLiIi", "")
 BUILTIN(__builtin_ia32_psrlq128, "V2LLiV2LLiV2LLi", "")
 BUILTIN(__builtin_ia32_psllw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_pslld128, "V4iV4iV4i", "")
@@ -307,8 +337,6 @@
 
 BUILTIN(__builtin_ia32_pblendvb128, "V16cV16cV16cV16c", "")
 BUILTIN(__builtin_ia32_pblendw128, "V8sV8sV8sIc", "")
-BUILTIN(__builtin_ia32_blendpd, "V2dV2dV2dIc", "")
-BUILTIN(__builtin_ia32_blendps, "V4fV4fV4fIc", "")
 BUILTIN(__builtin_ia32_blendvpd, "V2dV2dV2dV2d", "")
 BUILTIN(__builtin_ia32_blendvps, "V4fV4fV4fV4f", "")
 
@@ -404,13 +432,11 @@
 BUILTIN(__builtin_ia32_vpermilvarps, "V4fV4fV4i", "")
 BUILTIN(__builtin_ia32_vpermilvarpd256, "V4dV4dV4LLi", "")
 BUILTIN(__builtin_ia32_vpermilvarps256, "V8fV8fV8i", "")
-BUILTIN(__builtin_ia32_blendpd256, "V4dV4dV4dIc", "")
-BUILTIN(__builtin_ia32_blendps256, "V8fV8fV8fIc", "")
 BUILTIN(__builtin_ia32_blendvpd256, "V4dV4dV4dV4d", "")
 BUILTIN(__builtin_ia32_blendvps256, "V8fV8fV8fV8f", "")
 BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fIc", "")
-BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dc", "")
-BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fc", "")
+BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dIc", "")
+BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fIc", "")
 BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dIc", "")
 BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fIc", "")
 BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8iIc", "")
@@ -706,12 +732,12 @@
 BUILTIN(__builtin_ia32_vfmaddsubpd256, "V4dV4dV4dV4d", "")
 BUILTIN(__builtin_ia32_vfmsubaddps256, "V8fV8fV8fV8f", "")
 BUILTIN(__builtin_ia32_vfmsubaddpd256, "V4dV4dV4dV4d", "")
-BUILTIN(__builtin_ia32_vfmaddpd512_mask,  "V8dV8dV8dV8dUci", "")
-BUILTIN(__builtin_ia32_vfmsubpd512_mask,  "V8dV8dV8dV8dUci", "")
-BUILTIN(__builtin_ia32_vfnmaddpd512_mask, "V8dV8dV8dV8dUci", "")
-BUILTIN(__builtin_ia32_vfmaddps512_mask,  "V16fV16fV16fV16fUsi", "")
-BUILTIN(__builtin_ia32_vfmsubps512_mask,  "V16fV16fV16fV16fUsi", "")
-BUILTIN(__builtin_ia32_vfnmaddps512_mask, "V16fV16fV16fV16fUsi", "")
+BUILTIN(__builtin_ia32_vfmaddpd512_mask,  "V8dV8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_vfmsubpd512_mask,  "V8dV8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_vfnmaddpd512_mask, "V8dV8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_vfmaddps512_mask,  "V16fV16fV16fV16fUsIi", "")
+BUILTIN(__builtin_ia32_vfmsubps512_mask,  "V16fV16fV16fV16fUsIi", "")
+BUILTIN(__builtin_ia32_vfnmaddps512_mask, "V16fV16fV16fV16fUsIi", "")
 
 // XOP
 BUILTIN(__builtin_ia32_vpmacssww, "V8sV8sV8sV8s", "")
@@ -788,29 +814,31 @@
 BUILTIN(__builtin_ia32_rdtscp, "ULLiUi*", "")
 
 // AVX-512
-BUILTIN(__builtin_ia32_sqrtpd512_mask, "V8dV8dV8dUcCi", "")
-BUILTIN(__builtin_ia32_sqrtps512_mask, "V16fV16fV16fUsCi", "")
+BUILTIN(__builtin_ia32_sqrtpd512_mask, "V8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_sqrtps512_mask, "V16fV16fV16fUsIi", "")
 BUILTIN(__builtin_ia32_rsqrt14sd_mask, "V2dV2dV2dV2dUc", "")
 BUILTIN(__builtin_ia32_rsqrt14ss_mask, "V4fV4fV4fV4fUc", "")
 BUILTIN(__builtin_ia32_rsqrt14pd512_mask, "V8dV8dV8dUc", "")
 BUILTIN(__builtin_ia32_rsqrt14ps512_mask, "V16fV16fV16fUs", "")
-BUILTIN(__builtin_ia32_rsqrt28sd_mask, "V2dV2dV2dV2dUcCi", "")
-BUILTIN(__builtin_ia32_rsqrt28ss_mask, "V4fV4fV4fV4fUcCi", "")
-BUILTIN(__builtin_ia32_rsqrt28pd_mask, "V8dV8dV8dUcCi", "")
-BUILTIN(__builtin_ia32_rsqrt28ps_mask, "V16fV16fV16fUsCi", "")
+BUILTIN(__builtin_ia32_rsqrt28sd_mask, "V2dV2dV2dV2dUcIi", "")
+BUILTIN(__builtin_ia32_rsqrt28ss_mask, "V4fV4fV4fV4fUcIi", "")
+BUILTIN(__builtin_ia32_rsqrt28pd_mask, "V8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_rsqrt28ps_mask, "V16fV16fV16fUsIi", "")
 BUILTIN(__builtin_ia32_rcp14sd_mask, "V2dV2dV2dV2dUc", "")
 BUILTIN(__builtin_ia32_rcp14ss_mask, "V4fV4fV4fV4fUc", "")
 BUILTIN(__builtin_ia32_rcp14pd512_mask, "V8dV8dV8dUc", "")
 BUILTIN(__builtin_ia32_rcp14ps512_mask, "V16fV16fV16fUs", "")
-BUILTIN(__builtin_ia32_rcp28sd_mask, "V2dV2dV2dV2dUcCi", "")
-BUILTIN(__builtin_ia32_rcp28ss_mask, "V4fV4fV4fV4fUcCi", "")
-BUILTIN(__builtin_ia32_rcp28pd_mask, "V8dV8dV8dUcCi", "")
-BUILTIN(__builtin_ia32_rcp28ps_mask, "V16fV16fV16fUsCi", "")
-BUILTIN(__builtin_ia32_cvttps2dq512_mask, "V16iV16fV16iUsCi", "")
-BUILTIN(__builtin_ia32_cvttps2udq512_mask, "V16iV16fV16iUsCi", "")
-BUILTIN(__builtin_ia32_cvttpd2dq512_mask, "V8iV8dV8iUcCi", "")
-BUILTIN(__builtin_ia32_cvttpd2udq512_mask, "V8iV8dV8iUcCi", "")
-BUILTIN(__builtin_ia32_cmpps512_mask, "UsV16fV16fCiUsi", "")
+BUILTIN(__builtin_ia32_rcp28sd_mask, "V2dV2dV2dV2dUcIi", "")
+BUILTIN(__builtin_ia32_rcp28ss_mask, "V4fV4fV4fV4fUcIi", "")
+BUILTIN(__builtin_ia32_rcp28pd_mask, "V8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_rcp28ps_mask, "V16fV16fV16fUsIi", "")
+BUILTIN(__builtin_ia32_exp2pd_mask, "V8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_exp2ps_mask, "V16fV16fV16fUsIi", "")
+BUILTIN(__builtin_ia32_cvttps2dq512_mask, "V16iV16fV16iUsIi", "")
+BUILTIN(__builtin_ia32_cvttps2udq512_mask, "V16iV16fV16iUsIi", "")
+BUILTIN(__builtin_ia32_cvttpd2dq512_mask, "V8iV8dV8iUcIi", "")
+BUILTIN(__builtin_ia32_cvttpd2udq512_mask, "V8iV8dV8iUcIi", "")
+BUILTIN(__builtin_ia32_cmpps512_mask, "UsV16fV16fIcUsIi", "")
 BUILTIN(__builtin_ia32_pcmpeqb512_mask, "LLiV64cV64cLLi", "")
 BUILTIN(__builtin_ia32_pcmpeqd512_mask, "sV16iV16is", "")
 BUILTIN(__builtin_ia32_pcmpeqq512_mask, "cV8LLiV8LLic", "")
@@ -823,24 +851,36 @@
 BUILTIN(__builtin_ia32_pcmpeqd128_mask, "cV4iV4ic", "")
 BUILTIN(__builtin_ia32_pcmpeqq128_mask, "cV2LLiV2LLic", "")
 BUILTIN(__builtin_ia32_pcmpeqw128_mask, "cV8sV8sc", "")
-BUILTIN(__builtin_ia32_cmppd512_mask, "UcV8dV8dCiUci", "")
-BUILTIN(__builtin_ia32_rndscaleps_mask, "V16fV16fCiV16fUsCi", "")
-BUILTIN(__builtin_ia32_rndscalepd_mask, "V8dV8dCiV8dUcCi", "")
-BUILTIN(__builtin_ia32_cvtps2dq512_mask, "V16iV16fV16iUsCi", "")
-BUILTIN(__builtin_ia32_cvtpd2dq512_mask, "V8iV8dV8iUcCi", "")
-BUILTIN(__builtin_ia32_cvtps2udq512_mask, "V16iV16fV16iUsCi", "")
-BUILTIN(__builtin_ia32_cvtpd2udq512_mask, "V8iV8dV8iUcCi", "")
-BUILTIN(__builtin_ia32_minps512_mask, "V16fV16fV16fV16fUsCi", "")
-BUILTIN(__builtin_ia32_minpd512_mask, "V8dV8dV8dV8dUcCi", "")
-BUILTIN(__builtin_ia32_maxps512_mask, "V16fV16fV16fV16fUsCi", "")
-BUILTIN(__builtin_ia32_maxpd512_mask, "V8dV8dV8dV8dUcCi", "")
-BUILTIN(__builtin_ia32_cvtdq2ps512_mask, "V16fV16iV16fUsCi", "")
-BUILTIN(__builtin_ia32_cvtudq2ps512_mask, "V16fV16iV16fUsCi", "")
+BUILTIN(__builtin_ia32_pcmpgtb512_mask, "LLiV64cV64cLLi", "")
+BUILTIN(__builtin_ia32_pcmpgtd512_mask, "sV16iV16is", "")
+BUILTIN(__builtin_ia32_pcmpgtq512_mask, "cV8LLiV8LLic", "")
+BUILTIN(__builtin_ia32_pcmpgtw512_mask, "iV32sV32si", "")
+BUILTIN(__builtin_ia32_pcmpgtb256_mask, "iV32cV32ci", "")
+BUILTIN(__builtin_ia32_pcmpgtd256_mask, "cV8iV8ic", "")
+BUILTIN(__builtin_ia32_pcmpgtq256_mask, "cV4LLiV4LLic", "")
+BUILTIN(__builtin_ia32_pcmpgtw256_mask, "sV16sV16ss", "")
+BUILTIN(__builtin_ia32_pcmpgtb128_mask, "sV16cV16cs", "")
+BUILTIN(__builtin_ia32_pcmpgtd128_mask, "cV4iV4ic", "")
+BUILTIN(__builtin_ia32_pcmpgtq128_mask, "cV2LLiV2LLic", "")
+BUILTIN(__builtin_ia32_pcmpgtw128_mask, "cV8sV8sc", "")
+BUILTIN(__builtin_ia32_cmppd512_mask, "UcV8dV8dIcUcIi", "")
+BUILTIN(__builtin_ia32_rndscaleps_mask, "V16fV16fIiV16fUsIi", "")
+BUILTIN(__builtin_ia32_rndscalepd_mask, "V8dV8dIiV8dUcIi", "")
+BUILTIN(__builtin_ia32_cvtps2dq512_mask, "V16iV16fV16iUsIi", "")
+BUILTIN(__builtin_ia32_cvtpd2dq512_mask, "V8iV8dV8iUcIi", "")
+BUILTIN(__builtin_ia32_cvtps2udq512_mask, "V16iV16fV16iUsIi", "")
+BUILTIN(__builtin_ia32_cvtpd2udq512_mask, "V8iV8dV8iUcIi", "")
+BUILTIN(__builtin_ia32_minps512_mask, "V16fV16fV16fV16fUsIi", "")
+BUILTIN(__builtin_ia32_minpd512_mask, "V8dV8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_maxps512_mask, "V16fV16fV16fV16fUsIi", "")
+BUILTIN(__builtin_ia32_maxpd512_mask, "V8dV8dV8dV8dUcIi", "")
+BUILTIN(__builtin_ia32_cvtdq2ps512_mask, "V16fV16iV16fUsIi", "")
+BUILTIN(__builtin_ia32_cvtudq2ps512_mask, "V16fV16iV16fUsIi", "")
 BUILTIN(__builtin_ia32_cvtdq2pd512_mask, "V8dV8iV8dUc", "")
 BUILTIN(__builtin_ia32_cvtudq2pd512_mask, "V8dV8iV8dUc", "")
-BUILTIN(__builtin_ia32_cvtpd2ps512_mask, "V8fV8dV8fUcCi", "")
-BUILTIN(__builtin_ia32_vcvtps2ph512_mask, "V16sV16fCiV16sUs", "")
-BUILTIN(__builtin_ia32_vcvtph2ps512_mask, "V16fV16sV16fUsCi", "")
+BUILTIN(__builtin_ia32_cvtpd2ps512_mask, "V8fV8dV8fUcIi", "")
+BUILTIN(__builtin_ia32_vcvtps2ph512_mask, "V16sV16fIiV16sUs", "")
+BUILTIN(__builtin_ia32_vcvtph2ps512_mask, "V16fV16sV16fUsIi", "")
 BUILTIN(__builtin_ia32_pabsd512_mask, "V16iV16iV16iUs", "")
 BUILTIN(__builtin_ia32_pabsq512_mask, "V8LLiV8LLiV8LLiUc", "")
 BUILTIN(__builtin_ia32_pmaxsd512_mask, "V16iV16iV16iV16iUs", "")
@@ -865,41 +905,72 @@
 BUILTIN(__builtin_ia32_loaddqusi512_mask, "V16ivC*V16iUs", "")
 BUILTIN(__builtin_ia32_loaddqudi512_mask, "V8LLivC*V8LLiUc", "")
 BUILTIN(__builtin_ia32_loadups512_mask, "V16fvC*V16fUs", "")
+BUILTIN(__builtin_ia32_loadaps512_mask, "V16fvC*V16fUs", "")
 BUILTIN(__builtin_ia32_loadupd512_mask, "V8dvC*V8dUc", "")
+BUILTIN(__builtin_ia32_loadapd512_mask, "V8dvC*V8dUc", "")
 BUILTIN(__builtin_ia32_storedqudi512_mask, "vv*V8LLiUc", "")
 BUILTIN(__builtin_ia32_storedqusi512_mask, "vv*V16iUs", "")
 BUILTIN(__builtin_ia32_storeupd512_mask, "vv*V8dUc", "")
+BUILTIN(__builtin_ia32_storeapd512_mask, "vv*V8dUc", "")
 BUILTIN(__builtin_ia32_storeups512_mask, "vv*V16fUs", "")
+BUILTIN(__builtin_ia32_storeaps512_mask, "vv*V16fUs", "")
 BUILTIN(__builtin_ia32_vpermt2vard512_mask, "V16iV16iV16iV16iUs", "")
 BUILTIN(__builtin_ia32_vpermt2varq512_mask, "V8LLiV8LLiV8LLiV8LLiUc", "")
 BUILTIN(__builtin_ia32_vpermt2varps512_mask, "V16fV16iV16fV16fUs", "")
 BUILTIN(__builtin_ia32_vpermt2varpd512_mask, "V8dV8LLiV8dV8dUc", "")
-BUILTIN(__builtin_ia32_alignq512_mask, "V8LLiV8LLiV8LLiUcV8LLiUc", "")
-BUILTIN(__builtin_ia32_alignd512_mask, "V16iV16iV16iUcV16iUc", "")
-BUILTIN(__builtin_ia32_gathersiv8df, "V8dV8dv*V8iUcCi", "")
-BUILTIN(__builtin_ia32_gathersiv16sf, "V16fV16fv*UsCi", "")
-BUILTIN(__builtin_ia32_gatherdiv8df, "V8dV8dv*V8LLiUcCi", "")
-BUILTIN(__builtin_ia32_gatherdiv16sf, "V8fV8fv*V8LLiUcCi", "")
-BUILTIN(__builtin_ia32_gathersiv8di, "V8LLiV8LLiv*V8iUcCi", "")
-BUILTIN(__builtin_ia32_gathersiv16si, "V16iV16iv*UsCi", "")
-BUILTIN(__builtin_ia32_gatherdiv8di, "V8LLiV8LLiv*V8LLiUcCi", "")
-BUILTIN(__builtin_ia32_gatherdiv16si, "V8iV8iv*V8LLiUcCi", "")
-BUILTIN(__builtin_ia32_scattersiv8df, "vv*UcV8iV8dCi", "")
-BUILTIN(__builtin_ia32_scattersiv16sf, "vv*UsV16iV16fCi", "")
-BUILTIN(__builtin_ia32_scatterdiv8df,  "vv*UcV8LLiV8dCi", "")
-BUILTIN(__builtin_ia32_scatterdiv16sf, "vv*UcV8LLiV8fCi", "")
-BUILTIN(__builtin_ia32_scattersiv8di,  "vv*UcV8iV8LLiCi", "")
-BUILTIN(__builtin_ia32_scattersiv16si, "vv*UsV16iV16iCi", "")
-BUILTIN(__builtin_ia32_scatterdiv8di,  "vv*UcV8LLiV8LLiCi", "")
-BUILTIN(__builtin_ia32_scatterdiv16si, "vv*UcV8LLiV8iCi", "")
-BUILTIN(__builtin_ia32_gatherpfdpd,  "vUcV8iv*CiCi", "")
-BUILTIN(__builtin_ia32_gatherpfdps,  "vUsV16iv*CiCi", "")
-BUILTIN(__builtin_ia32_gatherpfqpd,  "vUcV8LLiv*CiCi", "")
-BUILTIN(__builtin_ia32_gatherpfqps,  "vUcV8LLiv*CiCi", "")
-BUILTIN(__builtin_ia32_scatterpfdpd, "vUcV8iv*CiCi", "")
-BUILTIN(__builtin_ia32_scatterpfdps, "vUsV16iv*CiCi", "")
-BUILTIN(__builtin_ia32_scatterpfqpd, "vUcV8LLiv*CiCi", "")
-BUILTIN(__builtin_ia32_scatterpfqps, "vUcV8LLiv*CiCi", "")
+BUILTIN(__builtin_ia32_alignq512_mask, "V8LLiV8LLiV8LLiIcV8LLiUc", "")
+BUILTIN(__builtin_ia32_alignd512_mask, "V16iV16iV16iIcV16iUs", "")
+BUILTIN(__builtin_ia32_extractf64x4_mask, "V4dV8dIcV4dUc", "")
+BUILTIN(__builtin_ia32_extractf32x4_mask, "V4fV16fIcV4fUc", "")
+BUILTIN(__builtin_ia32_gathersiv8df, "V8dV8dvC*V8iUcIi", "")
+BUILTIN(__builtin_ia32_gathersiv16sf, "V16fV16fvC*UsIi", "")
+BUILTIN(__builtin_ia32_gatherdiv8df, "V8dV8dvC*V8LLiUcIi", "")
+BUILTIN(__builtin_ia32_gatherdiv16sf, "V8fV8fvC*V8LLiUcIi", "")
+BUILTIN(__builtin_ia32_gathersiv8di, "V8LLiV8LLivC*V8iUcIi", "")
+BUILTIN(__builtin_ia32_gathersiv16si, "V16iV16ivC*UsIi", "")
+BUILTIN(__builtin_ia32_gatherdiv8di, "V8LLiV8LLivC*V8LLiUcIi", "")
+BUILTIN(__builtin_ia32_gatherdiv16si, "V8iV8ivC*V8LLiUcIi", "")
+BUILTIN(__builtin_ia32_scattersiv8df, "vv*UcV8iV8dIi", "")
+BUILTIN(__builtin_ia32_scattersiv16sf, "vv*UsV16iV16fIi", "")
+BUILTIN(__builtin_ia32_scatterdiv8df,  "vv*UcV8LLiV8dIi", "")
+BUILTIN(__builtin_ia32_scatterdiv16sf, "vv*UcV8LLiV8fIi", "")
+BUILTIN(__builtin_ia32_scattersiv8di,  "vv*UcV8iV8LLiIi", "")
+BUILTIN(__builtin_ia32_scattersiv16si, "vv*UsV16iV16iIi", "")
+BUILTIN(__builtin_ia32_scatterdiv8di,  "vv*UcV8LLiV8LLiIi", "")
+BUILTIN(__builtin_ia32_scatterdiv16si, "vv*UcV8LLiV8iIi", "")
+BUILTIN(__builtin_ia32_gatherpfdpd,  "vUcV8ivC*IiIi", "")
+BUILTIN(__builtin_ia32_gatherpfdps,  "vUsV16ivC*IiIi", "")
+BUILTIN(__builtin_ia32_gatherpfqpd,  "vUcV8LLivC*IiIi", "")
+BUILTIN(__builtin_ia32_gatherpfqps,  "vUcV8LLivC*IiIi", "")
+BUILTIN(__builtin_ia32_scatterpfdpd, "vUcV8iv*IiIi", "")
+BUILTIN(__builtin_ia32_scatterpfdps, "vUsV16iv*IiIi", "")
+BUILTIN(__builtin_ia32_scatterpfqpd, "vUcV8LLiv*IiIi", "")
+BUILTIN(__builtin_ia32_scatterpfqps, "vUcV8LLiv*IiIi", "")
 BUILTIN(__builtin_ia32_knothi, "UsUs", "")
 
+BUILTIN(__builtin_ia32_cmpb128_mask, "UsV16cV16cIcUs", "")
+BUILTIN(__builtin_ia32_cmpd128_mask, "UcV4iV4iIcUc", "")
+BUILTIN(__builtin_ia32_cmpq128_mask, "UcV2LLiV2LLiIcUc", "")
+BUILTIN(__builtin_ia32_cmpw128_mask, "UcV8sV8sIcUc", "")
+BUILTIN(__builtin_ia32_cmpb256_mask, "UiV32cV32cIcUi", "")
+BUILTIN(__builtin_ia32_cmpd256_mask, "UcV8iV8iIcUc", "")
+BUILTIN(__builtin_ia32_cmpq256_mask, "UcV4LLiV4LLiIcUc", "")
+BUILTIN(__builtin_ia32_cmpw256_mask, "UsV16sV16sIcUs", "")
+BUILTIN(__builtin_ia32_cmpb512_mask, "ULLiV64cV64cIcULLi", "")
+BUILTIN(__builtin_ia32_cmpd512_mask, "UsV16iV16iIcUs", "")
+BUILTIN(__builtin_ia32_cmpq512_mask, "UcV8LLiV8LLiIcUc", "")
+BUILTIN(__builtin_ia32_cmpw512_mask, "UiV32sV32sIcUi", "")
+BUILTIN(__builtin_ia32_ucmpb128_mask, "UsV16cV16cIcUs", "")
+BUILTIN(__builtin_ia32_ucmpd128_mask, "UcV4iV4iIcUc", "")
+BUILTIN(__builtin_ia32_ucmpq128_mask, "UcV2LLiV2LLiIcUc", "")
+BUILTIN(__builtin_ia32_ucmpw128_mask, "UcV8sV8sIcUc", "")
+BUILTIN(__builtin_ia32_ucmpb256_mask, "UiV32cV32cIcUi", "")
+BUILTIN(__builtin_ia32_ucmpd256_mask, "UcV8iV8iIcUc", "")
+BUILTIN(__builtin_ia32_ucmpq256_mask, "UcV4LLiV4LLiIcUc", "")
+BUILTIN(__builtin_ia32_ucmpw256_mask, "UsV16sV16sIcUs", "")
+BUILTIN(__builtin_ia32_ucmpb512_mask, "ULLiV64cV64cIcULLi", "")
+BUILTIN(__builtin_ia32_ucmpd512_mask, "UsV16iV16iIcUs", "")
+BUILTIN(__builtin_ia32_ucmpq512_mask, "UcV8LLiV8LLiIcUc", "")
+BUILTIN(__builtin_ia32_ucmpw512_mask, "UiV32sV32sIcUi", "")
+
 #undef BUILTIN
diff --git a/include/clang/Basic/Diagnostic.h b/include/clang/Basic/Diagnostic.h
index 31a29fa..f72809c 100644
--- a/include/clang/Basic/Diagnostic.h
+++ b/include/clang/Basic/Diagnostic.h
@@ -132,8 +132,8 @@
 /// the user. DiagnosticsEngine is tied to one translation unit and one
 /// SourceManager.
 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
-  DiagnosticsEngine(const DiagnosticsEngine &) LLVM_DELETED_FUNCTION;
-  void operator=(const DiagnosticsEngine &) LLVM_DELETED_FUNCTION;
+  DiagnosticsEngine(const DiagnosticsEngine &) = delete;
+  void operator=(const DiagnosticsEngine &) = delete;
 
 public:
   /// \brief The level of the diagnostic, after it has been through mapping.
@@ -347,6 +347,7 @@
                       DiagnosticOptions *DiagOpts,
                       DiagnosticConsumer *client = nullptr,
                       bool ShouldOwnClient = true);
+  ~DiagnosticsEngine();
 
   const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
     return Diags;
@@ -876,7 +877,7 @@
   /// call to ForceEmit.
   mutable bool IsForceEmit;
 
-  void operator=(const DiagnosticBuilder &) LLVM_DELETED_FUNCTION;
+  void operator=(const DiagnosticBuilder &) = delete;
   friend class DiagnosticsEngine;
 
   DiagnosticBuilder()
@@ -990,7 +991,8 @@
 
   void AddFixItHint(const FixItHint &Hint) const {
     assert(isActive() && "Clients must not add to cleared diagnostic!");
-    DiagObj->DiagFixItHints.push_back(Hint);
+    if (!Hint.isNull())
+      DiagObj->DiagFixItHints.push_back(Hint);
   }
 
   void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
@@ -1094,7 +1096,13 @@
 
 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
                                            const FixItHint &Hint) {
-  if (!Hint.isNull())
+  DB.AddFixItHint(Hint);
+  return DB;
+}
+
+inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
+                                           ArrayRef<FixItHint> Hints) {
+  for (const FixItHint &Hint : Hints)
     DB.AddFixItHint(Hint);
   return DB;
 }
@@ -1259,7 +1267,7 @@
   ~StoredDiagnostic();
 
   /// \brief Evaluates true when this object stores a diagnostic.
-  LLVM_EXPLICIT operator bool() const { return Message.size() > 0; }
+  explicit operator bool() const { return Message.size() > 0; }
 
   unsigned getID() const { return ID; }
   DiagnosticsEngine::Level getLevel() const { return Level; }
diff --git a/include/clang/Basic/DiagnosticCommonKinds.td b/include/clang/Basic/DiagnosticCommonKinds.td
index ff9ed69..afdd926 100644
--- a/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/include/clang/Basic/DiagnosticCommonKinds.td
@@ -81,8 +81,13 @@
   "only functions can have deleted definitions">;
 def err_module_not_found : Error<"module '%0' not found">, DefaultFatal;
 def err_module_not_built : Error<"could not build module '%0'">, DefaultFatal;
+def err_module_build_disabled: Error<
+  "module '%0' is needed but has not been provided, and implicit use of module "
+  "files is disabled">, DefaultFatal;
 def err_module_lock_failure : Error<
   "could not acquire lock file for module '%0'">, DefaultFatal;
+def err_module_lock_timeout : Error<
+  "timed out waiting to acquire lock file for module '%0'">, DefaultFatal;
 def err_module_cycle : Error<"cyclic dependency in module '%0': %1">, 
   DefaultFatal;
 def note_pragma_entered_here : Note<"#pragma entered here">;  
@@ -112,6 +117,16 @@
   "interpreting as unsigned">,
   InGroup<DiagGroup<"implicitly-unsigned-literal">>;
 
+// SEH
+def err_seh_expected_handler : Error<
+  "expected '__except' or '__finally' block">;
+def err_seh___except_block : Error<
+  "%0 only allowed in __except block or filter expression">;
+def err_seh___except_filter : Error<
+  "%0 only allowed in __except filter expression">;
+def err_seh___finally_block : Error<
+  "%0 only allowed in __finally block">;
+
 // Sema && AST
 def note_invalid_subexpr_in_const_expr : Note<
   "subexpression not valid in a constant expression">;
diff --git a/include/clang/Basic/DiagnosticDriverKinds.td b/include/clang/Basic/DiagnosticDriverKinds.td
index 41c78ee..76853d8 100644
--- a/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/include/clang/Basic/DiagnosticDriverKinds.td
@@ -160,6 +160,12 @@
   InGroup<DiagGroup<"missing-sysroot">>;
 def warn_debug_compression_unavailable : Warning<"cannot compress debug sections (zlib not installed)">,
   InGroup<DiagGroup<"debug-compression-unavailable">>;
+def warn_drv_enabling_rtti_with_exceptions : Warning<
+  "implicitly enabling rtti for exception handling">,
+  InGroup<DiagGroup<"rtti-for-exceptions">>;
+def warn_drv_disabling_vptr_no_rtti_default : Warning<
+  "implicitly disabling vptr sanitizer because rtti wasn't enabled">,
+  InGroup<DiagGroup<"auto-disable-vptr-sanitizer">>;
 
 def note_drv_command_failed_diag_msg : Note<
   "diagnostic msg: %0">;
diff --git a/include/clang/Basic/DiagnosticFrontendKinds.td b/include/clang/Basic/DiagnosticFrontendKinds.td
index 15f74b1..13e2865 100644
--- a/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -35,6 +35,10 @@
 def remark_fe_backend_plugin: Remark<"%0">, BackendInfo, InGroup<RemarkBackendPlugin>;
 def note_fe_backend_plugin: Note<"%0">, BackendInfo;
 
+def warn_fe_override_module : Warning<
+    "overriding the module target triple with %0">, 
+    InGroup<DiagGroup<"override-module">>;
+
 def remark_fe_backend_optimization_remark : Remark<"%0">, BackendInfo,
     InGroup<BackendOptimizationRemark>;
 def remark_fe_backend_optimization_remark_missed : Remark<"%0">, BackendInfo,
diff --git a/include/clang/Basic/DiagnosticGroups.td b/include/clang/Basic/DiagnosticGroups.td
index cc4508a..215ff06 100644
--- a/include/clang/Basic/DiagnosticGroups.td
+++ b/include/clang/Basic/DiagnosticGroups.td
@@ -60,7 +60,7 @@
 def KeywordCompat : DiagGroup<"keyword-compat">;
 def GNUCaseRange : DiagGroup<"gnu-case-range">;
 def CastAlign : DiagGroup<"cast-align">;
-def : DiagGroup<"cast-qual">;
+def CastQual : DiagGroup<"cast-qual">;
 def : DiagGroup<"char-align">;
 def Comment : DiagGroup<"comment">;
 def GNUComplexInteger : DiagGroup<"gnu-complex-integer">;
@@ -190,6 +190,7 @@
 def DanglingElse: DiagGroup<"dangling-else">;
 def DanglingField : DiagGroup<"dangling-field">;
 def DistributedObjectModifiers : DiagGroup<"distributed-object-modifiers">;
+def FlagEnum : DiagGroup<"flag-enum">;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
@@ -273,6 +274,7 @@
 def ObjCRootClass : DiagGroup<"objc-root-class">;
 def ObjCPointerIntrospectPerformSelector : DiagGroup<"deprecated-objc-pointer-introspection-performSelector">;
 def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ObjCPointerIntrospectPerformSelector]>;
+def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">;
 def DeprecatedObjCIsaUsage : DiagGroup<"deprecated-objc-isa-usage">;
 def ExplicitInitializeCall : DiagGroup<"explicit-initialize-call">;
 def Packed : DiagGroup<"packed">;
@@ -292,6 +294,7 @@
                                     [CXX98CompatBindToTemporaryCopy]>;
 def SelfAssignmentField : DiagGroup<"self-assign-field">;
 def SelfAssignment : DiagGroup<"self-assign", [SelfAssignmentField]>;
+def SelfMove : DiagGroup<"self-move">;
 def SemiBeforeMethodBody : DiagGroup<"semicolon-before-method-body">;
 def Sentinel : DiagGroup<"sentinel">;
 def MissingMethodReturnType : DiagGroup<"missing-method-return-type">;
@@ -336,6 +339,8 @@
 
 // Preprocessor warnings.
 def AmbiguousMacro : DiagGroup<"ambiguous-macro">;
+def KeywordAsMacro : DiagGroup<"keyword-macro">;
+def ReservedIdAsMacro : DiagGroup<"reserved-id-macro">;
 
 // Just silence warnings about -Wstrict-aliasing for now.
 def : DiagGroup<"strict-aliasing=0">;
@@ -405,12 +410,17 @@
 def UnusedLabel : DiagGroup<"unused-label">;
 def UnusedParameter : DiagGroup<"unused-parameter">;
 def UnusedResult : DiagGroup<"unused-result">;
-def UnusedValue : DiagGroup<"unused-value", [UnusedComparison, UnusedResult]>;
+def PotentiallyEvaluatedExpression : DiagGroup<"potentially-evaluated-expression">;
+def UnevaluatedExpression : DiagGroup<"unevaluated-expression",
+                                      [PotentiallyEvaluatedExpression]>;
+def UnusedValue : DiagGroup<"unused-value", [UnusedComparison, UnusedResult,
+                                             UnevaluatedExpression]>;
 def UnusedConstVariable : DiagGroup<"unused-const-variable">;
 def UnusedVariable : DiagGroup<"unused-variable",
                                [UnusedConstVariable]>;
 def UnusedLocalTypedef : DiagGroup<"unused-local-typedef">;
 def UnusedPropertyIvar :  DiagGroup<"unused-property-ivar">;
+def UnusedGetterReturnValue : DiagGroup<"unused-getter-return-value">;
 def UsedButMarkedUnused : DiagGroup<"used-but-marked-unused">;
 def UserDefinedLiterals : DiagGroup<"user-defined-literals">;
 def Reorder : DiagGroup<"reorder">;
@@ -419,8 +429,6 @@
 def CustomAtomic : DiagGroup<"custom-atomic-properties">;
 def AtomicProperties : DiagGroup<"atomic-properties",
                                  [ImplicitAtomic, CustomAtomic]>;
-// FIXME: Remove arc-abi once an Xcode is released that doesn't pass this flag.
-def : DiagGroup<"arc-abi">;
 def ARCUnsafeRetainedAssign : DiagGroup<"arc-unsafe-retained-assign">;
 def ARCRetainCycles : DiagGroup<"arc-retain-cycles">;
 def ARCNonPodMemAccess : DiagGroup<"arc-non-pod-memaccess">;
@@ -579,6 +587,7 @@
     Reorder,
     ReturnType,
     SelfAssignment,
+    SelfMove,
     SizeofArrayArgument,
     SizeofArrayDecay,
     StringPlusInt,
@@ -741,3 +750,6 @@
 // A warning group for warnings about code that clang accepts when
 // compiling CUDA C/C++ but which is not compatible with the CUDA spec.
 def CudaCompat : DiagGroup<"cuda-compat">;
+
+// A warning group for things that will change semantics in the future.
+def FutureCompat : DiagGroup<"future-compat">;
diff --git a/include/clang/Basic/DiagnosticLexKinds.td b/include/clang/Basic/DiagnosticLexKinds.td
index 2fcfa02..3fa9bcf 100644
--- a/include/clang/Basic/DiagnosticLexKinds.td
+++ b/include/clang/Basic/DiagnosticLexKinds.td
@@ -290,6 +290,11 @@
   "expanding this definition of %0">;
 def note_pp_ambiguous_macro_other : Note<
   "other definition of %0">;
+def warn_pp_macro_hides_keyword : Extension<
+  "keyword is hidden by macro definition">, InGroup<KeywordAsMacro>;
+def warn_pp_macro_is_reserved_id : Warning<
+  "macro name is a reserved identifier">, DefaultIgnore,
+  InGroup<ReservedIdAsMacro>;
 
 def pp_invalid_string_literal : Warning<
   "invalid string literal, ignoring final '\\'">;
@@ -327,7 +332,7 @@
   InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def ext_named_variadic_macro : Extension<
   "named variadic macros are a GNU extension">, InGroup<VariadicMacros>;
-def err_embedded_include : Error<
+def err_embedded_directive : Error<
   "embedding a #%0 directive within macro arguments is not supported">;
 def ext_embedded_directive : Extension<
   "embedding a directive within macro arguments has undefined behavior">,
@@ -620,9 +625,10 @@
   InGroup<IncompleteUmbrella>;
 def err_expected_id_building_module : Error<
   "expected a module name in '__building_module' expression">;
-def error_use_of_private_header_outside_module : Error<
-  "use of private header from outside its module: '%0'">;
-def error_undeclared_use_of_module : Error<
+def warn_use_of_private_header_outside_module : Warning<
+  "use of private header from outside its module: '%0'">,
+  InGroup<DiagGroup<"private-header">>, DefaultError;
+def err_undeclared_use_of_module : Error<
   "module %0 does not depend on a module exporting '%1'">;
 def warn_non_modular_include_in_framework_module : Warning<
   "include of non-modular header inside framework module '%0'">,
diff --git a/include/clang/Basic/DiagnosticOptions.def b/include/clang/Basic/DiagnosticOptions.def
index a360a5a..fdd3254 100644
--- a/include/clang/Basic/DiagnosticOptions.def
+++ b/include/clang/Basic/DiagnosticOptions.def
@@ -81,6 +81,8 @@
 VALUE_DIAGOPT(TemplateBacktraceLimit, 32, DefaultTemplateBacktraceLimit)
 /// Limit depth of constexpr backtrace.
 VALUE_DIAGOPT(ConstexprBacktraceLimit, 32, DefaultConstexprBacktraceLimit)
+/// Limit number of times to perform spell checking.
+VALUE_DIAGOPT(SpellCheckingLimit, 32, DefaultSpellCheckingLimit)
 
 VALUE_DIAGOPT(TabStop, 32, DefaultTabStop) /// The distance between tab stops.
 /// Column limit for formatting message diagnostics, or 0 if unused.
@@ -92,4 +94,3 @@
 #undef SEMANTIC_DIAGOPT
 #undef SEMANTIC_ENUM_DIAGOPT
 #undef SEMANTIC_VALUE_DIAGOPT
-
diff --git a/include/clang/Basic/DiagnosticOptions.h b/include/clang/Basic/DiagnosticOptions.h
index 3e4d0ee..a16c774 100644
--- a/include/clang/Basic/DiagnosticOptions.h
+++ b/include/clang/Basic/DiagnosticOptions.h
@@ -27,13 +27,14 @@
 /// \brief Options for controlling the compiler diagnostics engine.
 class DiagnosticOptions : public RefCountedBase<DiagnosticOptions>{
 public:
-  enum TextDiagnosticFormat { Clang, Msvc, Vi };
+  enum TextDiagnosticFormat { Clang, MSVC, Vi };
 
   // Default values.
   enum { DefaultTabStop = 8, MaxTabStop = 100,
     DefaultMacroBacktraceLimit = 6,
     DefaultTemplateBacktraceLimit = 10,
-    DefaultConstexprBacktraceLimit = 10 };
+    DefaultConstexprBacktraceLimit = 10,
+    DefaultSpellCheckingLimit = 50 };
 
   // Define simple diagnostic options (with no accessors).
 #define DIAGOPT(Name, Bits, Default) unsigned Name : Bits;
diff --git a/include/clang/Basic/DiagnosticParseKinds.td b/include/clang/Basic/DiagnosticParseKinds.td
index 6bf1910..c8915a7 100644
--- a/include/clang/Basic/DiagnosticParseKinds.td
+++ b/include/clang/Basic/DiagnosticParseKinds.td
@@ -25,6 +25,8 @@
   "Unsupported architecture '%0' for MS-style inline assembly">;
 def err_msasm_unable_to_create_target : Error<
   "MS-style inline assembly is not available: %0">;
+def err_gnu_inline_asm_disabled : Error<
+  "GNU-style inline assembly is disabled">;
 }
 
 let CategoryName = "Parse Issue" in {
@@ -108,6 +110,9 @@
 def warn_microsoft_dependent_exists : Warning<
   "dependent %select{__if_not_exists|__if_exists}0 declarations are ignored">, 
   InGroup<DiagGroup<"microsoft-exists">>;
+def warn_microsoft_qualifiers_ignored : Warning<
+  "qualifiers after comma in declarator list are ignored">,
+  InGroup<IgnoredAttributes>;
 
 def ext_c11_generic_selection : Extension<
   "generic selections are a C11-specific feature">, InGroup<C11>;
@@ -128,6 +133,8 @@
   "use of GNU indirect-goto extension">, InGroup<GNULabelsAsValue>;
 def ext_gnu_address_of_label : Extension<
   "use of GNU address-of-label extension">, InGroup<GNULabelsAsValue>;
+def err_stmtexpr_file_scope : Error<
+  "statement expression not allowed at file scope">;
 def ext_gnu_statement_expr : Extension<
   "use of GNU statement expression extension">, InGroup<GNUStatementExpression>;
 def ext_gnu_conditional_expr : Extension<
@@ -290,13 +297,8 @@
 def warn_cxx98_compat_for_range : Warning<
   "range-based for loop is incompatible with C++98">,
   InGroup<CXX98Compat>, DefaultIgnore;
-def ext_for_range_identifier : ExtWarn<
-  "range-based for loop with implicit deduced type is a C++1z extension">,
-  InGroup<CXX1z>;
-def warn_cxx14_compat_for_range_identifier : Warning<
-  "range-based for loop with implicit deduced type is incompatible with "
-  "C++ standards before C++1z">,
-  InGroup<CXXPre1zCompat>, DefaultIgnore;
+def err_for_range_identifier : Error<
+  "range-based for loop requires type for loop variable">;
 def err_for_range_expected_decl : Error<
   "for range declaration must declare a variable">;
 def err_argument_required_after_attribute : Error<
@@ -604,6 +606,8 @@
   "expected name of accessor method">;
 def err_ms_property_expected_comma_or_rparen : Error<
   "expected ',' or ')' at end of property accessor list">;
+def err_ms_property_initializer : Error<
+  "property declaration cannot have an in-class initializer">;
 
 /// C++ Templates
 def err_expected_template : Error<"expected template">;
@@ -800,6 +804,10 @@
 def err_lambda_missing_parens : Error<
   "lambda requires '()' before %select{'mutable'|return type|"
   "attribute specifier}0">;
+def warn_init_capture_direct_list_init : Warning<
+  "direct list initialization of a lambda init-capture will change meaning in "
+  "a future version of Clang; insert an '=' to avoid a change in behavior">,
+  InGroup<FutureCompat>;
 
 // Availability attribute
 def err_expected_version : Error<
@@ -934,8 +942,8 @@
   "unexpected extra argument '%0' to '#pragma clang optimize'">;
 
 // OpenCL Section 6.8.g
-def err_not_opencl_storage_class_specifier : Error<
-  "OpenCL does not support the '%0' storage class specifier">;
+def err_opencl_unknown_type_specifier : Error<
+  "OpenCL does not support the '%0' %select{type qualifier|storage class specifier}1">;
 
 // OpenCL EXTENSION pragma (OpenCL 1.1 [9.1])
 def warn_pragma_expected_colon : Warning<
@@ -945,18 +953,6 @@
 def warn_pragma_unknown_extension : Warning<
   "unknown OpenCL extension %0 - ignoring">, InGroup<IgnoredPragmas>;
 
-def err_seh_expected_handler : Error<
-  "expected '__except' or '__finally' block">;
-
-def err_seh___except_block : Error<
-  "%0 only allowed in __except block">;
-
-def err_seh___except_filter : Error<
-  "%0 only allowed in __except filter expression">;
-
-def err_seh___finally_block : Error<
-  "%0 only allowed in __finally block">;
-
 // OpenMP support.
 def warn_pragma_omp_ignored : Warning<
   "unexpected '#pragma omp ...' in program">, InGroup<SourceUsesOpenMP>, DefaultIgnore;
diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td
index aa93e63..16d9337 100644
--- a/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1,3 +1,4 @@
+
 //==--- DiagnosticSemaKinds.td - libsema diagnostics ----------------------===//
 //
 //                     The LLVM Compiler Infrastructure
@@ -64,6 +65,9 @@
   "value of type %0 is not implicitly convertible to %1">;
 def err_typecheck_converted_constant_expression_disallowed : Error<
   "conversion from %0 to %1 is not allowed in a converted constant expression">;
+def err_typecheck_converted_constant_expression_indirect : Error<
+  "conversion from %0 to %1 in converted constant expression would "
+  "bind reference to a temporary">;
 def err_expr_not_cce : Error<
   "%select{case value|enumerator value|non-type template argument|array size}0 "
   "is not a constant expression">;
@@ -582,7 +586,8 @@
   "@protocol is using a forward protocol declaration of %0">, InGroup<AtProtocol>;
 def warn_readonly_property : Warning<
   "attribute 'readonly' of property %0 restricts attribute "
-  "'readwrite' of property inherited from %1">;
+  "'readwrite' of property inherited from %1">,
+  InGroup<PropertyAttr>;
 
 def warn_property_attribute : Warning<
   "'%1' attribute on property %0 does not match the property inherited from %2">,
@@ -717,7 +722,8 @@
 "default assign attribute on property %0 which implements "
 "NSCopying protocol is not appropriate with -fobjc-gc[-only]">;
 
-def warn_multiple_method_decl : Warning<"multiple methods named %0 found">;
+def warn_multiple_method_decl : Warning<"multiple methods named %0 found">,
+  InGroup<ObjCMultipleMethodNames>;
 def warn_strict_multiple_method_decl : Warning<
   "multiple methods named %0 found">, InGroup<StrictSelector>, DefaultIgnore;
 def warn_accessor_property_type_mismatch : Warning<
@@ -792,6 +798,12 @@
   "property follows Cocoa naming"
   " convention for returning 'owned' objects">,
   InGroup<DiagGroup<"objc-property-matches-cocoa-ownership-rule">>;
+def err_cocoa_naming_owned_rule : Error<
+  "property follows Cocoa naming"
+  " convention for returning 'owned' objects">;
+def note_cocoa_naming_declare_family : Note<
+  "explicitly declare getter %objcinstance0 with '%1' to return an 'unowned' "
+  "object">;
 def warn_auto_synthesizing_protocol_property :Warning<
   "auto property synthesis will not synthesize property %0"
   " declared in protocol %1">,
@@ -823,9 +835,6 @@
 def error_property_setter_ambiguous_use : Error<
   "synthesized properties %0 and %1 both claim setter %2 -"
   " use of this setter will cause unexpected behavior">;
-def err_cocoa_naming_owned_rule : Error<
-  "property follows Cocoa naming"
-  " convention for returning 'owned' objects">;
 def warn_default_atomic_custom_getter_setter : Warning<
   "atomic by default property %0 has a user defined %select{getter|setter}1 "
   "(property should be marked 'atomic' if this is intended)">,
@@ -1222,13 +1231,19 @@
   InGroup<CXX98Compat>, DefaultIgnore;
 def err_nested_name_spec_is_not_class : Error<
   "%0 cannot appear before '::' because it is not a class"
-  "%select{ or namespace|, namespace, or scoped enumeration}1; did you mean ':'?">;
+  "%select{ or namespace|, namespace, or enumeration}1; did you mean ':'?">;
+def ext_nested_name_spec_is_enum : ExtWarn<
+  "use of enumeration in a nested name specifier is a C++11 extension">,
+  InGroup<CXX11>;
 
 // C++ class members
 def err_storageclass_invalid_for_member : Error<
   "storage class specified for a member declaration">;
 def err_mutable_function : Error<"'mutable' cannot be applied to functions">;
 def err_mutable_reference : Error<"'mutable' cannot be applied to references">;
+def ext_mutable_reference : ExtWarn<
+  "'mutable' on a reference type is a Microsoft extension">,
+  InGroup<Microsoft>;
 def err_mutable_const : Error<"'mutable' and 'const' cannot be mixed">;
 def err_mutable_nonmember : Error<
   "'mutable' can only be applied to member variables">;
@@ -1287,6 +1302,8 @@
   "%select{|implicit default |inheriting }0constructor for %1 must explicitly "
   "initialize the %select{base class|member}2 %3 which does not have a default "
   "constructor">;
+def note_due_to_dllexported_class : Note<
+  "due to '%0' being dllexported%select{|; try compiling in C++11 mode}1">;
 
 def err_illegal_union_or_anon_struct_member : Error<
   "%select{anonymous struct|union}0 member %1 has a non-trivial "
@@ -1496,6 +1513,9 @@
   "uninitialized reference member is here">;
 def warn_field_is_uninit : Warning<"field %0 is uninitialized when used here">,
   InGroup<Uninitialized>;
+def warn_base_class_is_uninit : Warning<
+  "base class %0 is uninitialized when used here to access %q1">,
+  InGroup<Uninitialized>;
 def warn_reference_field_is_uninit : Warning<
   "reference %0 is not yet bound to a value when used here">,
   InGroup<Uninitialized>;
@@ -1627,6 +1647,10 @@
 def err_auto_var_init_paren_braces : Error<
   "cannot deduce type for variable %0 with type %1 from "
   "parenthesized initializer list">;
+def warn_auto_var_direct_list_init : Warning<
+  "direct list initialization of a variable with a deduced type will change "
+  "meaning in a future version of Clang; insert an '=' to avoid a change in "
+  "behavior">, InGroup<FutureCompat>;
 def err_auto_new_ctor_multiple_expressions : Error<
   "new expression for type %0 contains multiple constructor arguments">;
 def err_auto_missing_trailing_return : Error<
@@ -1868,6 +1892,8 @@
   "'enable_if' attribute expression never produces a constant expression">;
 def err_constexpr_body_no_return : Error<
   "no return statement in constexpr function">;
+def err_constexpr_return_missing_expr : Error<
+  "non-void constexpr function %0 should return a value">;
 def warn_cxx11_compat_constexpr_body_no_return : Warning<
   "constexpr function with no return statements is incompatible with C++ "
   "standards before C++14">, InGroup<CXXPre14Compat>, DefaultIgnore;
@@ -1888,8 +1914,6 @@
   "constexpr constructor must initialize all members">;
 def note_constexpr_ctor_missing_init : Note<
   "member not initialized by constructor">;
-def err_constexpr_method_non_literal : Error<
-  "non-literal type %0 cannot have constexpr members">;
 def note_non_literal_no_constexpr_ctors : Note<
   "%0 is not literal because it is not an aggregate and has no constexpr "
   "constructors other than copy or move constructors">;
@@ -2013,6 +2037,8 @@
   "can't convert between vector values of different size (%0 and %1)">;
 def err_typecheck_vector_not_convertable_non_scalar : Error<
   "can't convert between vector and non-scalar values (%0 and %1)">;
+def err_typecheck_vector_lengths_not_equal : Error<
+  "vector operands do not have the same number of elements (%0 and %1)">;
 def err_ext_vector_component_exceeds_length : Error<
   "vector component access exceeds type %0">;
 def err_ext_vector_component_name_illegal : Error<
@@ -2193,6 +2219,9 @@
 def warn_attribute_dllimport_static_field_definition : Warning<
   "definition of dllimport static field">,
   InGroup<DiagGroup<"dllimport-static-field-def">>;
+def warn_attribute_dllexport_explicit_instantiation_decl : Warning<
+  "explicit instantiation declaration should not be 'dllexport'">,
+  InGroup<DiagGroup<"dllexport-explicit-instantation-decl">>;
 def warn_invalid_initializer_from_system_header : Warning<
   "invalid constructor form class in system header, should not be explicit">,
   InGroup<DiagGroup<"invalid-initializer-from-system-header">>;
@@ -2228,7 +2257,7 @@
   "%0 attribute only applies to %select{functions|unions|"
   "variables and functions|functions and methods|parameters|"
   "functions, methods and blocks|functions, methods, and classes|"
-  "functions, methods, and parameters|classes|variables|methods|"
+  "functions, methods, and parameters|classes|enums|variables|methods|"
   "variables, functions and labels|fields and global variables|structs|"
   "variables and typedefs|thread-local variables|"
   "variables and fields|variables, data members and tag types|"
@@ -2236,8 +2265,8 @@
   "struct or union|struct, union or class|types|"
   "Objective-C instance methods|init methods of interface or class extension declarations|"
   "variables, functions and classes|Objective-C protocols|"
-  "functions and global variables|structs or typedefs|"
-  "interface or protocol declarations}1">,
+  "functions and global variables|structs, unions, and typedefs|structs and typedefs|"
+  "interface or protocol declarations|kernel functions}1">,
   InGroup<IgnoredAttributes>;
 def err_attribute_wrong_decl_type : Error<warn_attribute_wrong_decl_type.Text>;
 def warn_type_attribute_wrong_type : Warning<
@@ -2376,6 +2405,13 @@
 def warn_cannot_resolve_lock : Warning<
   "cannot resolve lock expression">,
   InGroup<ThreadSafetyAnalysis>, DefaultIgnore;
+def warn_acquired_before : Warning<
+  "%0 '%1' must be acquired before '%2'">,
+  InGroup<ThreadSafetyAnalysis>, DefaultIgnore;
+def warn_acquired_before_after_cycle : Warning<
+  "Cycle in acquired_before/after dependencies, starting with '%0'">,
+  InGroup<ThreadSafetyAnalysis>, DefaultIgnore;
+
 
 // Thread safety warnings negative capabilities
 def warn_acquire_requires_negative_cap : Warning<
@@ -2599,6 +2635,7 @@
   InGroup<DiagGroup<"unsupported-visibility">>;
 def err_mismatched_visibility: Error<"visibility does not match previous declaration">;
 def note_previous_attribute : Note<"previous attribute is here">;
+def note_conflicting_attribute : Note<"conflicting attribute is here">;
 def note_attribute : Note<"attribute is here">;
 def err_mismatched_ms_inheritance : Error<
   "inheritance model does not match %select{definition|previous declaration}0">;
@@ -2620,9 +2657,6 @@
 def warn_attribute_nonnull_parm_no_args : Warning<
   "'nonnull' attribute when used on parameters takes no arguments">,
   InGroup<IgnoredAttributes>;
-def warn_attribute_malloc_pointer_only : Warning<
-  "'malloc' attribute only applies to functions returning a pointer type">,
-  InGroup<IgnoredAttributes>;
 def warn_attribute_sentinel_named_arguments : Warning<
   "'sentinel' attribute requires named arguments">,
   InGroup<IgnoredAttributes>;
@@ -2715,6 +2749,10 @@
 // objc_bridge attribute diagnostics.
 def err_objc_attr_not_id : Error<
   "parameter of %0 attribute must be a single name of an Objective-C %select{class|protocol}1">;
+def err_objc_attr_typedef_not_id : Error<
+  "parameter of %0 attribute must be 'id' when used on a typedef">;
+def err_objc_attr_typedef_not_void_pointer : Error<
+  "'objc_bridge(id)' is only allowed on structs and typedefs of void pointers">;
 def err_objc_cf_bridged_not_interface : Error<
   "CF object of type %0 is bridged to %1, which is not an Objective-C class">;
 def err_objc_ns_bridged_invalid_cfobject : Error<
@@ -2838,6 +2876,9 @@
     "|volatile and restrict|const, volatile, and restrict}4)}2">;
 
 def note_ovl_candidate_inherited_constructor : Note<"inherited from here">;
+def note_ovl_candidate_illegal_constructor : Note<
+    "candidate %select{constructor|template}0 ignored: "
+    "instantiation %select{takes|would take}0 its own class type by value">;
 def note_ovl_candidate_bad_deduction : Note<
     "candidate template ignored: failed template argument deduction">;
 def note_ovl_candidate_incomplete_deduction : Note<"candidate template ignored: "
@@ -3290,6 +3331,10 @@
 def err_deduced_non_type_template_arg_type_mismatch : Error<
   "deduced non-type template argument does not have the same type as the "
   "its corresponding template parameter%diff{ ($ vs $)|}0,1">;
+def err_non_type_template_arg_subobject : Error<
+  "non-type template argument refers to subobject '%0'">;
+def err_non_type_template_arg_addr_label_diff : Error<
+  "template argument / label address difference / what did you expect?">;
 def err_template_arg_not_convertible : Error<
   "non-type template argument of type %0 cannot be converted to a value "
   "of type %1">;
@@ -3341,6 +3386,9 @@
   "non-type template argument does not refer to an object or function">;
 def err_template_arg_not_pointer_to_member_form : Error<
   "non-type template argument is not a pointer to member constant">;
+def err_template_arg_member_ptr_base_derived_not_supported : Error<
+  "sorry, non-type template argument of pointer-to-member type %1 that refers "
+  "to member %q0 of a different class is not supported yet">;
 def ext_template_arg_extra_parens : ExtWarn<
   "address non-type template argument cannot be surrounded by parentheses">;
 def warn_cxx98_compat_template_arg_extra_parens : Warning<
@@ -3876,8 +3924,8 @@
 def err_redefinition : Error<"redefinition of %0">;
 def err_alias_after_tentative :
   Error<"alias definition of %0 after tentative definition">;
-def err_tentative_after_alias :
-  Error<"tentative definition of %0 after alias definition">;
+def err_alias_is_definition :
+  Error<"definition %0 cannot also be an alias">;
 def err_definition_of_implicitly_declared_member : Error<
   "definition of implicitly declared %select{default constructor|copy "
   "constructor|move constructor|copy assignment operator|move assignment "
@@ -4040,6 +4088,9 @@
 def ext_enumerator_increment_too_large : ExtWarn<
   "incremented enumerator value %0 is not representable in the "
   "largest integer type">, InGroup<EnumTooLarge>;
+def warn_flag_enum_constant_out_of_range : Warning<
+  "enumeration value %0 is out of range of flags in enumeration type %1">,
+  InGroup<FlagEnum>;
   
 def warn_illegal_constant_array_size : Extension<
   "size of static array must be an integer constant expression">;
@@ -4124,9 +4175,10 @@
   "missing field %0 initializer">,
   InGroup<MissingFieldInitializers>, DefaultIgnore;
 def warn_braces_around_scalar_init : Warning<
-  "braces around scalar initializer">;
+  "braces around scalar initializer">, InGroup<DiagGroup<"braced-scalar-init">>;
 def ext_many_braces_around_scalar_init : ExtWarn<
-  "too many braces around scalar initializer">;
+  "too many braces around scalar initializer">,
+  InGroup<DiagGroup<"many-braces-around-scalar-init">>;
 def ext_complex_component_init : Extension<
   "complex initialization specifying real and imaginary components "
   "is an extension">, InGroup<DiagGroup<"complex-component-init">>;
@@ -4255,6 +4307,12 @@
   "jump bypasses initialization of try block">;
 def note_protected_by_cxx_catch : Note<
   "jump bypasses initialization of catch block">;
+def note_protected_by_seh_try : Note<
+  "jump bypasses initialization of __try block">;
+def note_protected_by_seh_except : Note<
+  "jump bypasses initialization of __except block">;
+def note_protected_by_seh_finally : Note<
+  "jump bypasses initialization of __finally block">;
 def note_protected_by___block : Note<
   "jump bypasses setup of __block variable">;
 def note_protected_by_objc_ownership : Note<
@@ -4287,6 +4345,12 @@
   "jump exits try block">;
 def note_exits_cxx_catch : Note<
   "jump exits catch block">;
+def note_exits_seh_try : Note<
+  "jump exits __try block">;
+def note_exits_seh_except : Note<
+  "jump exits __except block">;
+def note_exits_seh_finally : Note<
+  "jump exits __finally block">;
 def note_exits_objc_autoreleasepool : Note<
   "jump exits autoreleasepool block">;
 def note_exits_objc_ownership : Note<
@@ -4298,6 +4362,9 @@
 def note_exits_block_captures_weak : Note<
   "jump exits lifetime of block which weakly captures a variable">;
 
+def err_func_returning_qualified_void : ExtWarn<
+  "function cannot return qualified void type %0">,
+  InGroup<DiagGroup<"qualified-void-return-type">>;
 def err_func_returning_array_function : Error<
   "function cannot return %select{array|function}0 type %1">;
 def err_field_declared_as_function : Error<"field %0 declared as a function">;
@@ -4679,6 +4746,9 @@
 def warn_self_assignment : Warning<
   "explicitly assigning value of variable of type %0 to itself">,
   InGroup<SelfAssignment>, DefaultIgnore;
+def warn_self_move : Warning<
+  "explicitly moving variable of type %0 to itself">,
+  InGroup<SelfMove>, DefaultIgnore;
 
 def warn_string_plus_int : Warning<
   "adding %0 to a string does not append to the string">,
@@ -4823,6 +4893,8 @@
   "instance variables cannot be of reference type">;
 def err_typecheck_illegal_increment_decrement : Error<
   "cannot %select{decrement|increment}1 value of type %0">;
+def err_typecheck_expect_int : Error<
+  "used type %0 where integer is required">;
 def err_typecheck_arithmetic_incomplete_type : Error<
   "arithmetic on a pointer to an incomplete type %0">;
 def err_typecheck_pointer_arith_function_type : Error<
@@ -4957,9 +5029,11 @@
 def ext_typecheck_comparison_of_distinct_pointers_nonstandard : ExtWarn<
   "comparison of distinct pointer types (%0 and %1) uses non-standard "
   "composite pointer type %2">, InGroup<CompareDistinctPointerType>;
+def err_typecheck_op_on_nonoverlapping_address_space_pointers : Error<
+  "%select{comparison between %diff{ ($ and $)|}0,1"
+  "|arithmetic operation with operands of type %diff{ ($ and $)|}0,1}2"
+  " which are pointers to non-overlapping address spaces">;
 def err_typecheck_assign_const : Error<"read-only variable is not assignable">;
-def err_stmtexpr_file_scope : Error<
-  "statement expression not allowed at file scope">;
 def warn_mixed_sign_comparison : Warning<
   "comparison of integers of different signs: %0 and %1">,
   InGroup<SignCompare>, DefaultIgnore;
@@ -4984,6 +5058,9 @@
   "comparison between NULL and non-pointer "
   "%select{(%1 and NULL)|(NULL and %1)}0">,
   InGroup<NullArithmetic>;
+def err_shift_rhs_only_vector : Error<
+  "requested shift is a vector of type %0 but the first operand is not a "
+  "vector (%1)">;
 
 def warn_logical_not_on_lhs_of_comparison : Warning<
   "logical not is only applied to the left hand side of this comparison">,
@@ -5227,6 +5304,11 @@
 def err_bad_cxx_cast_generic : Error<
   "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|"
   "functional-style cast}0 from %1 to %2 is not allowed">;
+def err_bad_cxx_cast_unrelated_class : Error<
+  "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|"
+  "functional-style cast}0 from %1 to %2, which are not related by "
+  "inheritance, is not allowed">;
+def note_type_incomplete : Note<"%0 is incomplete">;
 def err_bad_cxx_cast_rvalue : Error<
   "%select{const_cast|static_cast|reinterpret_cast|dynamic_cast|C-style cast|"
   "functional-style cast}0 from rvalue to reference type %2">;
@@ -5266,7 +5348,7 @@
   "cannot %select{||reinterpret_cast||C-style cast|}0 from member pointer "
   "type %1 to member pointer type %2 of different size">;
 def err_bad_reinterpret_cast_reference : Error<
-  "reinterpret_cast of a %0 to %1 needs its address which is not allowed">;
+  "reinterpret_cast of a %0 to %1 needs its address, which is not allowed">;
 def warn_undefined_reinterpret_cast : Warning<
   "reinterpret_cast from %0 to %1 has undefined behavior">,
   InGroup<UndefinedReinterpretCast>, DefaultIgnore;
@@ -5300,6 +5382,7 @@
 def err_uuidof_with_multiple_guids : Error<
   "cannot call operator __uuidof on a type with multiple GUIDs">;
 def err_incomplete_typeid : Error<"'typeid' of incomplete type %0">;
+def err_variably_modified_typeid : Error<"'typeid' of variably modified type %0">;
 def err_static_illegal_in_new : Error<
   "the 'static' modifier for the array size is not legal in new expressions">;
 def err_array_new_needs_size : Error<
@@ -5397,6 +5480,12 @@
   "cannot use '%0' with exceptions disabled">;
 def err_objc_exceptions_disabled : Error<
   "cannot use '%0' with Objective-C exceptions disabled">;
+def err_seh_try_outside_functions : Error<
+  "cannot use SEH '__try' in blocks, captured regions, or Obj-C method decls">;
+def err_mixing_cxx_try_seh_try : Error<
+  "cannot use C++ 'try' in the same function as SEH '__try'">;
+def note_conflicting_try_here : Note<
+  "conflicting %0 here">;
 def warn_non_virtual_dtor : Warning<
   "%0 has virtual functions but non-virtual destructor">,
   InGroup<NonVirtualDtor>, DefaultIgnore;
@@ -5438,6 +5527,12 @@
 def err_conditional_ambiguous_ovl : Error<
   "conditional expression is ambiguous; %diff{$ and $|types}0,1 "
   "can be converted to several common types">;
+def err_conditional_vector_size : Error<
+  "vector condition type %0 and result type %1 do not have the same number "
+  "of elements">;
+def err_conditional_vector_element_size : Error<
+  "vector condition type %0 and result type %1 do not have elements of the "
+  "same size">;
 
 def err_throw_incomplete : Error<
   "cannot throw object of incomplete type %0">;
@@ -5550,8 +5645,8 @@
 def err_pseudo_dtor_call_with_args : Error<
   "call to pseudo-destructor cannot have any arguments">;
 def err_dtor_expr_without_call : Error<
-  "%select{destructor reference|pseudo-destructor expression}0 must be "
-  "called immediately with '()'">;
+  "reference to %select{destructor|pseudo-destructor}0 must be called"
+  "%select{|; did you mean to call it with no arguments?}1">;
 def err_pseudo_dtor_destructor_non_type : Error<
   "%0 does not refer to a type name in pseudo-destructor expression; expected "
   "the name of type %1">;
@@ -5573,7 +5668,7 @@
   "invokes a deleted function">;
   
 def err_expected_class_or_namespace : Error<"%0 is not a class"
-  "%select{ or namespace|, namespace, or scoped enumeration}1">;
+  "%select{ or namespace|, namespace, or enumeration}1">;
 def err_invalid_declarator_scope : Error<"cannot define or redeclare %0 here "
   "because namespace %1 does not enclose namespace %2">;
 def err_invalid_declarator_global_scope : Error<
@@ -5979,6 +6074,9 @@
 def err_ref_bad_target : Error<
   "reference to %select{__device__|__global__|__host__|__host__ __device__}0 "
   "function %1 in %select{__device__|__global__|__host__|__host__ __device__}2 function">;
+def warn_host_calls_from_host_device : Warning<
+  "calling __host__ function %0 from __host__ __device__ function %1 can lead to runtime errors">,
+  InGroup<CudaCompat>;
 
 def warn_non_pod_vararg_with_format_string : Warning<
   "cannot pass %select{non-POD|non-trivial}0 object of type %1 to variadic "
@@ -6020,12 +6118,14 @@
 def err_typecheck_call_invalid_unary_fp : Error<
   "floating point classification requires argument of floating point type "
   "(passed in %0)">;
+def err_typecheck_cond_expect_int_float : Error<
+  "used type %0 where integer or floating point type is required">;
 def err_typecheck_cond_expect_scalar : Error<
   "used type %0 where arithmetic or pointer type is required">;
+def err_typecheck_cond_expect_nonfloat : Error<
+  "used type %0 where floating point type is not allowed">;
 def ext_typecheck_cond_one_void : Extension<
   "C99 forbids conditional expressions with only one void side">;
-def err_typecheck_cond_expect_scalar_or_vector : Error<
-  "used type %0 where arithmetic, pointer, or vector type is required">;
 def err_typecheck_cast_to_incomplete : Error<
   "cast to incomplete type %0">;
 def ext_typecheck_cast_nonscalar : Extension<
@@ -6074,13 +6174,19 @@
   InGroup<UnusedValue>;
 def warn_unused_property_expr : Warning<
  "property access result unused - getters should not be used for side effects">,
-  InGroup<UnusedValue>;
+  InGroup<UnusedGetterReturnValue>;
 def warn_unused_container_subscript_expr : Warning<
  "container access result unused - container access should not be used for side effects">,
   InGroup<UnusedValue>;
 def warn_unused_call : Warning<
   "ignoring return value of function declared with %0 attribute">,
   InGroup<UnusedValue>;
+def warn_side_effects_unevaluated_context : Warning<
+  "expression with side effects has no effect in an unevaluated context">,
+  InGroup<UnevaluatedExpression>;
+def warn_side_effects_typeid : Warning<
+  "expression with side effects will be evaluated despite being used as an "
+  "operand to 'typeid'">, InGroup<PotentiallyEvaluatedExpression>;
 def warn_unused_result : Warning<
   "ignoring return value of function declared with warn_unused_result "
   "attribute">, InGroup<DiagGroup<"unused-result">>;
@@ -6112,11 +6218,15 @@
 def warn_zero_size_struct_union_in_extern_c : Warning<"%select{|empty }0"
   "%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++">,
   InGroup<ExternCCompat>;
+def warn_cast_qual : Warning<"cast from %0 to %1 drops %select{const and "
+  "volatile qualifiers|const qualifier|volatile qualifier}2">,
+  InGroup<CastQual>, DefaultIgnore;
+def warn_cast_qual2 : Warning<"cast from %0 to %1 must have all intermediate "
+  "pointers const qualified to be safe">, InGroup<CastQual>, DefaultIgnore;
 } // End of general sema category.
 
 // inline asm.
 let CategoryName = "Inline Assembly Issue" in {
-  def err_asm_wide_character : Error<"wide string is invalid in 'asm'">;
   def err_asm_invalid_lvalue_in_output : Error<"invalid lvalue in asm output">;
   def err_asm_invalid_output_constraint : Error<
     "invalid output constraint '%0' in asm">;
@@ -6124,11 +6234,15 @@
     "invalid lvalue in asm input for constraint '%0'">;
   def err_asm_invalid_input_constraint : Error<
     "invalid input constraint '%0' in asm">;
+  def err_asm_immediate_expected : Error<"constraint '%0' expects "
+    "an integer constant expression">;
   def err_asm_invalid_type_in_input : Error<
     "invalid type %0 in asm input for constraint '%1'">;
   def err_asm_tying_incompatible_types : Error<
     "unsupported inline asm: input with type "
     "%diff{$ matching output with type $|}0,1">;
+  def err_asm_unexpected_constraint_alternatives : Error<
+    "asm constraint has an unexpected number of alternatives: %0 vs %1">;
   def err_asm_incomplete_type : Error<"asm operand has incomplete type %0">;
   def err_asm_unknown_register_name : Error<"unknown register name '%0' in asm">;
   def err_asm_bad_register_type : Error<"bad type for named register variable">;
@@ -6139,6 +6253,8 @@
   def err_invalid_asm_cast_lvalue : Error<
     "invalid use of a cast in a inline asm context requiring an l-value: "
     "remove the cast or build with -fheinous-gnu-extensions">;
+  def err_invalid_asm_value_for_constraint
+      : Error <"value '%0' out of range for constraint '%1'">;
 
   def warn_asm_label_on_auto_decl : Warning<
     "ignored asm label '%0' on automatic variable">;
@@ -6304,6 +6420,9 @@
 def err_incomplete_base_class : Error<"base class has incomplete type">;
 def err_duplicate_base_class : Error<
   "base class %0 specified more than once as a direct base class">;
+def warn_inaccessible_base_class : Warning<
+  "direct base %0 is inaccessible due to ambiguity:%1">,
+  InGroup<DiagGroup<"inaccessible-base">>;
 // FIXME: better way to display derivation?  Pass entire thing into diagclient?
 def err_ambiguous_derived_to_base_conv : Error<
   "ambiguous conversion from derived class %0 to base class %1:%2">;
@@ -6414,7 +6533,13 @@
 def err_conv_function_to_function : Error<
   "conversion function cannot convert to a function type">;
 def err_conv_function_with_complex_decl : Error<
-  "must use a typedef to declare a conversion to %0">;
+  "cannot specify any part of a return type in the "
+  "declaration of a conversion function"
+  "%select{"
+  "; put the complete type after 'operator'|"
+  "; use a typedef to declare a conversion to %1|"
+  "; use an alias template to declare a conversion to %1|"
+  "}0">;
 def err_conv_function_redeclared : Error<
   "conversion function cannot be redeclared">;
 def warn_conv_to_self_not_used : Warning<
@@ -6891,6 +7016,17 @@
 def err_convertvector_incompatible_vector : Error<
   "first two arguments to __builtin_convertvector must have the same number of elements">;
 
+def err_first_argument_to_cwsc_not_call : Error<
+  "first argument to __builtin_call_with_static_chain must be a non-member call expression">;
+def err_first_argument_to_cwsc_block_call : Error<
+  "first argument to __builtin_call_with_static_chain must not be a block call">;
+def err_first_argument_to_cwsc_builtin_call : Error<
+  "first argument to __builtin_call_with_static_chain must not be a builtin call">;
+def err_first_argument_to_cwsc_pdtor_call : Error<
+  "first argument to __builtin_call_with_static_chain must not be a pseudo-destructor call">;
+def err_second_argument_to_cwsc_not_pointer : Error<
+  "second argument to __builtin_call_with_static_chain must be of pointer type">;
+
 def err_vector_incorrect_num_initializers : Error<
   "%select{too many|too few}0 elements in vector initialization (expected %1 elements, have %2)">;
 def err_altivec_empty_initializer : Error<"expected initializer">;
@@ -7102,9 +7238,14 @@
 
 def err_non_asm_stmt_in_naked_function : Error<
   "non-ASM statement in naked function is not supported">;
+def err_asm_naked_this_ref : Error<
+  "'this' pointer references not allowed in naked functions">;
 def err_asm_naked_parm_ref : Error<
   "parameter references not allowed in naked functions">;
 
+def ext_deprecated_attr_is_a_cxx14_extension : ExtWarn<
+  "use of the 'deprecated' attribute is a C++14 extension">, InGroup<CXX14>;
+
 // OpenCL warnings and errors.
 def err_invalid_astype_of_different_size : Error<
   "invalid reinterpretation: sizes of %0 and %1 must match">;
@@ -7167,7 +7308,7 @@
 def err_omp_var_used : Error<
   "'#pragma omp %0' must precede all references to variable %q1">;
 def err_omp_var_thread_local : Error<
-  "variable %0 cannot be threadprivate because it is thread-local">;
+  "variable %0 cannot be threadprivate because it is %select{thread-local|a global named register variable}1">;
 def err_omp_private_incomplete_type : Error<
   "a private variable with incomplete type %0">;
 def err_omp_firstprivate_incomplete_type : Error<
@@ -7331,11 +7472,11 @@
 def err_omp_atomic_read_not_expression_statement : Error<
   "the statement for 'atomic read' must be an expression statement of form 'v = x;',"
   " where v and x are both lvalue expressions with scalar type">;
-def note_omp_atomic_read: Note<
+def note_omp_atomic_read_write: Note<
   "%select{expected an expression statement|expected built-in assignment operator|expected expression of scalar type|expected lvalue expression}0">;
 def err_omp_atomic_write_not_expression_statement : Error<
   "the statement for 'atomic write' must be an expression statement of form 'x = expr;',"
-  " where x is an l-value expression with scalar type">;
+  " where x is a lvalue expression with scalar type">;
 def err_omp_atomic_update_not_expression_statement : Error<
   "the statement for 'atomic%select{| update}0' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x',"
   " where x is an l-value expression with scalar type">;
@@ -7357,6 +7498,10 @@
   "nested teams construct here">;
 def note_omp_nested_statement_here : Note<
   "%select{statement|directive}0 outside teams construct here">;
+def err_omp_single_copyprivate_with_nowait : Error<
+  "the 'copyprivate' clause must not be used with the 'nowait' clause">;
+def note_omp_nowait_clause_here : Note<
+  "'nowait' clause is here">;
 } // end of OpenMP category
 
 let CategoryName = "Related Result Type Issue" in {
diff --git a/include/clang/Basic/DiagnosticSerializationKinds.td b/include/clang/Basic/DiagnosticSerializationKinds.td
index 5de2c6a..b0d352f 100644
--- a/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -41,6 +41,8 @@
   "%0 differs in PCH file vs. current file">;
 def err_pch_diagopt_mismatch : Error<"%0 is currently enabled, but was not in "
   "the PCH file">;
+def err_pch_modulecache_mismatch : Error<"PCH was compiled with module cache "
+  "path '%0', but the path is currently '%1'">;
   
 def err_pch_version_too_old : Error<
     "PCH file uses an older PCH format that is no longer supported">;
@@ -58,6 +60,9 @@
 def err_imported_module_modmap_changed : Error<
     "module '%0' imported by AST file '%1' found in a different module map file"
     " (%2) than when the importing AST file was built (%3)">, DefaultFatal;
+def err_imported_module_relocated : Error<
+    "module '%0' was built in directory '%1' but now resides in "
+    "directory '%2'">, DefaultFatal;
 def err_module_different_modmap : Error<
     "module '%0' %select{uses|does not use}1 additional module map '%2'"
     "%select{| not}1 used when the module was built">;
diff --git a/include/clang/Basic/FileManager.h b/include/clang/Basic/FileManager.h
index 132bf37..37e19e1 100644
--- a/include/clang/Basic/FileManager.h
+++ b/include/clang/Basic/FileManager.h
@@ -73,11 +73,7 @@
   mutable std::unique_ptr<vfs::File> File;
   friend class FileManager;
 
-  void closeFile() const {
-    File.reset(); // rely on destructor to close File
-  }
-
-  void operator=(const FileEntry &) LLVM_DELETED_FUNCTION;
+  void operator=(const FileEntry &) = delete;
 
 public:
   FileEntry()
@@ -109,6 +105,10 @@
   /// \brief Check whether the file is a named pipe (and thus can't be opened by
   /// the native FileManager methods).
   bool isNamedPipe() const { return IsNamedPipe; }
+
+  void closeFile() const {
+    File.reset(); // rely on destructor to close File
+  }
 };
 
 struct FileData;
@@ -274,6 +274,9 @@
   static void modifyFileEntry(FileEntry *File, off_t Size,
                               time_t ModificationTime);
 
+  /// \brief Remove any './' components from a path.
+  static bool removeDotPaths(SmallVectorImpl<char> &Path);
+
   /// \brief Retrieve the canonical name for a given directory.
   ///
   /// This is a very expensive operation, despite its results being cached,
diff --git a/include/clang/Basic/IdentifierTable.h b/include/clang/Basic/IdentifierTable.h
index ed92339..f540c58 100644
--- a/include/clang/Basic/IdentifierTable.h
+++ b/include/clang/Basic/IdentifierTable.h
@@ -73,8 +73,8 @@
   void *FETokenInfo;               // Managed by the language front-end.
   llvm::StringMapEntry<IdentifierInfo*> *Entry;
 
-  IdentifierInfo(const IdentifierInfo&) LLVM_DELETED_FUNCTION;
-  void operator=(const IdentifierInfo&) LLVM_DELETED_FUNCTION;
+  IdentifierInfo(const IdentifierInfo&) = delete;
+  void operator=(const IdentifierInfo&) = delete;
 
   friend class IdentifierTable;
   
@@ -249,6 +249,9 @@
   }
   bool isCPlusPlusOperatorKeyword() const { return IsCPPOperatorKeyword; }
 
+  /// \brief Return true if this token is a keyword in the specified language.
+  bool isKeyword(const LangOptions &LangOpts);
+
   /// getFETokenInfo/setFETokenInfo - The language front-end is allowed to
   /// associate arbitrary metadata with this token.
   template<typename T>
@@ -353,8 +356,8 @@
 /// actual functionality.
 class IdentifierIterator {
 private:
-  IdentifierIterator(const IdentifierIterator &) LLVM_DELETED_FUNCTION;
-  void operator=(const IdentifierIterator &) LLVM_DELETED_FUNCTION;
+  IdentifierIterator(const IdentifierIterator &) = delete;
+  void operator=(const IdentifierIterator &) = delete;
 
 protected:
   IdentifierIterator() { }
@@ -724,8 +727,8 @@
 /// multi-keyword caching.
 class SelectorTable {
   void *Impl;  // Actually a SelectorTableImpl
-  SelectorTable(const SelectorTable &) LLVM_DELETED_FUNCTION;
-  void operator=(const SelectorTable &) LLVM_DELETED_FUNCTION;
+  SelectorTable(const SelectorTable &) = delete;
+  void operator=(const SelectorTable &) = delete;
 public:
   SelectorTable();
   ~SelectorTable();
diff --git a/include/clang/Basic/LangOptions.def b/include/clang/Basic/LangOptions.def
index 82dba18..3c15057 100644
--- a/include/clang/Basic/LangOptions.def
+++ b/include/clang/Basic/LangOptions.def
@@ -114,6 +114,7 @@
 LANGOPT(Freestanding, 1, 0, "freestanding implementation")
 LANGOPT(NoBuiltin         , 1, 0, "disable builtin functions")
 LANGOPT(NoMathBuiltin     , 1, 0, "disable math builtin functions")
+LANGOPT(GNUAsm            , 1, 1, "GNU-style inline assembly")
 
 BENIGN_LANGOPT(ThreadsafeStatics , 1, 1, "thread-safe static initializers")
 LANGOPT(POSIXThreads      , 1, 0, "POSIX thread support")
@@ -122,10 +123,12 @@
 LANGOPT(MathErrno         , 1, 1, "errno support for math functions")
 BENIGN_LANGOPT(HeinousExtensions , 1, 0, "Extensions that we really don't like and may be ripped out at any time")
 LANGOPT(Modules           , 1, 0, "modules extension to C")
-LANGOPT(ModulesDeclUse    , 1, 0, "require declaration of module uses")
+COMPATIBLE_LANGOPT(ModulesDeclUse    , 1, 0, "require declaration of module uses")
 LANGOPT(ModulesSearchAll  , 1, 1, "search even non-imported modules to find unresolved references")
-LANGOPT(ModulesStrictDeclUse, 1, 0, "require declaration of module uses and all headers to be in modules")
+COMPATIBLE_LANGOPT(ModulesStrictDeclUse, 1, 0, "require declaration of module uses and all headers to be in modules")
 LANGOPT(ModulesErrorRecovery, 1, 1, "automatically import modules as needed when performing error recovery")
+BENIGN_LANGOPT(ModulesImplicitMaps, 1, 1, "use files called module.modulemap implicitly as module maps")
+BENIGN_LANGOPT(ImplicitModules, 1, 1, "build modules that are not specified via -fmodule-file")
 COMPATIBLE_LANGOPT(Optimize          , 1, 0, "__OPTIMIZE__ predefined macro")
 COMPATIBLE_LANGOPT(OptimizeSize      , 1, 0, "__OPTIMIZE_SIZE__ predefined macro")
 LANGOPT(Static            , 1, 0, "__STATIC__ predefined macro (as opposed to __DYNAMIC__)")
@@ -157,9 +160,12 @@
 LANGOPT(CUDA              , 1, 0, "CUDA")
 LANGOPT(OpenMP            , 1, 0, "OpenMP support")
 LANGOPT(Renderscript      , 1, 0, "RenderScript")
+LANGOPT(CUDAIsDevice      , 1, 0, "Compiling for CUDA device")
+LANGOPT(CUDAAllowHostCallsFromHostDevice, 1, 0, "Allow host device functions to call host functions")
 
 LANGOPT(AssumeSaneOperatorNew , 1, 1, "implicit __attribute__((malloc)) for C++'s new operators")
 LANGOPT(SizedDeallocation , 1, 0, "enable sized deallocation functions")
+LANGOPT(DefineSizedDeallocation , 1, 0, "generate weak definitions of sized delete")
 BENIGN_LANGOPT(ElideConstructors , 1, 1, "C++ copy constructor elision")
 BENIGN_LANGOPT(DumpRecordLayouts , 1, 0, "dumping the layout of IRgen'd records")
 BENIGN_LANGOPT(DumpRecordLayoutsSimple , 1, 0, "dumping the layout of IRgen'd records in a simple form")
diff --git a/include/clang/Basic/LangOptions.h b/include/clang/Basic/LangOptions.h
index 5ac96c5..8edfa4b 100644
--- a/include/clang/Basic/LangOptions.h
+++ b/include/clang/Basic/LangOptions.h
@@ -21,6 +21,7 @@
 #include "clang/Basic/Sanitizers.h"
 #include "clang/Basic/Visibility.h"
 #include <string>
+#include <vector>
 
 namespace clang {
 
@@ -70,9 +71,9 @@
   /// \brief Set of enabled sanitizers.
   SanitizerSet Sanitize;
 
-  /// \brief Path to blacklist file specifying which objects
+  /// \brief Paths to blacklist files specifying which objects
   /// (files, functions, variables) should not be instrumented.
-  std::string SanitizerBlacklistFile;
+  std::vector<std::string> SanitizerBlacklistFiles;
 
   clang::ObjCRuntime ObjCRuntime;
 
@@ -92,6 +93,10 @@
   /// treat this as the CurrentModule.
   std::string ImplementationOfModule;
 
+  /// \brief The names of any features to enable in module 'requires' decls
+  /// in addition to the hard-coded list in Module.cpp and the target features.
+  std::vector<std::string> ModuleFeatures;
+
   /// \brief Options for parsing comments.
   CommentOptions CommentOpts;
   
diff --git a/include/clang/Basic/Module.h b/include/clang/Basic/Module.h
index e46be9e..e3953a4 100644
--- a/include/clang/Basic/Module.h
+++ b/include/clang/Basic/Module.h
@@ -55,7 +55,12 @@
   /// \brief The parent of this module. This will be NULL for the top-level
   /// module.
   Module *Parent;
-  
+
+  /// \brief The build directory of this module. This is the directory in
+  /// which the module is notionally built, and relative to which its headers
+  /// are found.
+  const DirectoryEntry *Directory;
+
   /// \brief The umbrella header or directory.
   llvm::PointerUnion<const DirectoryEntry *, const FileEntry *> Umbrella;
   
@@ -81,26 +86,28 @@
   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
 
 public:
-  /// \brief The headers that are part of this module.
-  SmallVector<const FileEntry *, 2> NormalHeaders;
-
-  /// \brief The headers that are logically part of this module but
-  /// must be textually included.
-  SmallVector<const FileEntry *, 2> TextualHeaders;
-
-  /// \brief The headers that are private to this module.
-  SmallVector<const FileEntry *, 2> PrivateHeaders;
-
-  /// \brief The headers that are private to this module and are to be
-  /// included textually.
-  SmallVector<const FileEntry *, 2> PrivateTextualHeaders;
-
-  /// \brief The headers that are explicitly excluded from this module.
-  SmallVector<const FileEntry *, 2> ExcludedHeaders;
+  enum HeaderKind {
+    HK_Normal,
+    HK_Textual,
+    HK_Private,
+    HK_PrivateTextual,
+    HK_Excluded
+  };
+  static const int NumHeaderKinds = HK_Excluded + 1;
 
   /// \brief Information about a header directive as found in the module map
   /// file.
-  struct HeaderDirective {
+  struct Header {
+    std::string NameAsWritten;
+    const FileEntry *Entry;
+  };
+
+  /// \brief The headers that are part of this module.
+  SmallVector<Header, 2> Headers[5];
+
+  /// \brief Stored information about a header directive that was found in the
+  /// module map file but has not been resolved to a file.
+  struct UnresolvedHeaderDirective {
     SourceLocation FileNameLoc;
     std::string FileName;
     bool IsUmbrella;
@@ -108,7 +115,7 @@
 
   /// \brief Headers that are mentioned in the module map file but could not be
   /// found on the file system.
-  SmallVector<HeaderDirective, 1> MissingHeaders;
+  SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
 
   /// \brief An individual requirement: a feature name and a flag indicating
   /// the required state of that feature.
@@ -303,7 +310,7 @@
   bool isAvailable(const LangOptions &LangOpts, 
                    const TargetInfo &Target,
                    Requirement &Req,
-                   HeaderDirective &MissingHeader) const;
+                   UnresolvedHeaderDirective &MissingHeader) const;
 
   /// \brief Determine whether this module is a submodule.
   bool isSubModule() const { return Parent != nullptr; }
diff --git a/include/clang/Basic/PlistSupport.h b/include/clang/Basic/PlistSupport.h
index 081f22d..84dd291 100644
--- a/include/clang/Basic/PlistSupport.h
+++ b/include/clang/Basic/PlistSupport.h
@@ -12,7 +12,6 @@
 
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
-#include "clang/Lex/Lexer.h"
 #include "llvm/Support/raw_ostream.h"
 
 namespace clang {
@@ -89,31 +88,29 @@
 }
 
 inline void EmitLocation(raw_ostream &o, const SourceManager &SM,
-                         const LangOptions &LangOpts, SourceLocation L,
-                         const FIDMap &FM, unsigned indent,
-                         bool extend = false) {
-  FullSourceLoc Loc(SM.getExpansionLoc(L), const_cast<SourceManager &>(SM));
+                         SourceLocation L, const FIDMap &FM, unsigned indent) {
+  if (L.isInvalid()) return;
 
-  // Add in the length of the token, so that we cover multi-char tokens.
-  unsigned offset =
-      extend ? Lexer::MeasureTokenLength(Loc, SM, LangOpts) - 1 : 0;
+  FullSourceLoc Loc(SM.getExpansionLoc(L), const_cast<SourceManager &>(SM));
 
   Indent(o, indent) << "<dict>\n";
   Indent(o, indent) << " <key>line</key>";
   EmitInteger(o, Loc.getExpansionLineNumber()) << '\n';
   Indent(o, indent) << " <key>col</key>";
-  EmitInteger(o, Loc.getExpansionColumnNumber() + offset) << '\n';
+  EmitInteger(o, Loc.getExpansionColumnNumber()) << '\n';
   Indent(o, indent) << " <key>file</key>";
   EmitInteger(o, GetFID(FM, SM, Loc)) << '\n';
   Indent(o, indent) << "</dict>\n";
 }
 
 inline void EmitRange(raw_ostream &o, const SourceManager &SM,
-                      const LangOptions &LangOpts, CharSourceRange R,
-                      const FIDMap &FM, unsigned indent) {
+                      CharSourceRange R, const FIDMap &FM, unsigned indent) {
+  if (R.isInvalid()) return;
+
+  assert(R.isCharRange() && "cannot handle a token range");
   Indent(o, indent) << "<array>\n";
-  EmitLocation(o, SM, LangOpts, R.getBegin(), FM, indent + 1);
-  EmitLocation(o, SM, LangOpts, R.getEnd(), FM, indent + 1, R.isTokenRange());
+  EmitLocation(o, SM, R.getBegin(), FM, indent + 1);
+  EmitLocation(o, SM, R.getEnd(), FM, indent + 1);
   Indent(o, indent) << "</array>\n";
 }
 }
diff --git a/include/clang/Basic/SanitizerBlacklist.h b/include/clang/Basic/SanitizerBlacklist.h
index 2ce268a..e651e18 100644
--- a/include/clang/Basic/SanitizerBlacklist.h
+++ b/include/clang/Basic/SanitizerBlacklist.h
@@ -28,7 +28,8 @@
   SourceManager &SM;
 
 public:
-  SanitizerBlacklist(StringRef BlacklistPath, SourceManager &SM);
+  SanitizerBlacklist(const std::vector<std::string> &BlacklistPaths,
+                     SourceManager &SM);
   bool isBlacklistedGlobal(StringRef GlobalName,
                            StringRef Category = StringRef()) const;
   bool isBlacklistedType(StringRef MangledTypeName,
diff --git a/include/clang/Basic/Sanitizers.def b/include/clang/Basic/Sanitizers.def
index adb9b04..a0acce9 100644
--- a/include/clang/Basic/Sanitizers.def
+++ b/include/clang/Basic/Sanitizers.def
@@ -76,6 +76,10 @@
 // DataFlowSanitizer
 SANITIZER("dataflow", DataFlow)
 
+// Control Flow Integrity
+SANITIZER("cfi-vptr", CFIVptr)
+SANITIZER_GROUP("cfi", CFI, CFIVptr)
+
 // -fsanitize=undefined includes all the sanitizers which have low overhead, no
 // ABI or address space layout implications, and only catch undefined behavior.
 SANITIZER_GROUP("undefined", Undefined,
@@ -102,5 +106,9 @@
 SANITIZER("local-bounds", LocalBounds)
 SANITIZER_GROUP("bounds", Bounds, ArrayBounds | LocalBounds)
 
+// Magic group, containing all sanitizers. For example, "-fno-sanitize=all"
+// can be used to disable all the sanitizers.
+SANITIZER_GROUP("all", All, ~0)
+
 #undef SANITIZER
 #undef SANITIZER_GROUP
diff --git a/include/clang/Basic/SourceManager.h b/include/clang/Basic/SourceManager.h
index 717258d..4fa95c5 100644
--- a/include/clang/Basic/SourceManager.h
+++ b/include/clang/Basic/SourceManager.h
@@ -231,7 +231,7 @@
 
   private:
     // Disable assignments.
-    ContentCache &operator=(const ContentCache& RHS) LLVM_DELETED_FUNCTION;
+    ContentCache &operator=(const ContentCache& RHS) = delete;
   };
 
   // Assert that the \c ContentCache objects will always be 8-byte aligned so
@@ -705,8 +705,8 @@
   SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
 
   // SourceManager doesn't support copy construction.
-  explicit SourceManager(const SourceManager&) LLVM_DELETED_FUNCTION;
-  void operator=(const SourceManager&) LLVM_DELETED_FUNCTION;
+  explicit SourceManager(const SourceManager&) = delete;
+  void operator=(const SourceManager&) = delete;
 public:
   SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
                 bool UserFilesAreVolatile = false);
@@ -1057,10 +1057,16 @@
   getImmediateExpansionRange(SourceLocation Loc) const;
 
   /// \brief Given a SourceLocation object, return the range of
-  /// tokens covered by the expansion the ultimate file.
+  /// tokens covered by the expansion in the ultimate file.
   std::pair<SourceLocation,SourceLocation>
   getExpansionRange(SourceLocation Loc) const;
 
+  /// \brief Given a SourceRange object, return the range of
+  /// tokens covered by the expansion in the ultimate file.
+  SourceRange getExpansionRange(SourceRange Range) const {
+    return SourceRange(getExpansionRange(Range.getBegin()).first,
+                       getExpansionRange(Range.getEnd()).second);
+  }
 
   /// \brief Given a SourceLocation object, return the spelling
   /// location referenced by the ID.
diff --git a/include/clang/Basic/Specifiers.h b/include/clang/Basic/Specifiers.h
index a968d00..7569c16 100644
--- a/include/clang/Basic/Specifiers.h
+++ b/include/clang/Basic/Specifiers.h
@@ -209,8 +209,9 @@
     CC_X86_64SysV,  // __attribute__((sysv_abi))
     CC_AAPCS,       // __attribute__((pcs("aapcs")))
     CC_AAPCS_VFP,   // __attribute__((pcs("aapcs-vfp")))
-    CC_PnaclCall,   // __attribute__((pnaclcall))
-    CC_IntelOclBicc // __attribute__((intel_ocl_bicc))
+    CC_IntelOclBicc, // __attribute__((intel_ocl_bicc))
+    CC_SpirFunction, // default for OpenCL functions on SPIR target
+    CC_SpirKernel    // inferred for OpenCL kernels on SPIR target
   };
 
   /// \brief Checks whether the given calling convention supports variadic
@@ -222,6 +223,8 @@
     case CC_X86ThisCall:
     case CC_X86Pascal:
     case CC_X86VectorCall:
+    case CC_SpirFunction:
+    case CC_SpirKernel:
       return false;
     default:
       return true;
diff --git a/include/clang/Basic/TargetCXXABI.h b/include/clang/Basic/TargetCXXABI.h
index 5669d2a..42a976b 100644
--- a/include/clang/Basic/TargetCXXABI.h
+++ b/include/clang/Basic/TargetCXXABI.h
@@ -79,6 +79,12 @@
     ///   - guard variables  are smaller.
     GenericAArch64,
 
+    /// The generic Mips ABI is a modified version of the Itanium ABI.
+    ///
+    /// At the moment, only change from the generic ABI in this case is:
+    ///   - representation of member function pointers adjusted as in ARM.
+    GenericMIPS,
+
     /// The Microsoft ABI is the ABI used by Microsoft Visual Studio (and
     /// compatible compilers).
     ///
@@ -114,6 +120,7 @@
     case GenericARM:
     case iOS:
     case iOS64:
+    case GenericMIPS:
       return true;
 
     case Microsoft:
@@ -130,6 +137,7 @@
     case GenericARM:
     case iOS:
     case iOS64:
+    case GenericMIPS:
       return false;
 
     case Microsoft:
@@ -212,6 +220,7 @@
     case GenericItanium:
     case iOS:   // old iOS compilers did not follow this rule
     case Microsoft:
+    case GenericMIPS:
       return true;
     }
     llvm_unreachable("bad ABI kind");
@@ -257,6 +266,7 @@
     case GenericAArch64:
     case GenericARM:
     case iOS:
+    case GenericMIPS:
       return UseTailPaddingUnlessPOD03;
 
     // iOS on ARM64 uses the C++11 POD rules.  It does not honor the
diff --git a/include/clang/Basic/TargetInfo.h b/include/clang/Basic/TargetInfo.h
index 8c2b89c..bda132e 100644
--- a/include/clang/Basic/TargetInfo.h
+++ b/include/clang/Basic/TargetInfo.h
@@ -370,6 +370,15 @@
   /// \brief Return the maximum width lock-free atomic operation which can be
   /// inlined given the supported features of the given target.
   unsigned getMaxAtomicInlineWidth() const { return MaxAtomicInlineWidth; }
+  /// \brief Returns true if the given target supports lock-free atomic
+  /// operations at the specified width and alignment.
+  virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits,
+                                uint64_t AlignmentInBits) const {
+    return AtomicSizeInBits <= AlignmentInBits &&
+           AtomicSizeInBits <= getMaxAtomicInlineWidth() &&
+           (AtomicSizeInBits <= getCharWidth() ||
+            llvm::isPowerOf2_64(AtomicSizeInBits / getCharWidth()));
+  }
 
   /// \brief Return the maximum vector alignment supported for the given target.
   unsigned getMaxVectorAlign() const { return MaxVectorAlign; }
@@ -519,22 +528,31 @@
       CI_None = 0x00,
       CI_AllowsMemory = 0x01,
       CI_AllowsRegister = 0x02,
-      CI_ReadWrite = 0x04,       // "+r" output constraint (read and write).
-      CI_HasMatchingInput = 0x08 // This output operand has a matching input.
+      CI_ReadWrite = 0x04,         // "+r" output constraint (read and write).
+      CI_HasMatchingInput = 0x08,  // This output operand has a matching input.
+      CI_ImmediateConstant = 0x10, // This operand must be an immediate constant
+      CI_EarlyClobber = 0x20,      // "&" output constraint (early clobber).
     };
     unsigned Flags;
     int TiedOperand;
+    struct {
+      int Min;
+      int Max;
+    } ImmRange;
 
     std::string ConstraintStr;  // constraint: "=rm"
     std::string Name;           // Operand name: [foo] with no []'s.
   public:
     ConstraintInfo(StringRef ConstraintStr, StringRef Name)
-      : Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
-      Name(Name.str()) {}
+        : Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
+          Name(Name.str()) {
+      ImmRange.Min = ImmRange.Max = 0;
+    }
 
     const std::string &getConstraintStr() const { return ConstraintStr; }
     const std::string &getName() const { return Name; }
     bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; }
+    bool earlyClobber() { return (Flags & CI_EarlyClobber) != 0; }
     bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; }
     bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; }
 
@@ -553,10 +571,22 @@
       return (unsigned)TiedOperand;
     }
 
+    bool requiresImmediateConstant() const {
+      return (Flags & CI_ImmediateConstant) != 0;
+    }
+    int getImmConstantMin() const { return ImmRange.Min; }
+    int getImmConstantMax() const { return ImmRange.Max; }
+
     void setIsReadWrite() { Flags |= CI_ReadWrite; }
+    void setEarlyClobber() { Flags |= CI_EarlyClobber; }
     void setAllowsMemory() { Flags |= CI_AllowsMemory; }
     void setAllowsRegister() { Flags |= CI_AllowsRegister; }
     void setHasMatchingInput() { Flags |= CI_HasMatchingInput; }
+    void setRequiresImmediate(int Min, int Max) {
+      Flags |= CI_ImmediateConstant;
+      ImmRange.Min = Min;
+      ImmRange.Max = Max;
+    }
 
     /// \brief Indicate that this is an input operand that is tied to
     /// the specified output operand. 
@@ -608,6 +638,12 @@
     return std::string(1, *Constraint);
   }
 
+  /// \brief Returns true if NaN encoding is IEEE 754-2008.
+  /// Only MIPS allows a different encoding.
+  virtual bool isNan2008() const {
+    return true;
+  }
+
   /// \brief Returns a string of target-specific clobbers, in LLVM format.
   virtual const char *getClobbers() const = 0;
 
@@ -806,7 +842,8 @@
 
   enum CallingConvCheckResult {
     CCCR_OK,
-    CCCR_Warning
+    CCCR_Warning,
+    CCCR_Ignore,
   };
 
   /// \brief Determines whether a given calling convention is valid for the
diff --git a/include/clang/Basic/TokenKinds.def b/include/clang/Basic/TokenKinds.def
index c63dea0..3319d4e 100644
--- a/include/clang/Basic/TokenKinds.def
+++ b/include/clang/Basic/TokenKinds.def
@@ -116,8 +116,6 @@
 TOK(eod)                 // End of preprocessing directive (end of line inside a
                          // directive).
 TOK(code_completion)     // Code completion marker
-TOK(cxx_defaultarg_end)  // C++ default argument end marker
-TOK(cxx_exceptspec_end)  // C++ exception-specification end marker
 
 // C99 6.4.9: Comments.
 TOK(comment)             // Comment (only in -E -C[C] mode)
@@ -471,10 +469,12 @@
 KEYWORD(__local                     , KEYOPENCL)
 KEYWORD(__constant                  , KEYOPENCL)
 KEYWORD(__private                   , KEYOPENCL)
+KEYWORD(__generic                   , KEYOPENCL)
 ALIAS("global", __global            , KEYOPENCL)
 ALIAS("local", __local              , KEYOPENCL)
 ALIAS("constant", __constant        , KEYOPENCL)
 ALIAS("private", __private          , KEYOPENCL)
+ALIAS("generic", __generic          , KEYOPENCL)
 // OpenCL function qualifiers
 KEYWORD(__kernel                    , KEYOPENCL)
 ALIAS("kernel", __kernel            , KEYOPENCL)
@@ -495,6 +495,7 @@
 // Altivec Extension.
 KEYWORD(__vector                    , KEYALTIVEC)
 KEYWORD(__pixel                     , KEYALTIVEC)
+KEYWORD(__bool                      , KEYALTIVEC)
 
 // ARM NEON extensions.
 ALIAS("__fp16", half                , KEYALL)
diff --git a/include/clang/Basic/VirtualFileSystem.h b/include/clang/Basic/VirtualFileSystem.h
index 7086596..1c65fb5 100644
--- a/include/clang/Basic/VirtualFileSystem.h
+++ b/include/clang/Basic/VirtualFileSystem.h
@@ -18,8 +18,8 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/raw_ostream.h"
 
 namespace llvm {
 class MemoryBuffer;
diff --git a/include/clang/CodeGen/CGFunctionInfo.h b/include/clang/CodeGen/CGFunctionInfo.h
index 8aea6c3..e32fb14 100644
--- a/include/clang/CodeGen/CGFunctionInfo.h
+++ b/include/clang/CodeGen/CGFunctionInfo.h
@@ -63,10 +63,10 @@
     Expand,
 
     /// InAlloca - Pass the argument directly using the LLVM inalloca attribute.
-    /// This is similar to 'direct', except it only applies to arguments stored
-    /// in memory and forbids any implicit copies.  When applied to a return
-    /// type, it means the value is returned indirectly via an implicit sret
-    /// parameter stored in the argument struct.
+    /// This is similar to indirect with byval, except it only applies to
+    /// arguments stored in memory and forbids any implicit copies.  When
+    /// applied to a return type, it means the value is returned indirectly via
+    /// an implicit sret parameter stored in the argument struct.
     InAlloca,
     KindFirst = Direct,
     KindLast = InAlloca
@@ -352,6 +352,9 @@
   /// Whether this is an instance method.
   unsigned InstanceMethod : 1;
 
+  /// Whether this is a chain call.
+  unsigned ChainCall : 1;
+
   /// Whether this function is noreturn.
   unsigned NoReturn : 1;
 
@@ -360,7 +363,7 @@
 
   /// How many arguments to pass inreg.
   unsigned HasRegParm : 1;
-  unsigned RegParm : 4;
+  unsigned RegParm : 3;
 
   RequiredArgs Required;
 
@@ -380,7 +383,8 @@
 
 public:
   static CGFunctionInfo *create(unsigned llvmCC,
-                                bool InstanceMethod,
+                                bool instanceMethod,
+                                bool chainCall,
                                 const FunctionType::ExtInfo &extInfo,
                                 CanQualType resultType,
                                 ArrayRef<CanQualType> argTypes,
@@ -412,6 +416,8 @@
 
   bool isInstanceMethod() const { return InstanceMethod; }
 
+  bool isChainCall() const { return ChainCall; }
+
   bool isNoReturn() const { return NoReturn; }
 
   /// In ARC, whether this function retains its return value.  This
@@ -462,6 +468,7 @@
   void Profile(llvm::FoldingSetNodeID &ID) {
     ID.AddInteger(getASTCallingConvention());
     ID.AddBoolean(InstanceMethod);
+    ID.AddBoolean(ChainCall);
     ID.AddBoolean(NoReturn);
     ID.AddBoolean(ReturnsRetained);
     ID.AddBoolean(HasRegParm);
@@ -473,12 +480,14 @@
   }
   static void Profile(llvm::FoldingSetNodeID &ID,
                       bool InstanceMethod,
+                      bool ChainCall,
                       const FunctionType::ExtInfo &info,
                       RequiredArgs required,
                       CanQualType resultType,
                       ArrayRef<CanQualType> argTypes) {
     ID.AddInteger(info.getCC());
     ID.AddBoolean(InstanceMethod);
+    ID.AddBoolean(ChainCall);
     ID.AddBoolean(info.getNoReturn());
     ID.AddBoolean(info.getProducesResult());
     ID.AddBoolean(info.getHasRegParm());
diff --git a/include/clang/CodeGen/ModuleBuilder.h b/include/clang/CodeGen/ModuleBuilder.h
index f4c3107..8facc3c 100644
--- a/include/clang/CodeGen/ModuleBuilder.h
+++ b/include/clang/CodeGen/ModuleBuilder.h
@@ -27,7 +27,6 @@
   class CoverageSourceInfo;
   class LangOptions;
   class CodeGenOptions;
-  class TargetOptions;
   class Decl;
 
   class CodeGenerator : public ASTConsumer {
@@ -44,7 +43,6 @@
   CodeGenerator *CreateLLVMCodeGen(DiagnosticsEngine &Diags,
                                    const std::string &ModuleName,
                                    const CodeGenOptions &CGO,
-                                   const TargetOptions &TO,
                                    llvm::LLVMContext& C,
                                    CoverageSourceInfo *CoverageInfo = nullptr);
 }
diff --git a/include/clang/Config/config.h b/include/clang/Config/config.h
index e106019..8e6047a 100644
--- a/include/clang/Config/config.h
+++ b/include/clang/Config/config.h
@@ -7,15 +7,15 @@
 /* Bug report URL. */
 #define BUG_REPORT_URL "http://llvm.org/bugs/"
 
+/* Multilib suffix for libdir. */
+#define CLANG_LIBDIR_SUFFIX ""
+
 /* Relative directory for resource files */
 #define CLANG_RESOURCE_DIR ""
 
 /* Directories clang will search for headers */
 #define C_INCLUDE_DIRS ""
 
-/* Linker version detected at compile time. */
-#define HOST_LINK_VERSION "2.22"
-
 /* Default <path> to all compiler invocations for --sysroot=<path>. */
 #define DEFAULT_SYSROOT ""
 
@@ -30,4 +30,7 @@
 /* The LLVM product name and version */
 #define BACKEND_PACKAGE_STRING PACKAGE_STRING
 
+/* Linker version detected at compile time. */
+#define HOST_LINK_VERSION "2.24"
+
 #endif
diff --git a/include/clang/Config/config.h.cmake b/include/clang/Config/config.h.cmake
index 38b398c..5d89b1a 100644
--- a/include/clang/Config/config.h.cmake
+++ b/include/clang/Config/config.h.cmake
@@ -8,6 +8,9 @@
 /* Bug report URL. */
 #define BUG_REPORT_URL "${BUG_REPORT_URL}"
 
+/* Multilib suffix for libdir. */
+#define CLANG_LIBDIR_SUFFIX "${CLANG_LIBDIR_SUFFIX}"
+
 /* Relative directory for resource files */
 #define CLANG_RESOURCE_DIR "${CLANG_RESOURCE_DIR}"
 
diff --git a/include/clang/Config/config.h.in b/include/clang/Config/config.h.in
index 3c2cb07..dba05db 100644
--- a/include/clang/Config/config.h.in
+++ b/include/clang/Config/config.h.in
@@ -8,6 +8,9 @@
 /* Bug report URL. */
 #undef BUG_REPORT_URL
 
+/* Multilib suffix for libdir. */
+#undef CLANG_LIBDIR_SUFFIX
+
 /* Relative directory for resource files */
 #undef CLANG_RESOURCE_DIR
 
diff --git a/include/clang/Driver/Action.h b/include/clang/Driver/Action.h
index 2739d49..dd0261c 100644
--- a/include/clang/Driver/Action.h
+++ b/include/clang/Driver/Action.h
@@ -46,6 +46,7 @@
     AnalyzeJobClass,
     MigrateJobClass,
     CompileJobClass,
+    BackendJobClass,
     AssembleJobClass,
     LinkJobClass,
     LipoJobClass,
@@ -195,6 +196,16 @@
   }
 };
 
+class BackendJobAction : public JobAction {
+  void anchor() override;
+public:
+  BackendJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
+
+  static bool classof(const Action *A) {
+    return A->getKind() == BackendJobClass;
+  }
+};
+
 class AssembleJobAction : public JobAction {
   void anchor() override;
 public:
diff --git a/include/clang/Driver/CC1Options.td b/include/clang/Driver/CC1Options.td
index fbab14b..f60fb4e 100644
--- a/include/clang/Driver/CC1Options.td
+++ b/include/clang/Driver/CC1Options.td
@@ -279,6 +279,8 @@
   HelpText<"Set the maximum number of entries to print in a template instantiation backtrace (0 = no limit).">;
 def fconstexpr_backtrace_limit : Separate<["-"], "fconstexpr-backtrace-limit">, MetaVarName<"<N>">,
   HelpText<"Set the maximum number of entries to print in a constexpr evaluation backtrace (0 = no limit).">;
+def fspell_checking_limit : Separate<["-"], "fspell-checking-limit">, MetaVarName<"<N>">,
+  HelpText<"Set the maximum number of times to perform spell checking on unrecognized identifiers (0 = no limit).">;
 def fmessage_length : Separate<["-"], "fmessage-length">, MetaVarName<"<N>">,
   HelpText<"Format message diagnostics so that they fit within N columns or fewer, when possible.">;
 def verify : Flag<["-"], "verify">,
@@ -337,6 +339,12 @@
 def fmodule_implementation_of : Separate<["-"], "fmodule-implementation-of">,
   MetaVarName<"<name>">,
   HelpText<"Specify the name of the module whose implementation file this is">;
+def fmodule_map_file_home_is_cwd : Flag<["-"], "fmodule-map-file-home-is-cwd">,
+  HelpText<"Use the current working directory as the home directory of "
+           "module maps specified by -fmodule-map-file=<FILE>">;
+def fmodule_feature : Separate<["-"], "fmodule-feature">,
+  MetaVarName<"<feature>">,
+  HelpText<"Enable <feature> in module map requires declarations">;
 
 let Group = Action_Group in {
 
@@ -510,6 +518,10 @@
   HelpText<"Undefines the __DEPRECATED macro">;
 def fsized_deallocation : Flag<["-"], "fsized-deallocation">,
   HelpText<"Enable C++14 sized global deallocation functions">;
+def fno_sized_deallocation: Flag<["-"], "fno-sized-deallocation">,
+  HelpText<"Disable sized deallocation functions">;
+def fdefine_sized_deallocation: Flag<["-"], "fdefine-sized-deallocation">,
+  HelpText<"Allow compiler-generated definition of sized deallocation functions">;
 def fobjc_subscripting_legacy_runtime : Flag<["-"], "fobjc-subscripting-legacy-runtime">,
   HelpText<"Allow Objective-C array and dictionary subscripting in legacy runtime">;
 def vtordisp_mode_EQ : Joined<["-"], "vtordisp-mode=">,
@@ -569,12 +581,16 @@
 
 def cl_opt_disable : Flag<["-"], "cl-opt-disable">,
   HelpText<"OpenCL only. This option disables all optimizations. The default is optimizations are enabled.">;
+def cl_strict_aliasing : Flag<["-"], "cl-strict-aliasing">,
+  HelpText<"OpenCL only. This option does nothing and is for compatibility with OpenCL 1.0">;
 def cl_single_precision_constant : Flag<["-"], "cl-single-precision-constant">,
   HelpText<"OpenCL only. Treat double precision floating-point constant as single precision constant.">;
 def cl_finite_math_only : Flag<["-"], "cl-finite-math-only">,
   HelpText<"OpenCL only. Allow floating-point optimizations that assume arguments and results are not NaNs or +-Inf.">;
 def cl_kernel_arg_info : Flag<["-"], "cl-kernel-arg-info">,
   HelpText<"OpenCL only. Generate kernel argument metadata.">;
+def : Flag<["-"], "cl-no-signed-zeros">, Alias<fno_signed_zeros>,
+  HelpText<"OpenCL only. Allow optimizations to ignore the signedness of the floating-point zero.">;
 def cl_unsafe_math_optimizations : Flag<["-"], "cl-unsafe-math-optimizations">,
   HelpText<"OpenCL only. Allow unsafe floating-point optimizations.  Also implies -cl-no-signed-zeros and -cl-mad-enable">;
 def cl_fast_relaxed_math : Flag<["-"], "cl-fast-relaxed-math">,
@@ -592,6 +608,9 @@
 
 def fcuda_is_device : Flag<["-"], "fcuda-is-device">,
   HelpText<"Generate code for CUDA device">;
+def fcuda_allow_host_calls_from_host_device : Flag<["-"],
+    "fcuda-allow-host-calls-from-host-device">,
+  HelpText<"Allow host device functions to call host functions">;
 
 } // let Flags = [CC1Option]
 
diff --git a/include/clang/Driver/CLCompatOptions.td b/include/clang/Driver/CLCompatOptions.td
index e05d687..80630fc 100644
--- a/include/clang/Driver/CLCompatOptions.td
+++ b/include/clang/Driver/CLCompatOptions.td
@@ -62,6 +62,8 @@
 def _SLASH_GR_ : CLFlag<"GR-">, HelpText<"Disable emission of RTTI data">;
 def _SLASH_GF_ : CLFlag<"GF-">, HelpText<"Disable string pooling">,
   Alias<fwritable_strings>;
+def _SLASH_Gs : CLJoined<"Gs">, HelpText<"Set stack probe size">,
+  Alias<mstack_probe_size>;
 def _SLASH_Gy : CLFlag<"Gy">, HelpText<"Put each function in its own section">,
   Alias<ffunction_sections>;
 def _SLASH_Gy_ : CLFlag<"Gy-">, HelpText<"Don't put each function in its own section">,
@@ -78,6 +80,7 @@
   Alias<I>;
 def _SLASH_J : CLFlag<"J">, HelpText<"Make char type unsigned">,
   Alias<funsigned_char>;
+def _SLASH_O0 : CLFlag<"O0">, Alias<O0>;
 def _SLASH_O : CLJoined<"O">, HelpText<"Optimization level">,
   MetaVarName<"<n>">, Alias<O>;
 def _SLASH_Ob0 : CLFlag<"Ob0">, HelpText<"Disable inlining">,
@@ -127,8 +130,17 @@
 def _SLASH_w_flag : CLFlag<"w">, HelpText<"Disable all warnings">, Alias<w>;
 def _SLASH_wd4005 : CLFlag<"wd4005">, Alias<W_Joined>,
   AliasArgs<["no-macro-redefined"]>;
+def _SLASH_wd4996 : CLFlag<"wd4996">, Alias<W_Joined>,
+  AliasArgs<["no-deprecated-declarations"]>;
 def _SLASH_vd : CLJoined<"vd">, HelpText<"Control vtordisp placement">,
   Alias<vtordisp_mode_EQ>;
+def _SLASH_Zc_strictStrings : CLFlag<"Zc:strictStrings">,
+  HelpText<"Treat string literals as const">, Alias<W_Joined>,
+  AliasArgs<["error=c++11-compat-deprecated-writable-strings"]>;
+def _SLASH_Zc_trigraphs : CLFlag<"Zc:trigraphs">,
+  HelpText<"Enable trigraphs">, Alias<ftrigraphs>;
+def _SLASH_Zc_trigraphs_off : CLFlag<"Zc:trigraphs-">,
+  HelpText<"Disable trigraphs (default)">, Alias<fno_trigraphs>;
 def _SLASH_Z7 : CLFlag<"Z7">, Alias<gline_tables_only>;
 def _SLASH_Zi : CLFlag<"Zi">, HelpText<"Enable debug information">,
   Alias<gline_tables_only>;
@@ -148,6 +160,7 @@
   HelpText<"Set architecture for code generation">;
 
 def _SLASH_M_Group : OptionGroup<"</M group>">, Group<cl_compile_Group>;
+def _SLASH_volatile_Group : OptionGroup<"</volatile group>">, Group<cl_compile_Group>;
 
 def _SLASH_EH : CLJoined<"EH">, HelpText<"Exception handling model">;
 def _SLASH_EP : CLFlag<"EP">,
@@ -192,14 +205,20 @@
 def _SLASH_Tp : CLCompileJoinedOrSeparate<"Tp">,
   HelpText<"Specify a C++ source file">, MetaVarName<"<filename>">;
 def _SLASH_TP : CLCompileFlag<"TP">, HelpText<"Treat all source files as C++">;
-
+def _SLASH_volatile_iso : Option<["/", "-"], "volatile:iso", KIND_FLAG>, Group<_SLASH_volatile_Group>,
+  Flags<[CLOption, DriverOption]>, HelpText<"Volatile loads and stores have standard semantics">;
+def _SLASH_volatile_ms  : Option<["/", "-"], "volatile:ms", KIND_FLAG>, Group<_SLASH_volatile_Group>,
+  Flags<[CLOption, DriverOption]>, HelpText<"Volatile loads and stores have acquire and release semantics">;
 
 // Ignored:
 
 def _SLASH_analyze_ : CLIgnoredFlag<"analyze-">;
+def _SLASH_cgthreads : CLIgnoredJoined<"cgthreads">;
 def _SLASH_d2Zi_PLUS : CLIgnoredFlag<"d2Zi+">;
 def _SLASH_errorReport : CLIgnoredJoined<"errorReport">;
+def _SLASH_Fd : CLIgnoredJoined<"Fd">;
 def _SLASH_FS : CLIgnoredFlag<"FS">, HelpText<"Force synchronous PDB writes">;
+def _SLASH_Gd : CLIgnoredFlag<"Gd">;
 def _SLASH_GF : CLIgnoredFlag<"GF">;
 def _SLASH_GS_ : CLIgnoredFlag<"GS-">;
 def _SLASH_kernel_ : CLIgnoredFlag<"kernel-">;
@@ -210,6 +229,7 @@
 def _SLASH_sdl : CLIgnoredFlag<"sdl">;
 def _SLASH_sdl_ : CLIgnoredFlag<"sdl-">;
 def _SLASH_w : CLIgnoredJoined<"w">;
+def _SLASH_Zc_auto : CLIgnoredFlag<"Zc:auto">;
 def _SLASH_Zc_forScope : CLIgnoredFlag<"Zc:forScope">;
 def _SLASH_Zc_inline : CLIgnoredFlag<"Zc:inline">;
 def _SLASH_Zc_rvalueCast : CLIgnoredFlag<"Zc:rvalueCast">;
@@ -229,7 +249,6 @@
 def _SLASH_favor : CLJoined<"favor">;
 def _SLASH_FC : CLFlag<"FC">;
 def _SLASH_F : CLFlag<"F">;
-def _SLASH_Fd : CLJoined<"Fd">;
 def _SLASH_Fm : CLJoined<"Fm">;
 def _SLASH_fp : CLJoined<"fp">;
 def _SLASH_Fp : CLJoined<"Fp">;
@@ -240,7 +259,6 @@
 def _SLASH_G1 : CLFlag<"G1">;
 def _SLASH_G2 : CLFlag<"G2">;
 def _SLASH_GA : CLFlag<"GA">;
-def _SLASH_Gd : CLFlag<"Gd">;
 def _SLASH_Ge : CLFlag<"Ge">;
 def _SLASH_Gh : CLFlag<"Gh">;
 def _SLASH_GH : CLFlag<"GH">;
@@ -250,9 +268,9 @@
 def _SLASH_Gm_ : CLFlag<"Gm-">;
 def _SLASH_Gr : CLFlag<"Gr">;
 def _SLASH_GS : CLFlag<"GS">;
-def _SLASH_Gs : CLJoined<"Gs">;
 def _SLASH_GT : CLFlag<"GT">;
 def _SLASH_GX : CLFlag<"GX">;
+def _SLASH_Gv : CLFlag<"Gv">;
 def _SLASH_Gz : CLFlag<"Gz">;
 def _SLASH_GZ : CLFlag<"GZ">;
 def _SLASH_H : CLFlag<"H">;
@@ -269,7 +287,6 @@
 def _SLASH_Qvec_report : CLJoined<"Qvec-report">;
 def _SLASH_u : CLFlag<"u">;
 def _SLASH_V : CLFlag<"V">;
-def _SLASH_volatile : CLFlag<"volatile">;
 def _SLASH_WL : CLFlag<"WL">;
 def _SLASH_Wp64 : CLFlag<"Wp64">;
 def _SLASH_X : CLFlag<"X">;
diff --git a/include/clang/Driver/Driver.h b/include/clang/Driver/Driver.h
index 020966f..09521c2 100644
--- a/include/clang/Driver/Driver.h
+++ b/include/clang/Driver/Driver.h
@@ -61,6 +61,12 @@
     CLMode
   } Mode;
 
+  enum SaveTempsMode {
+    SaveTempsNone,
+    SaveTempsCwd,
+    SaveTempsObj
+  } SaveTemps;
+
 public:
   // Diag - Forwarding function for diagnostics.
   DiagnosticBuilder Diag(unsigned DiagID) const {
@@ -104,9 +110,6 @@
   /// Default target triple.
   std::string DefaultTargetTriple;
 
-  /// Default name for linked images (e.g., "a.out").
-  std::string DefaultImageName;
-
   /// Driver title to use with help.
   std::string DriverTitle;
 
@@ -235,6 +238,9 @@
     InstalledDir = Value;
   }
 
+  bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
+  bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
+
   /// @}
   /// @name Primary Functionality
   /// @{
@@ -351,8 +357,8 @@
   /// \p Phase on the \p Input, taking in to account arguments
   /// like -fsyntax-only or --analyze.
   std::unique_ptr<Action>
-  ConstructPhaseAction(const llvm::opt::ArgList &Args, phases::ID Phase,
-                       std::unique_ptr<Action> Input) const;
+  ConstructPhaseAction(const ToolChain &TC, const llvm::opt::ArgList &Args,
+                       phases::ID Phase, std::unique_ptr<Action> Input) const;
 
   /// BuildJobsForAction - Construct the jobs to perform for the
   /// action \p A.
@@ -365,6 +371,9 @@
                           const char *LinkingOutput,
                           InputInfo &Result) const;
 
+  /// Returns the default name for linked images (e.g., "a.out").
+  const char *getDefaultImageName() const;
+
   /// GetNamedOutputPath - Return the name to use for the output of
   /// the action \p JA. The result is appended to the compilation's
   /// list of temporary or result files, as appropriate.
@@ -393,7 +402,7 @@
   /// handle this action.
   bool ShouldUseClangCompiler(const JobAction &JA) const;
 
-  bool IsUsingLTO(const llvm::opt::ArgList &Args) const;
+  bool IsUsingLTO(const ToolChain &TC, const llvm::opt::ArgList &Args) const;
 
 private:
   /// \brief Retrieves a ToolChain for a particular target triple.
diff --git a/include/clang/Driver/Job.h b/include/clang/Driver/Job.h
index 685088d..b510676 100644
--- a/include/clang/Driver/Job.h
+++ b/include/clang/Driver/Job.h
@@ -12,8 +12,8 @@
 
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/Option/Option.h"
 #include "llvm/ADT/iterator.h"
+#include "llvm/Option/Option.h"
 #include <memory>
 
 namespace llvm {
diff --git a/include/clang/Driver/Multilib.h b/include/clang/Driver/Multilib.h
index 501ffe5..dcf609a 100644
--- a/include/clang/Driver/Multilib.h
+++ b/include/clang/Driver/Multilib.h
@@ -13,7 +13,6 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Option/Option.h"
-
 #include <functional>
 #include <string>
 #include <vector>
diff --git a/include/clang/Driver/Options.td b/include/clang/Driver/Options.td
index b42d348..6b7a47c 100644
--- a/include/clang/Driver/Options.td
+++ b/include/clang/Driver/Options.td
@@ -404,6 +404,11 @@
   Flags<[DriverOption, CC1Option]>,
   HelpText<"Disable generation of linker directives for automatic library linking">;
 
+def fgnu_inline_asm : Flag<["-"], "fgnu-inline-asm">, Group<f_Group>, Flags<[DriverOption]>;
+def fno_gnu_inline_asm : Flag<["-"], "fno-gnu-inline-asm">, Group<f_Group>,
+  Flags<[DriverOption, CC1Option]>,
+  HelpText<"Disable GNU style inline asm">;
+
 def fprofile_sample_use_EQ : Joined<["-"], "fprofile-sample-use=">,
     Group<f_Group>, Flags<[DriverOption, CC1Option]>,
     HelpText<"Enable sample-based profile guided optimizations">;
@@ -428,12 +433,12 @@
 def fbuiltin : Flag<["-"], "fbuiltin">, Group<f_Group>;
 def fcaret_diagnostics : Flag<["-"], "fcaret-diagnostics">, Group<f_Group>;
 def fclasspath_EQ : Joined<["-"], "fclasspath=">, Group<f_Group>;
-def fcolor_diagnostics : Flag<["-"], "fcolor-diagnostics">, Group<f_Group>, Flags<[CC1Option]>,
-  HelpText<"Use colors in diagnostics">;
+def fcolor_diagnostics : Flag<["-"], "fcolor-diagnostics">, Group<f_Group>,
+  Flags<[CoreOption, CC1Option]>, HelpText<"Use colors in diagnostics">;
 def fdiagnostics_color : Flag<["-"], "fdiagnostics-color">, Group<f_Group>;
 def fdiagnostics_color_EQ : Joined<["-"], "fdiagnostics-color=">, Group<f_Group>;
-def fansi_escape_codes : Flag<["-"], "fansi-escape-codes">, Group<f_Group>, Flags<[CC1Option]>,
-  HelpText<"Use ANSI escape codes for diagnostics">;
+def fansi_escape_codes : Flag<["-"], "fansi-escape-codes">, Group<f_Group>,
+  Flags<[CoreOption, CC1Option]>, HelpText<"Use ANSI escape codes for diagnostics">;
 def fcomment_block_commands : CommaJoined<["-"], "fcomment-block-commands=">, Group<f_clang_Group>, Flags<[CC1Option]>,
   HelpText<"Treat each comma separated argument in <arg> as a documentation comment block command">,
   MetaVarName<"<arg>">;
@@ -509,9 +514,8 @@
 def fno_signaling_math : Flag<["-"], "fno-signaling-math">, Group<f_Group>;
 def fsanitize_EQ : CommaJoined<["-"], "fsanitize=">, Group<f_clang_Group>,
                    Flags<[CC1Option, CoreOption]>, MetaVarName<"<check>">,
-                   HelpText<"Enable runtime instrumentation for bug detection: "
-                            "address (memory errors) | thread (race detection) | "
-                            "undefined (miscellaneous undefined behavior)">;
+                   HelpText<"Turn on runtime checks for various forms of undefined "
+                            "or suspicious behavior. See user manual for available checks ">;
 def fno_sanitize_EQ : CommaJoined<["-"], "fno-sanitize=">, Group<f_clang_Group>;
 def fsanitize_blacklist : Joined<["-"], "fsanitize-blacklist=">,
                           Group<f_clang_Group>, Flags<[CC1Option, CoreOption]>,
@@ -534,11 +538,17 @@
 def fsanitize_address_field_padding : Joined<["-"], "fsanitize-address-field-padding=">,
                                         Group<f_clang_Group>, Flags<[CC1Option]>,
                                         HelpText<"Level of field padding for AddressSanitizer">;
-def fsanitize_recover : Flag<["-"], "fsanitize-recover">,
-                        Group<f_clang_Group>;
+def fsanitize_recover : Flag<["-"], "fsanitize-recover">, Group<f_clang_Group>;
 def fno_sanitize_recover : Flag<["-"], "fno-sanitize-recover">,
-                           Group<f_clang_Group>, Flags<[CC1Option]>,
-                           HelpText<"Disable sanitizer check recovery">;
+                           Group<f_clang_Group>;
+def fsanitize_recover_EQ : CommaJoined<["-"], "fsanitize-recover=">,
+                           Group<f_clang_Group>,
+                           Flags<[CC1Option]>,
+                           HelpText<"Enable recovery for specified sanitizers">;
+def fno_sanitize_recover_EQ
+    : CommaJoined<["-"], "fno-sanitize-recover=">,
+      Group<f_clang_Group>,
+      HelpText<"Disable recovery for specified sanitizers">;
 def fsanitize_undefined_trap_on_error : Flag<["-"], "fsanitize-undefined-trap-on-error">,
                                         Group<f_clang_Group>, Flags<[CC1Option]>;
 def fno_sanitize_undefined_trap_on_error : Flag<["-"], "fno-sanitize-undefined-trap-on-error">,
@@ -556,7 +566,9 @@
 def ffinite_math_only : Flag<["-"], "ffinite-math-only">, Group<f_Group>, Flags<[CC1Option]>;
 def fno_finite_math_only : Flag<["-"], "fno-finite-math-only">, Group<f_Group>;
 def fsigned_zeros : Flag<["-"], "fsigned-zeros">, Group<f_Group>;
-def fno_signed_zeros : Flag<["-"], "fno-signed-zeros">, Group<f_Group>;
+def fno_signed_zeros :
+  Flag<["-"], "fno-signed-zeros">, Group<f_Group>, Flags<[CC1Option]>,
+  HelpText<"Allow optimizations that ignore the sign of floating point zeros">;
 def fhonor_nans : Flag<["-"], "fhonor-nans">, Group<f_Group>;
 def fno_honor_nans : Flag<["-"], "fno-honor-nans">, Group<f_Group>;
 def fhonor_infinities : Flag<["-"], "fhonor-infinities">, Group<f_Group>;
@@ -577,6 +589,17 @@
   Flags<[CC1Option]>;
 def fno_rewrite_includes : Flag<["-"], "fno-rewrite-includes">, Group<f_Group>;
 
+def frewrite_map_file : Separate<["-"], "frewrite-map-file">,
+                        Group<f_Group>,
+                        Flags<[ DriverOption, CC1Option ]>;
+def frewrite_map_file_EQ : Joined<["-"], "frewrite-map-file=">,
+                           Group<f_Group>,
+                           Flags<[DriverOption]>;
+
+def fuse_line_directives : Flag<["-"], "fuse-line-directives">, Group<f_Group>,
+  Flags<[CC1Option]>;
+def fno_use_line_directives : Flag<["-"], "fno-use-line-directives">, Group<f_Group>;
+
 def ffreestanding : Flag<["-"], "ffreestanding">, Group<f_Group>, Flags<[CC1Option]>,
   HelpText<"Assert that the compilation takes place in a freestanding environment">;
 def fgnu_keywords : Flag<["-"], "fgnu-keywords">, Group<f_Group>, Flags<[CC1Option]>,
@@ -609,6 +632,7 @@
   HelpText<"Accept some non-standard constructs supported by the Microsoft compiler">;
 def fms_compatibility : Flag<["-"], "fms-compatibility">, Group<f_Group>, Flags<[CC1Option]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">;
+def fms_volatile : Joined<["-"], "fms-volatile">, Group<f_Group>, Flags<[CC1Option]>;
 def fmsc_version : Joined<["-"], "fmsc-version=">, Group<f_Group>, Flags<[DriverOption, CoreOption]>,
   HelpText<"Microsoft compiler version number to report in _MSC_VER (0 = don't define it (default))">;
 def fms_compatibility_version
@@ -675,6 +699,15 @@
   HelpText<"Like -fmodules-decluse but requires all headers to be in modules">;
 def fno_modules_search_all : Flag <["-"], "fno-modules-search-all">, Group<f_Group>,
   Flags<[DriverOption, CC1Option]>;
+def fmodules_implicit_maps :
+  Flag <["-"], "fmodules-implicit-maps">,
+  Group<f_Group>, Flags<[DriverOption, CC1Option]>;
+def fno_modules_implicit_maps :
+  Flag <["-"], "fno-modules-implicit-maps">,
+  Group<f_Group>, Flags<[DriverOption, CC1Option]>;
+def fno_implicit_modules :
+  Flag <["-"], "fno-implicit-modules">,
+  Group<f_Group>, Flags<[DriverOption, CC1Option]>;
 def fretain_comments_from_system_headers : Flag<["-"], "fretain-comments-from-system-headers">, Group<f_Group>, Flags<[CC1Option]>;
 
 def fmudflapth : Flag<["-"], "fmudflapth">, Group<f_Group>;
@@ -735,6 +768,8 @@
   Flags<[DriverOption]>;
 def fno_modules_strict_decluse : Flag <["-"], "fno-strict-modules-decluse">, Group<f_Group>,
   Flags<[DriverOption]>;
+def fimplicit_modules : Flag <["-"], "fimplicit-modules">, Group<f_Group>,
+  Flags<[DriverOption]>;
 def fno_ms_extensions : Flag<["-"], "fno-ms-extensions">, Group<f_Group>;
 def fno_ms_compatibility : Flag<["-"], "fno-ms-compatibility">, Group<f_Group>;
 def fno_delayed_template_parsing : Flag<["-"], "fno-delayed-template-parsing">, Group<f_Group>;
@@ -856,6 +891,7 @@
 def fshow_column : Flag<["-"], "fshow-column">, Group<f_Group>, Flags<[CC1Option]>;
 def fshow_source_location : Flag<["-"], "fshow-source-location">, Group<f_Group>;
 def fspell_checking : Flag<["-"], "fspell-checking">, Group<f_Group>;
+def fspell_checking_limit_EQ : Joined<["-"], "fspell-checking-limit=">, Group<f_Group>;
 def fsigned_bitfields : Flag<["-"], "fsigned-bitfields">, Group<f_Group>;
 def fsigned_char : Flag<["-"], "fsigned-char">, Group<f_Group>;
 def fno_signed_char : Flag<["-"], "fno-signed-char">, Flags<[CC1Option]>,
@@ -933,6 +969,10 @@
   HelpText<"Turn on loop reroller">, Flags<[CC1Option]>;
 def fno_reroll_loops : Flag<["-"], "fno-reroll-loops">, Group<f_Group>,
   HelpText<"Turn off loop reroller">;
+def ftrigraphs : Flag<["-"], "ftrigraphs">, Group<f_Group>,
+  HelpText<"Process trigraph sequences">, Flags<[CC1Option]>;
+def fno_trigraphs : Flag<["-"], "fno-trigraphs">, Group<f_Group>,
+  HelpText<"Do not process trigraph sequences">, Flags<[CC1Option]>;
 def funsigned_bitfields : Flag<["-"], "funsigned-bitfields">, Group<f_Group>;
 def funsigned_char : Flag<["-"], "funsigned-char">, Group<f_Group>;
 def fno_unsigned_char : Flag<["-"], "fno-unsigned-char">, Group<clang_ignored_f_Group>;
@@ -964,6 +1004,14 @@
  Flags<[CC1Option]>, HelpText<"Place each data in its own section (ELF Only)">;
 def fno_data_sections : Flag <["-"], "fno-data-sections">, Group<f_Group>,
   Flags<[CC1Option]>;
+
+def funique_section_names : Flag <["-"], "funique-section-names">,
+  Group<f_Group>, Flags<[CC1Option]>,
+  HelpText<"Use unique names for text and data sections (ELF Only)">;
+def fno_unique_section_names : Flag <["-"], "fno-unique-section-names">,
+  Group<f_Group>, Flags<[CC1Option]>;
+
+
 def fdebug_types_section: Flag <["-"], "fdebug-types-section">, Group<f_Group>,
   Flags<[CC1Option]>, HelpText<"Place debug types in their own section (ELF Only)">;
 def fno_debug_types_section: Flag<["-"], "fno-debug-types-section">, Group<f_Group>,
@@ -1085,20 +1133,24 @@
 def mglobal_merge : Flag<["-"], "mglobal-merge">, Group<m_Group>;
 def mhard_float : Flag<["-"], "mhard-float">, Group<m_Group>;
 def miphoneos_version_min_EQ : Joined<["-"], "miphoneos-version-min=">, Group<m_Group>;
-def mios_version_min_EQ : Joined<["-"], "mios-version-min=">, Alias<miphoneos_version_min_EQ>;
+def mios_version_min_EQ : Joined<["-"], "mios-version-min=">,
+  Alias<miphoneos_version_min_EQ>, HelpText<"Set iOS deployment target">;
 def mios_simulator_version_min_EQ : Joined<["-"], "mios-simulator-version-min=">, Alias<miphoneos_version_min_EQ>;
 def mkernel : Flag<["-"], "mkernel">, Group<m_Group>;
 def mlinker_version_EQ : Joined<["-"], "mlinker-version=">,
   Flags<[DriverOption]>;
 def mllvm : Separate<["-"], "mllvm">, Flags<[CC1Option,CC1AsOption,CoreOption]>,
   HelpText<"Additional arguments to forward to LLVM's option processing">;
-def mmacosx_version_min_EQ : Joined<["-"], "mmacosx-version-min=">, Group<m_Group>;
+def mmacosx_version_min_EQ : Joined<["-"], "mmacosx-version-min=">,
+  Group<m_Group>, HelpText<"Set Mac OS X deployment target">;
 def mms_bitfields : Flag<["-"], "mms-bitfields">, Group<m_Group>, Flags<[CC1Option]>,
   HelpText<"Set the default structure layout to be compatible with the Microsoft compiler standard">;
 def mstackrealign : Flag<["-"], "mstackrealign">, Group<m_Group>, Flags<[CC1Option]>,
   HelpText<"Force realign the stack at entry to every function">;
 def mstack_alignment : Joined<["-"], "mstack-alignment=">, Group<m_Group>, Flags<[CC1Option]>,
   HelpText<"Set the stack alignment">;
+def mstack_probe_size : Joined<["-"], "mstack-probe-size=">, Group<m_Group>, Flags<[CC1Option]>,
+  HelpText<"Set the stack probe size">;
 def mthread_model : Separate<["-"], "mthread-model">, Group<m_Group>, Flags<[CC1Option]>,
   HelpText<"The thread model to use, e.g. posix, single (posix by default)">;
 
@@ -1178,6 +1230,15 @@
 def mgeneral_regs_only : Flag<["-"], "mgeneral-regs-only">, Group<m_aarch64_Features_Group>,
   HelpText<"Generate code which only uses the general purpose registers (AArch64 only)">;
 
+def mfix_cortex_a53_835769 : Flag<["-"], "mfix-cortex-a53-835769">,
+  Group<m_aarch64_Features_Group>,
+  HelpText<"Workaround Cortex-A53 erratum 835769 (AArch64 only)">;
+def mno_fix_cortex_a53_835769 : Flag<["-"], "mno-fix-cortex-a53-835769">,
+  Group<m_aarch64_Features_Group>,
+  HelpText<"Don't workaround Cortex-A53 erratum 835769 (AArch64 only)">;
+def ffixed_x18 : Flag<["-"], "ffixed-x18">, Group<m_aarch64_Features_Group>,
+  HelpText<"Reserve the x18 register (AArch64 only)">;
+
 def mvsx : Flag<["-"], "mvsx">, Group<m_ppc_Features_Group>;
 def mno_vsx : Flag<["-"], "mno-vsx">, Group<m_ppc_Features_Group>;
 def mpower8_vector : Flag<["-"], "mpower8-vector">,
@@ -1186,6 +1247,8 @@
     Group<m_ppc_Features_Group>;
 def mfprnd : Flag<["-"], "mfprnd">, Group<m_ppc_Features_Group>;
 def mno_fprnd : Flag<["-"], "mno-fprnd">, Group<m_ppc_Features_Group>;
+def mcmpb : Flag<["-"], "mcmpb">, Group<m_ppc_Features_Group>;
+def mno_cmpb : Flag<["-"], "mno-cmpb">, Group<m_ppc_Features_Group>;
 def mmfcrf : Flag<["-"], "mmfcrf">, Group<m_ppc_Features_Group>;
 def mno_mfcrf : Flag<["-"], "mno-mfcrf">, Group<m_ppc_Features_Group>;
 def mpopcntd : Flag<["-"], "mpopcntd">, Group<m_ppc_Features_Group>;
@@ -1194,6 +1257,11 @@
 def mno_qpx : Flag<["-"], "mno-qpx">, Group<m_ppc_Features_Group>;
 def mcrbits : Flag<["-"], "mcrbits">, Group<m_ppc_Features_Group>;
 def mno_crbits : Flag<["-"], "mno-crbits">, Group<m_ppc_Features_Group>;
+def minvariant_function_descriptors :
+  Flag<["-"], "minvariant-function-descriptors">, Group<m_ppc_Features_Group>;
+def mno_invariant_function_descriptors :
+  Flag<["-"], "mno-invariant-function-descriptors">,
+  Group<m_ppc_Features_Group>;
 
 def faltivec : Flag<["-"], "faltivec">, Group<f_Group>, Flags<[CC1Option]>,
   HelpText<"Enable AltiVec vector initializer syntax">;
@@ -1306,6 +1374,12 @@
 def mips32r2 : Flag<["-"], "mips32r2">,
   Alias<march_EQ>, AliasArgs<["mips32r2"]>,
   HelpText<"Equivalent to -march=mips32r2">, Flags<[HelpHidden]>;
+def mips32r3 : Flag<["-"], "mips32r3">,
+  Alias<march_EQ>, AliasArgs<["mips32r3"]>,
+  HelpText<"Equivalent to -march=mips32r3">, Flags<[HelpHidden]>;
+def mips32r5 : Flag<["-"], "mips32r5">,
+  Alias<march_EQ>, AliasArgs<["mips32r5"]>,
+  HelpText<"Equivalent to -march=mips32r5">, Flags<[HelpHidden]>;
 def mips32r6 : Flag<["-"], "mips32r6">,
   Alias<march_EQ>, AliasArgs<["mips32r6"]>,
   HelpText<"Equivalent to -march=mips32r6">, Flags<[HelpHidden]>;
@@ -1315,6 +1389,12 @@
 def mips64r2 : Flag<["-"], "mips64r2">,
   Alias<march_EQ>, AliasArgs<["mips64r2"]>,
   HelpText<"Equivalent to -march=mips64r2">, Flags<[HelpHidden]>;
+def mips64r3 : Flag<["-"], "mips64r3">,
+  Alias<march_EQ>, AliasArgs<["mips64r3"]>,
+  HelpText<"Equivalent to -march=mips64r3">, Flags<[HelpHidden]>;
+def mips64r5 : Flag<["-"], "mips64r5">,
+  Alias<march_EQ>, AliasArgs<["mips64r5"]>,
+  HelpText<"Equivalent to -march=mips64r5">, Flags<[HelpHidden]>;
 def mips64r6 : Flag<["-"], "mips64r6">,
   Alias<march_EQ>, AliasArgs<["mips64r6"]>,
   HelpText<"Equivalent to -march=mips64r6">, Flags<[HelpHidden]>;
@@ -1404,7 +1484,10 @@
 def rpath : Separate<["-"], "rpath">, Flags<[LinkerInput]>;
 def rtlib_EQ : Joined<["-", "--"], "rtlib=">;
 def r : Flag<["-"], "r">;
+def save_temps_EQ : Joined<["-", "--"], "save-temps=">, Flags<[DriverOption]>,
+  HelpText<"Save intermediate compilation results.">;
 def save_temps : Flag<["-", "--"], "save-temps">, Flags<[DriverOption]>,
+  Alias<save_temps_EQ>, AliasArgs<["cwd"]>,
   HelpText<"Save intermediate compilation results">;
 def via_file_asm : Flag<["-", "--"], "via-file-asm">, InternalDebugOpt,
   HelpText<"Write assembly to file for input to assemble jobs">;
@@ -1457,7 +1540,7 @@
 def traditional_cpp : Flag<["-", "--"], "traditional-cpp">, Flags<[CC1Option]>,
   HelpText<"Enable some traditional CPP emulation">;
 def traditional : Flag<["-", "--"], "traditional">;
-def trigraphs : Flag<["-", "--"], "trigraphs">, Flags<[CC1Option]>,
+def trigraphs : Flag<["-", "--"], "trigraphs">, Alias<ftrigraphs>,
   HelpText<"Process trigraph sequences">;
 def twolevel__namespace__hints : Flag<["-"], "twolevel_namespace_hints">;
 def twolevel__namespace : Flag<["-"], "twolevel_namespace">;
diff --git a/include/clang/Driver/Phases.h b/include/clang/Driver/Phases.h
index e2160e6..cd6b5b5 100644
--- a/include/clang/Driver/Phases.h
+++ b/include/clang/Driver/Phases.h
@@ -19,6 +19,7 @@
     Preprocess,
     Precompile,
     Compile,
+    Backend,
     Assemble,
     Link
   };
diff --git a/include/clang/Driver/SanitizerArgs.h b/include/clang/Driver/SanitizerArgs.h
index 32b2e89..5874c26 100644
--- a/include/clang/Driver/SanitizerArgs.h
+++ b/include/clang/Driver/SanitizerArgs.h
@@ -13,6 +13,7 @@
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
 #include <string>
+#include <vector>
 
 namespace clang {
 namespace driver {
@@ -22,9 +23,9 @@
 
 class SanitizerArgs {
   SanitizerSet Sanitizers;
-  bool SanitizeRecover;
+  SanitizerSet RecoverableSanitizers;
 
-  std::string BlacklistFile;
+  std::vector<std::string> BlacklistFiles;
   int SanitizeCoverage;
   int MsanTrackOrigins;
   int AsanFieldPadding;
@@ -48,9 +49,9 @@
   bool needsUbsanRt() const;
   bool needsDfsanRt() const { return Sanitizers.has(SanitizerKind::DataFlow); }
 
-  bool sanitizesVptr() const { return Sanitizers.has(SanitizerKind::Vptr); }
-  bool hasZeroBaseShadow() const;
+  bool requiresPIE() const;
   bool needsUnwindTables() const;
+  bool needsLTO() const;
   bool linkCXXRuntimes() const { return LinkCXXRuntimes; }
   void addArgs(const llvm::opt::ArgList &Args,
                llvm::opt::ArgStringList &CmdArgs) const;
diff --git a/include/clang/Driver/Tool.h b/include/clang/Driver/Tool.h
index aa895d0..b9eac1c 100644
--- a/include/clang/Driver/Tool.h
+++ b/include/clang/Driver/Tool.h
@@ -84,6 +84,7 @@
   const ToolChain &getToolChain() const { return TheToolChain; }
 
   virtual bool hasIntegratedAssembler() const { return false; }
+  virtual bool canEmitIR() const { return false; }
   virtual bool hasIntegratedCPP() const = 0;
   virtual bool isLinkJob() const { return false; }
   virtual bool isDsymutilJob() const { return false; }
diff --git a/include/clang/Driver/ToolChain.h b/include/clang/Driver/ToolChain.h
index 7279951..560df19 100644
--- a/include/clang/Driver/ToolChain.h
+++ b/include/clang/Driver/ToolChain.h
@@ -53,10 +53,20 @@
     RLT_Libgcc
   };
 
+  enum RTTIMode {
+    RM_EnabledExplicitly,
+    RM_EnabledImplicitly,
+    RM_DisabledExplicitly,
+    RM_DisabledImplicitly
+  };
+
 private:
   const Driver &D;
   const llvm::Triple Triple;
   const llvm::opt::ArgList &Args;
+  // We need to initialize CachedRTTIArg before CachedRTTIMode
+  const llvm::opt::Arg *const CachedRTTIArg;
+  const RTTIMode CachedRTTIMode;
 
   /// The list of toolchain specific path prefixes to search for
   /// files.
@@ -134,6 +144,12 @@
 
   const SanitizerArgs& getSanitizerArgs() const;
 
+  // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
+  const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
+
+  // Returns the RTTIMode for the toolchain with the current arguments.
+  RTTIMode getRTTIMode() const { return CachedRTTIMode; }
+
   // Tool access.
 
   /// TranslateArgs - Create a new derived argument list for any argument
@@ -251,7 +267,7 @@
   /// getThreadModel() - Which thread model does this target use?
   virtual std::string getThreadModel() const { return "posix"; }
 
-  /// supportsThreadModel() - Does this target support a thread model?
+  /// isThreadModelSupported() - Does this target support a thread model?
   virtual bool isThreadModelSupported(const StringRef Model) const;
 
   /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
diff --git a/include/clang/Format/Format.h b/include/clang/Format/Format.h
index a04705c..60c54ab 100644
--- a/include/clang/Format/Format.h
+++ b/include/clang/Format/Format.h
@@ -212,6 +212,8 @@
     SFS_None,
     /// \brief Only merge functions defined inside a class.
     SFS_Inline,
+    /// \brief Only merge empty functions.
+    SFS_Empty,
     /// \brief Merge all functions fitting on a single line.
     SFS_All,
   };
@@ -238,6 +240,10 @@
   /// \endcode
   bool AlignAfterOpenBracket;
 
+  /// \brief If \c true, horizontally align operands of binary and ternary
+  /// expressions.
+  bool AlignOperands;
+
   /// \brief If \c true, aligns trailing comments.
   bool AlignTrailingComments;
 
@@ -405,6 +411,7 @@
   bool operator==(const FormatStyle &R) const {
     return AccessModifierOffset == R.AccessModifierOffset &&
            AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
+           AlignOperands == R.AlignOperands &&
            AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
            AlignTrailingComments == R.AlignTrailingComments &&
            AllowAllParametersOfDeclarationOnNextLine ==
diff --git a/include/clang/Frontend/ASTConsumers.h b/include/clang/Frontend/ASTConsumers.h
index 54e06ef..757fcae 100644
--- a/include/clang/Frontend/ASTConsumers.h
+++ b/include/clang/Frontend/ASTConsumers.h
@@ -15,7 +15,6 @@
 #define LLVM_CLANG_FRONTEND_ASTCONSUMERS_H
 
 #include "clang/Basic/LLVM.h"
-
 #include <memory>
 
 namespace clang {
diff --git a/include/clang/Frontend/ASTUnit.h b/include/clang/Frontend/ASTUnit.h
index 634224d..79adf59 100644
--- a/include/clang/Frontend/ASTUnit.h
+++ b/include/clang/Frontend/ASTUnit.h
@@ -416,8 +416,8 @@
   /// \brief Clear out and deallocate 
   void ClearCachedCompletionResults();
   
-  ASTUnit(const ASTUnit &) LLVM_DELETED_FUNCTION;
-  void operator=(const ASTUnit &) LLVM_DELETED_FUNCTION;
+  ASTUnit(const ASTUnit &) = delete;
+  void operator=(const ASTUnit &) = delete;
   
   explicit ASTUnit(bool MainFileIsAST);
 
@@ -675,8 +675,8 @@
   /// \brief Returns an iterator range for the local preprocessing entities
   /// of the local Preprocessor, if this is a parsed source file, or the loaded
   /// preprocessing entities of the primary module if this is an AST file.
-  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
-    getLocalPreprocessingEntities() const;
+  llvm::iterator_range<PreprocessingRecord::iterator>
+  getLocalPreprocessingEntities() const;
 
   /// \brief Type for a function iterating over a number of declarations.
   /// \returns true to continue iteration and false to abort.
diff --git a/include/clang/Frontend/CodeGenOptions.def b/include/clang/Frontend/CodeGenOptions.def
index 8e0c78a..f14898f 100644
--- a/include/clang/Frontend/CodeGenOptions.def
+++ b/include/clang/Frontend/CodeGenOptions.def
@@ -40,6 +40,7 @@
 CODEGENOPT(CXXCtorDtorAliases, 1, 0) ///< Emit complete ctors/dtors as linker
                                      ///< aliases to base ctors when possible.
 CODEGENOPT(DataSections      , 1, 0) ///< Set when -fdata-sections is enabled.
+CODEGENOPT(UniqueSectionNames, 1, 1) ///< Set for -funique-section-names.
 CODEGENOPT(DisableFPElim     , 1, 0) ///< Set when -fomit-frame-pointer is enabled.
 CODEGENOPT(DisableFree       , 1, 0) ///< Don't free memory.
 CODEGENOPT(DisableGCov       , 1, 0) ///< Don't run the GCov pass, for testing.
@@ -68,6 +69,7 @@
                                      ///< be generated.
 CODEGENOPT(MergeAllConstants , 1, 1) ///< Merge identical constants.
 CODEGENOPT(MergeFunctions    , 1, 0) ///< Set when -fmerge-functions is enabled.
+CODEGENOPT(MSVolatile        , 1, 0) ///< Set when /volatile:ms is enabled.
 CODEGENOPT(NoCommon          , 1, 0) ///< Set when -fno-common or C++ is enabled.
 CODEGENOPT(NoDwarfDirectoryAsm , 1, 0) ///< Set when -fno-dwarf-directory-asm is
                                        ///< enabled.
@@ -78,6 +80,7 @@
 CODEGENOPT(NoGlobalMerge     , 1, 0) ///< Set when -mno-global-merge is enabled.
 CODEGENOPT(NoImplicitFloat   , 1, 0) ///< Set when -mno-implicit-float is enabled.
 CODEGENOPT(NoInfsFPMath      , 1, 0) ///< Assume FP arguments, results not +-Inf.
+CODEGENOPT(NoSignedZeros     , 1, 0) ///< Allow ignoring the signedness of FP zero
 CODEGENOPT(NoInline          , 1, 0) ///< Set when -fno-inline is enabled. 
                                      ///< Disables use of the inline keyword.
 CODEGENOPT(NoNaNsFPMath      , 1, 0) ///< Assume FP arguments, results not NaN.
@@ -86,7 +89,7 @@
 ENUM_CODEGENOPT(ObjCDispatchMethod, ObjCDispatchMethodKind, 2, Legacy) 
 CODEGENOPT(OmitLeafFramePointer , 1, 0) ///< Set when -momit-leaf-frame-pointer is
                                         ///< enabled.
-VALUE_CODEGENOPT(OptimizationLevel, 3, 0) ///< The -O[0-4] option specified.
+VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option specified.
 VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is specified.
 
 CODEGENOPT(ProfileInstrGenerate , 1, 0) ///< Instrument code to generate
@@ -137,6 +140,8 @@
                                      ///< .ctors.
 VALUE_CODEGENOPT(StackAlignment    , 32, 0) ///< Overrides default stack 
                                             ///< alignment, if not 0.
+VALUE_CODEGENOPT(StackProbeSize    , 32, 4096) ///< Overrides default stack
+                                               ///< probe size, even if 0.
 CODEGENOPT(DebugColumnInfo, 1, 0) ///< Whether or not to use column information
                                   ///< in debug info.
 
@@ -159,9 +164,6 @@
 /// The default TLS model to use.
 ENUM_CODEGENOPT(DefaultTLSModel, TLSModel, 2, GeneralDynamicTLSModel)
 
-CODEGENOPT(SanitizeRecover, 1, 1) ///< Attempt to recover from sanitizer checks
-                                  ///< by continuing execution when possible
-
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
 #undef VALUE_CODEGENOPT
diff --git a/include/clang/Frontend/CodeGenOptions.h b/include/clang/Frontend/CodeGenOptions.h
index 4e6171f..8196064 100644
--- a/include/clang/Frontend/CodeGenOptions.h
+++ b/include/clang/Frontend/CodeGenOptions.h
@@ -14,10 +14,11 @@
 #ifndef LLVM_CLANG_FRONTEND_CODEGENOPTIONS_H
 #define LLVM_CLANG_FRONTEND_CODEGENOPTIONS_H
 
+#include "clang/Basic/Sanitizers.h"
+#include "llvm/Support/Regex.h"
 #include <memory>
 #include <string>
 #include <vector>
-#include "llvm/Support/Regex.h"
 
 namespace clang {
 
@@ -176,6 +177,13 @@
   /// flag.
   std::shared_ptr<llvm::Regex> OptimizationRemarkAnalysisPattern;
 
+  /// Set of files definining the rules for the symbol rewriting.
+  std::vector<std::string> RewriteMapFiles;
+
+  /// Set of sanitizer checks that are non-fatal (i.e. execution should be
+  /// continued when possible).
+  SanitizerSet SanitizeRecover;
+
 public:
   // Define accessors/mutators for code generation options of enumeration type.
 #define CODEGENOPT(Name, Bits, Default)
diff --git a/include/clang/Frontend/CompilerInstance.h b/include/clang/Frontend/CompilerInstance.h
index 31a0d09..ed01329 100644
--- a/include/clang/Frontend/CompilerInstance.h
+++ b/include/clang/Frontend/CompilerInstance.h
@@ -10,11 +10,11 @@
 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
 
+#include "clang/AST/ASTConsumer.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/Utils.h"
-#include "clang/AST/ASTConsumer.h"
 #include "clang/Lex/ModuleLoader.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -121,6 +121,10 @@
   /// \brief Module names that have an override for the target file.
   llvm::StringMap<std::string> ModuleFileOverrides;
 
+  /// \brief Module files that we've explicitly loaded via \ref loadModuleFile,
+  /// and their dependencies.
+  llvm::StringSet<> ExplicitlyLoadedModuleFiles;
+
   /// \brief The location of the module-import keyword for the last module
   /// import. 
   SourceLocation LastModuleImportLoc;
@@ -157,8 +161,8 @@
   /// The list of active output files.
   std::list<OutputFile> OutputFiles;
 
-  CompilerInstance(const CompilerInstance &) LLVM_DELETED_FUNCTION;
-  void operator=(const CompilerInstance &) LLVM_DELETED_FUNCTION;
+  CompilerInstance(const CompilerInstance &) = delete;
+  void operator=(const CompilerInstance &) = delete;
 public:
   explicit CompilerInstance(bool BuildingModule = false);
   ~CompilerInstance();
@@ -250,6 +254,9 @@
     return Invocation->getDiagnosticOpts();
   }
 
+  FileSystemOptions &getFileSystemOpts() {
+    return Invocation->getFileSystemOpts();
+  }
   const FileSystemOptions &getFileSystemOpts() const {
     return Invocation->getFileSystemOpts();
   }
@@ -572,6 +579,8 @@
   /// and replace any existing one with it.
   void createPreprocessor(TranslationUnitKind TUKind);
 
+  std::string getSpecificModuleCachePath();
+
   /// Create the AST context.
   void createASTContext();
 
@@ -585,7 +594,7 @@
   /// Create an external AST source to read a PCH file.
   ///
   /// \return - The new object on success, or null on failure.
-  static ExternalASTSource *createPCHExternalASTSource(
+  static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
       StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
       bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
       void *DeserializationListener, bool OwnDeserializationListener,
diff --git a/include/clang/Frontend/CompilerInvocation.h b/include/clang/Frontend/CompilerInvocation.h
index f05ab80..7d12548 100644
--- a/include/clang/Frontend/CompilerInvocation.h
+++ b/include/clang/Frontend/CompilerInvocation.h
@@ -50,7 +50,7 @@
                          DiagnosticsEngine *Diags = nullptr);
 
 class CompilerInvocationBase : public RefCountedBase<CompilerInvocation> {
-  void operator=(const CompilerInvocationBase &) LLVM_DELETED_FUNCTION;
+  void operator=(const CompilerInvocationBase &) = delete;
 
 public:
   /// Options controlling the language variant.
diff --git a/include/clang/Frontend/FrontendOptions.h b/include/clang/Frontend/FrontendOptions.h
index 4e93b4e..71c5aa4 100644
--- a/include/clang/Frontend/FrontendOptions.h
+++ b/include/clang/Frontend/FrontendOptions.h
@@ -233,6 +233,9 @@
   /// The list of plugins to load.
   std::vector<std::string> Plugins;
 
+  /// \brief The list of module map files to load before processing the input.
+  std::vector<std::string> ModuleMapFiles;
+
   /// \brief The list of additional prebuilt module files to load before
   /// processing the input.
   std::vector<std::string> ModuleFiles;
diff --git a/include/clang/Frontend/MultiplexConsumer.h b/include/clang/Frontend/MultiplexConsumer.h
index c9122da..2553275 100644
--- a/include/clang/Frontend/MultiplexConsumer.h
+++ b/include/clang/Frontend/MultiplexConsumer.h
@@ -49,7 +49,7 @@
                             llvm::StringRef Value) override;
   void HandleDependentLibrary(llvm::StringRef Lib) override;
   void CompleteTentativeDefinition(VarDecl *D) override;
-  void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override;
+  void HandleVTable(CXXRecordDecl *RD) override;
   ASTMutationListener *GetASTMutationListener() override;
   ASTDeserializationListener *GetASTDeserializationListener() override;
   void PrintStats() override;
diff --git a/include/clang/Frontend/PreprocessorOutputOptions.h b/include/clang/Frontend/PreprocessorOutputOptions.h
index e273dd6..f86c490 100644
--- a/include/clang/Frontend/PreprocessorOutputOptions.h
+++ b/include/clang/Frontend/PreprocessorOutputOptions.h
@@ -19,6 +19,7 @@
   unsigned ShowCPP : 1;            ///< Print normal preprocessed output.
   unsigned ShowComments : 1;       ///< Show comments.
   unsigned ShowLineMarkers : 1;    ///< Show \#line markers.
+  unsigned UseLineDirectives : 1;   ///< Use \#line instead of GCC-style \# N.
   unsigned ShowMacroComments : 1;  ///< Show comments, even in macros.
   unsigned ShowMacros : 1;         ///< Print macro definitions.
   unsigned RewriteIncludes : 1;    ///< Preprocess include directives only.
@@ -28,6 +29,7 @@
     ShowCPP = 0;
     ShowComments = 0;
     ShowLineMarkers = 1;
+    UseLineDirectives = 0;
     ShowMacroComments = 0;
     ShowMacros = 0;
     RewriteIncludes = 0;
diff --git a/include/clang/Frontend/VerifyDiagnosticConsumer.h b/include/clang/Frontend/VerifyDiagnosticConsumer.h
index 80e140b..aa0bcc9 100644
--- a/include/clang/Frontend/VerifyDiagnosticConsumer.h
+++ b/include/clang/Frontend/VerifyDiagnosticConsumer.h
@@ -180,8 +180,8 @@
     }
 
   private:
-    Directive(const Directive &) LLVM_DELETED_FUNCTION;
-    void operator=(const Directive &) LLVM_DELETED_FUNCTION;
+    Directive(const Directive &) = delete;
+    void operator=(const Directive &) = delete;
   };
 
   typedef std::vector<std::unique_ptr<Directive>> DirectiveList;
diff --git a/include/clang/Lex/HeaderMap.h b/include/clang/Lex/HeaderMap.h
index 5dac9b7..183361e 100644
--- a/include/clang/Lex/HeaderMap.h
+++ b/include/clang/Lex/HeaderMap.h
@@ -16,7 +16,6 @@
 
 #include "clang/Basic/LLVM.h"
 #include "llvm/Support/Compiler.h"
-
 #include <memory>
 
 namespace llvm {
@@ -33,8 +32,8 @@
 /// symlinks to files.  Its advantages are that it is dense and more efficient
 /// to create and process than a directory of symlinks.
 class HeaderMap {
-  HeaderMap(const HeaderMap &) LLVM_DELETED_FUNCTION;
-  void operator=(const HeaderMap &) LLVM_DELETED_FUNCTION;
+  HeaderMap(const HeaderMap &) = delete;
+  void operator=(const HeaderMap &) = delete;
 
   std::unique_ptr<const llvm::MemoryBuffer> FileBuffer;
   bool NeedsBSwap;
diff --git a/include/clang/Lex/HeaderSearch.h b/include/clang/Lex/HeaderSearch.h
index 47e3313..28e7da3 100644
--- a/include/clang/Lex/HeaderSearch.h
+++ b/include/clang/Lex/HeaderSearch.h
@@ -252,11 +252,11 @@
   unsigned NumMultiIncludeFileOptzn;
   unsigned NumFrameworkLookups, NumSubFrameworkLookups;
 
-  bool EnabledModules;
+  const LangOptions &LangOpts;
 
   // HeaderSearch doesn't support default or copy construction.
-  HeaderSearch(const HeaderSearch&) LLVM_DELETED_FUNCTION;
-  void operator=(const HeaderSearch&) LLVM_DELETED_FUNCTION;
+  HeaderSearch(const HeaderSearch&) = delete;
+  void operator=(const HeaderSearch&) = delete;
 
   friend class DirectoryLookup;
   
@@ -479,7 +479,7 @@
   const HeaderMap *CreateHeaderMap(const FileEntry *FE);
 
   /// Returns true if modules are enabled.
-  bool enabledModules() const { return EnabledModules; }
+  bool enabledModules() const { return LangOpts.Modules; }
 
   /// \brief Retrieve the name of the module file that should be used to 
   /// load the given module.
@@ -640,7 +640,8 @@
   };
 
   LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File,
-                                            bool IsSystem);
+                                            bool IsSystem,
+                                            const DirectoryEntry *Dir);
 
   /// \brief Try to load the module map file in the given directory.
   ///
diff --git a/include/clang/Lex/HeaderSearchOptions.h b/include/clang/Lex/HeaderSearchOptions.h
index 06024b2..775943d 100644
--- a/include/clang/Lex/HeaderSearchOptions.h
+++ b/include/clang/Lex/HeaderSearchOptions.h
@@ -101,6 +101,15 @@
   /// \brief Interpret module maps.  This option is implied by full modules.
   unsigned ModuleMaps : 1;
 
+  /// \brief Set the 'home directory' of a module map file to the current
+  /// working directory (or the home directory of the module map file that
+  /// contained the 'extern module' directive importing this module map file
+  /// if any) rather than the directory containing the module map file.
+  //
+  /// The home directory is where we look for files named in the module map
+  /// file.
+  unsigned ModuleMapFileHomeIsCwd : 1;
+
   /// \brief The interval (in seconds) between pruning operations.
   ///
   /// This operation is expensive, because it requires Clang to walk through
@@ -129,9 +138,6 @@
   /// of computing the module hash.
   llvm::SetVector<std::string> ModulesIgnoreMacros;
 
-  /// \brief The set of user-provided module-map-files.
-  llvm::SetVector<std::string> ModuleMapFiles;
-
   /// \brief The set of user-provided virtual filesystem overlay files.
   std::vector<std::string> VFSOverlayFiles;
 
@@ -161,6 +167,7 @@
 public:
   HeaderSearchOptions(StringRef _Sysroot = "/")
     : Sysroot(_Sysroot), DisableModuleHash(0), ModuleMaps(0),
+      ModuleMapFileHomeIsCwd(0),
       ModuleCachePruneInterval(7*24*60*60),
       ModuleCachePruneAfter(31*24*60*60),
       BuildSessionTimestamp(0),
diff --git a/include/clang/Lex/Lexer.h b/include/clang/Lex/Lexer.h
index c1f968b..07564b9 100644
--- a/include/clang/Lex/Lexer.h
+++ b/include/clang/Lex/Lexer.h
@@ -89,8 +89,8 @@
   // CurrentConflictMarkerState - The kind of conflict marker we are handling.
   ConflictMarkerKind CurrentConflictMarkerState;
 
-  Lexer(const Lexer &) LLVM_DELETED_FUNCTION;
-  void operator=(const Lexer &) LLVM_DELETED_FUNCTION;
+  Lexer(const Lexer &) = delete;
+  void operator=(const Lexer &) = delete;
   friend class Preprocessor;
 
   void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
@@ -323,6 +323,26 @@
                                             const SourceManager &SM,
                                             const LangOptions &LangOpts);
 
+  /// \brief Given a token range, produce a corresponding CharSourceRange that
+  /// is not a token range. This allows the source range to be used by
+  /// components that don't have access to the lexer and thus can't find the
+  /// end of the range for themselves.
+  static CharSourceRange getAsCharRange(SourceRange Range,
+                                        const SourceManager &SM,
+                                        const LangOptions &LangOpts) {
+    SourceLocation End = getLocForEndOfToken(Range.getEnd(), 0, SM, LangOpts);
+    return End.isInvalid() ? CharSourceRange()
+                           : CharSourceRange::getCharRange(
+                                 Range.getBegin(), End.getLocWithOffset(-1));
+  }
+  static CharSourceRange getAsCharRange(CharSourceRange Range,
+                                        const SourceManager &SM,
+                                        const LangOptions &LangOpts) {
+    return Range.isTokenRange()
+               ? getAsCharRange(Range.getAsRange(), SM, LangOpts)
+               : Range;
+  }
+
   /// \brief Returns true if the given MacroID location points at the first
   /// token of the macro expansion.
   ///
diff --git a/include/clang/Lex/MacroInfo.h b/include/clang/Lex/MacroInfo.h
index ca5d497..8a113cb 100644
--- a/include/clang/Lex/MacroInfo.h
+++ b/include/clang/Lex/MacroInfo.h
@@ -444,7 +444,7 @@
     bool isValid() const { return DefDirective != nullptr; }
     bool isInvalid() const { return !isValid(); }
 
-    LLVM_EXPLICIT operator bool() const { return isValid(); }
+    explicit operator bool() const { return isValid(); }
 
     inline DefInfo getPreviousDefinition();
     const DefInfo getPreviousDefinition() const {
diff --git a/include/clang/Lex/ModuleMap.h b/include/clang/Lex/ModuleMap.h
index 553716b..d281421 100644
--- a/include/clang/Lex/ModuleMap.h
+++ b/include/clang/Lex/ModuleMap.h
@@ -104,7 +104,7 @@
 
     // \brief Whether this known header is valid (i.e., it has an
     // associated module).
-    LLVM_EXPLICIT operator bool() const {
+    explicit operator bool() const {
       return Storage.getPointer() != nullptr;
     }
   };
@@ -127,15 +127,29 @@
   /// header.
   llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
 
+  /// \brief The set of attributes that can be attached to a module.
+  struct Attributes {
+    Attributes() : IsSystem(), IsExternC(), IsExhaustive() {}
+
+    /// \brief Whether this is a system module.
+    unsigned IsSystem : 1;
+
+    /// \brief Whether this is an extern "C" module.
+    unsigned IsExternC : 1;
+
+    /// \brief Whether this is an exhaustive set of configuration macros.
+    unsigned IsExhaustive : 1;
+  };
+
   /// \brief A directory for which framework modules can be inferred.
   struct InferredDirectory {
-    InferredDirectory() : InferModules(), InferSystemModules() { }
+    InferredDirectory() : InferModules() {}
 
     /// \brief Whether to infer modules from this directory.
     unsigned InferModules : 1;
 
-    /// \brief Whether the modules we infer are [system] modules.
-    unsigned InferSystemModules : 1;
+    /// \brief The attributes to use for inferred modules.
+    Attributes Attrs;
 
     /// \brief If \c InferModules is non-zero, the module map file that allowed
     /// inferred modules.  Otherwise, nullptr.
@@ -214,6 +228,10 @@
     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
   }
 
+  Module *inferFrameworkModule(StringRef ModuleName,
+                               const DirectoryEntry *FrameworkDir,
+                               Attributes Attrs, Module *Parent);
+
 public:
   /// \brief Construct a new module map.
   ///
@@ -331,22 +349,6 @@
                                                bool IsFramework,
                                                bool IsExplicit);
 
-  /// \brief Determine whether we can infer a framework module a framework
-  /// with the given name in the given
-  ///
-  /// \param ParentDir The directory that is the parent of the framework
-  /// directory.
-  ///
-  /// \param Name The name of the module.
-  ///
-  /// \param IsSystem Will be set to 'true' if the inferred module must be a
-  /// system module.
-  ///
-  /// \returns true if we are allowed to infer a framework module, and false
-  /// otherwise.
-  bool canInferFrameworkModule(const DirectoryEntry *ParentDir,
-                               StringRef Name, bool &IsSystem) const;
-
   /// \brief Infer the contents of a framework module map from the given
   /// framework directory.
   Module *inferFrameworkModule(StringRef ModuleName, 
@@ -440,11 +442,11 @@
 
   /// \brief Adds this header to the given module.
   /// \param Role The role of the header wrt the module.
-  void addHeader(Module *Mod, const FileEntry *Header,
+  void addHeader(Module *Mod, Module::Header Header,
                  ModuleHeaderRole Role);
 
   /// \brief Marks this header as being excluded from the given module.
-  void excludeHeader(Module *Mod, const FileEntry *Header);
+  void excludeHeader(Module *Mod, Module::Header Header);
 
   /// \brief Parse the given module map file, and record any modules we 
   /// encounter.
@@ -454,8 +456,12 @@
   /// \param IsSystem Whether this module map file is in a system header
   /// directory, and therefore should be considered a system module.
   ///
+  /// \param HomeDir The directory in which relative paths within this module
+  ///        map file will be resolved.
+  ///
   /// \returns true if an error occurred, false otherwise.
-  bool parseModuleMapFile(const FileEntry *File, bool IsSystem);
+  bool parseModuleMapFile(const FileEntry *File, bool IsSystem,
+                          const DirectoryEntry *HomeDir);
     
   /// \brief Dump the contents of the module map, for debugging purposes.
   void dump();
diff --git a/include/clang/Lex/PTHLexer.h b/include/clang/Lex/PTHLexer.h
index 54c91f6..75abf6b 100644
--- a/include/clang/Lex/PTHLexer.h
+++ b/include/clang/Lex/PTHLexer.h
@@ -44,8 +44,8 @@
   ///  to process when doing quick skipping of preprocessor blocks.
   const unsigned char* CurPPCondPtr;
 
-  PTHLexer(const PTHLexer &) LLVM_DELETED_FUNCTION;
-  void operator=(const PTHLexer &) LLVM_DELETED_FUNCTION;
+  PTHLexer(const PTHLexer &) = delete;
+  void operator=(const PTHLexer &) = delete;
 
   /// ReadToken - Used by PTHLexer to read tokens TokBuf.
   void ReadToken(Token& T);
diff --git a/include/clang/Lex/PTHManager.h b/include/clang/Lex/PTHManager.h
index 64ecf5f..e09afef 100644
--- a/include/clang/Lex/PTHManager.h
+++ b/include/clang/Lex/PTHManager.h
@@ -91,8 +91,8 @@
              std::unique_ptr<PTHStringIdLookup> stringIdLookup, unsigned numIds,
              const unsigned char *spellingBase, const char *originalSourceFile);
 
-  PTHManager(const PTHManager &) LLVM_DELETED_FUNCTION;
-  void operator=(const PTHManager &) LLVM_DELETED_FUNCTION;
+  PTHManager(const PTHManager &) = delete;
+  void operator=(const PTHManager &) = delete;
 
   /// getSpellingAtPTHOffset - Used by PTHLexer classes to get the cached
   ///  spelling for a token.
diff --git a/include/clang/Lex/PreprocessingRecord.h b/include/clang/Lex/PreprocessingRecord.h
index 4609fe3..3f9679c 100644
--- a/include/clang/Lex/PreprocessingRecord.h
+++ b/include/clang/Lex/PreprocessingRecord.h
@@ -518,23 +518,24 @@
       return iterator(this, PreprocessedEntities.size());
     }
 
-    /// \brief begin/end iterator pair for the given range of loaded
+    /// \brief iterator range for the given range of loaded
     /// preprocessed entities.
-    std::pair<iterator, iterator>
-    getIteratorsForLoadedRange(unsigned start, unsigned count) {
+    llvm::iterator_range<iterator> getIteratorsForLoadedRange(unsigned start,
+                                                              unsigned count) {
       unsigned end = start + count;
       assert(end <= LoadedPreprocessedEntities.size());
-      return std::make_pair(
-                   iterator(this, int(start)-LoadedPreprocessedEntities.size()),
-                   iterator(this, int(end)-LoadedPreprocessedEntities.size()));
+      return llvm::make_range(
+          iterator(this, int(start) - LoadedPreprocessedEntities.size()),
+          iterator(this, int(end) - LoadedPreprocessedEntities.size()));
     }
 
-    /// \brief Returns a pair of [Begin, End) iterators of preprocessed entities
-    /// that source range \p R encompasses.
+    /// \brief Returns a range of preprocessed entities that source range \p R
+    /// encompasses.
     ///
     /// \param R the range to look for preprocessed entities.
     ///
-    std::pair<iterator, iterator> getPreprocessedEntitiesInRange(SourceRange R);
+    llvm::iterator_range<iterator>
+    getPreprocessedEntitiesInRange(SourceRange R);
 
     /// \brief Returns true if the preprocessed entity that \p PPEI iterator
     /// points to is coming from the file \p FID.
diff --git a/include/clang/Lex/Preprocessor.h b/include/clang/Lex/Preprocessor.h
index d16f212..326f519 100644
--- a/include/clang/Lex/Preprocessor.h
+++ b/include/clang/Lex/Preprocessor.h
@@ -136,6 +136,7 @@
   IdentifierInfo *Ident__building_module;          // __building_module
   IdentifierInfo *Ident__MODULE__;                 // __MODULE__
   IdentifierInfo *Ident__has_cpp_attribute;        // __has_cpp_attribute
+  IdentifierInfo *Ident__has_declspec;             // __has_declspec_attribute
 
   SourceLocation DATELoc, TIMELoc;
   unsigned CounterValue;  // Next __COUNTER__ value.
@@ -257,6 +258,11 @@
   /// \brief True if we hit the code-completion point.
   bool CodeCompletionReached;
 
+  /// \brief The directory that the main file should be considered to occupy,
+  /// if it does not correspond to a real file (as happens when building a
+  /// module).
+  const DirectoryEntry *MainFileDir;
+
   /// \brief The number of bytes that we will initially skip when entering the
   /// main file, along with a flag that indicates whether skipping this number
   /// of bytes will place the lexer at the start of a line.
@@ -1014,6 +1020,12 @@
     PragmaARCCFCodeAuditedLoc = Loc;
   }
 
+  /// \brief Set the directory in which the main file should be considered
+  /// to have been found, if it is not a real file.
+  void setMainFileDir(const DirectoryEntry *Dir) {
+    MainFileDir = Dir;
+  }
+
   /// \brief Instruct the preprocessor to skip part of the main source file.
   ///
   /// \param Bytes The number of bytes in the preamble to skip.
@@ -1368,7 +1380,8 @@
   /// followed by EOD.  Return true if the token is not a valid on-off-switch.
   bool LexOnOffSwitch(tok::OnOffSwitch &OOS);
 
-  bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef);
+  bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
+                      bool *ShadowFlag = nullptr);
 
 private:
 
@@ -1408,11 +1421,17 @@
                                                              bool isPublic);
 
   /// \brief Lex and validate a macro name, which occurs after a
-  /// \#define or \#undef. 
+  /// \#define or \#undef.
+  ///
+  /// \param MacroNameTok Token that represents the name defined or undefined.
+  /// \param IsDefineUndef Kind if preprocessor directive.
+  /// \param ShadowFlag Points to flag that is set if macro name shadows
+  ///                   a keyword.
   ///
   /// This emits a diagnostic, sets the token kind to eod,
   /// and discards the rest of the macro line if the macro name is invalid.
-  void ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef = MU_Other);
+  void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other,
+                     bool *ShadowFlag = nullptr);
 
   /// The ( starting an argument list of a macro definition has just been read.
   /// Lex the rest of the arguments and the closing ), updating \p MI with
diff --git a/include/clang/Lex/PreprocessorLexer.h b/include/clang/Lex/PreprocessorLexer.h
index 3a91fa7..6d6cf05 100644
--- a/include/clang/Lex/PreprocessorLexer.h
+++ b/include/clang/Lex/PreprocessorLexer.h
@@ -69,8 +69,8 @@
   /// we are currently in.
   SmallVector<PPConditionalInfo, 4> ConditionalStack;
 
-  PreprocessorLexer(const PreprocessorLexer &) LLVM_DELETED_FUNCTION;
-  void operator=(const PreprocessorLexer &) LLVM_DELETED_FUNCTION;
+  PreprocessorLexer(const PreprocessorLexer &) = delete;
+  void operator=(const PreprocessorLexer &) = delete;
   friend class Preprocessor;
 
   PreprocessorLexer(Preprocessor *pp, FileID fid);
diff --git a/include/clang/Lex/Token.h b/include/clang/Lex/Token.h
index a58c0c5..4a53c9c 100644
--- a/include/clang/Lex/Token.h
+++ b/include/clang/Lex/Token.h
@@ -58,6 +58,8 @@
   ///    may be dirty (have trigraphs / escaped newlines).
   ///  Annotations (resolved type names, C++ scopes, etc): isAnnotation().
   ///    This is a pointer to sema-specific data for the annotation token.
+  ///  Eof:
+  //     This is a pointer to a Decl.
   ///  Other:
   ///    This is null.
   void *PtrData;
@@ -66,7 +68,7 @@
   tok::TokenKind Kind;
 
   /// Flags - Bits we track about this token, members of the TokenFlags enum.
-  unsigned char Flags;
+  unsigned short Flags;
 public:
 
   // Various flags set per token:
@@ -80,7 +82,9 @@
     LeadingEmptyMacro = 0x10, // Empty macro exists before this token.
     HasUDSuffix = 0x20,    // This string or character literal has a ud-suffix.
     HasUCN = 0x40,         // This identifier contains a UCN.
-    IgnoredComma = 0x80    // This comma is not a macro argument separator (MS).
+    IgnoredComma = 0x80,   // This comma is not a macro argument separator (MS).
+    StringifiedInMacro = 0x100, // This string or character literal is formed by
+                                // macro stringizing or charizing operator.
   };
 
   tok::TokenKind getKind() const { return Kind; }
@@ -162,12 +166,23 @@
     assert(!isAnnotation() &&
            "getIdentifierInfo() on an annotation token!");
     if (isLiteral()) return nullptr;
+    if (is(tok::eof)) return nullptr;
     return (IdentifierInfo*) PtrData;
   }
   void setIdentifierInfo(IdentifierInfo *II) {
     PtrData = (void*) II;
   }
 
+  const void *getEofData() const {
+    assert(is(tok::eof));
+    return reinterpret_cast<const void *>(PtrData);
+  }
+  void setEofData(const void *D) {
+    assert(is(tok::eof));
+    assert(!PtrData);
+    PtrData = const_cast<void *>(D);
+  }
+
   /// getRawIdentifier - For a raw identifier token (i.e., an identifier
   /// lexed in raw mode), returns a reference to the text substring in the
   /// buffer if known.
@@ -262,6 +277,12 @@
 
   /// Returns true if this token contains a universal character name.
   bool hasUCN() const { return (Flags & HasUCN) ? true : false; }
+
+  /// Returns true if this token is formed by macro by stringizing or charizing
+  /// operator.
+  bool stringifiedInMacro() const {
+    return (Flags & StringifiedInMacro) ? true : false;
+  }
 };
 
 /// \brief Information about the conditional stack (\#if directives)
diff --git a/include/clang/Lex/TokenLexer.h b/include/clang/Lex/TokenLexer.h
index 306f98e..3119736 100644
--- a/include/clang/Lex/TokenLexer.h
+++ b/include/clang/Lex/TokenLexer.h
@@ -99,8 +99,8 @@
   /// should not be subject to further macro expansion.
   bool DisableMacroExpansion : 1;
 
-  TokenLexer(const TokenLexer &) LLVM_DELETED_FUNCTION;
-  void operator=(const TokenLexer &) LLVM_DELETED_FUNCTION;
+  TokenLexer(const TokenLexer &) = delete;
+  void operator=(const TokenLexer &) = delete;
 public:
   /// Create a TokenLexer for the specified macro with the specified actual
   /// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
diff --git a/include/clang/Parse/Parser.h b/include/clang/Parse/Parser.h
index 38073c3..bb23b74 100644
--- a/include/clang/Parse/Parser.h
+++ b/include/clang/Parse/Parser.h
@@ -339,7 +339,7 @@
   void UnconsumeToken(Token &Consumed) {
       Token Next = Tok;
       PP.EnterToken(Consumed);
-      ConsumeToken();
+      PP.Lex(Tok);
       PP.EnterToken(Next);
   }
 
@@ -745,8 +745,8 @@
   /// the parser will exit the scope.
   class ParseScope {
     Parser *Self;
-    ParseScope(const ParseScope &) LLVM_DELETED_FUNCTION;
-    void operator=(const ParseScope &) LLVM_DELETED_FUNCTION;
+    ParseScope(const ParseScope &) = delete;
+    void operator=(const ParseScope &) = delete;
 
   public:
     // ParseScope - Construct a new object to manage a scope in the
@@ -790,8 +790,8 @@
   class ParseScopeFlags {
     Scope *CurScope;
     unsigned OldFlags;
-    ParseScopeFlags(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
-    void operator=(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
+    ParseScopeFlags(const ParseScopeFlags &) = delete;
+    void operator=(const ParseScopeFlags &) = delete;
 
   public:
     ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
@@ -1362,12 +1362,9 @@
   typedef SmallVector<SourceLocation, 20> CommaLocsTy;
 
   /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
-  bool
-  ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
-                      SmallVectorImpl<SourceLocation> &CommaLocs,
-                      void (Sema::*Completer)(Scope *S, Expr *Data,
-                                              ArrayRef<Expr *> Args) = nullptr,
-                      Expr *Data = nullptr);
+  bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
+                           SmallVectorImpl<SourceLocation> &CommaLocs,
+                           std::function<void()> Completer = nullptr);
 
   /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
   /// used for misc language extensions.
@@ -1661,7 +1658,6 @@
   // MS: SEH Statements and Blocks
 
   StmtResult ParseSEHTryBlock();
-  StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
   StmtResult ParseSEHExceptBlock(SourceLocation Loc);
   StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
   StmtResult ParseSEHLeaveStatement();
@@ -1728,7 +1724,6 @@
                                         ForRangeInit *FRI = nullptr);
   bool MightBeDeclarator(unsigned Context);
   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
-                                bool AllowFunctionDefinitions,
                                 SourceLocation *DeclEnd = nullptr,
                                 ForRangeInit *FRI = nullptr);
   Decl *ParseDeclarationAfterDeclarator(Declarator &D,
@@ -2094,6 +2089,8 @@
                                   SourceLocation AttrNameLoc,
                                   ParsedAttributes &Attrs);
   void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
+  void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
+  SourceLocation SkipExtendedMicrosoftTypeAttributes();
   void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
   void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
   void ParseOpenCLAttributes(ParsedAttributes &attrs);
@@ -2293,7 +2290,7 @@
                                    Decl *TagDecl);
   ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
                                        SourceLocation &EqualLoc);
-  void ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
+  bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo,
                                                  VirtSpecifiers &VS,
                                                  ExprResult &BitfieldSize,
                                                  LateParsedAttrList &LateAttrs);
diff --git a/include/clang/Rewrite/Core/DeltaTree.h b/include/clang/Rewrite/Core/DeltaTree.h
index 248f2a0..fbffb38 100644
--- a/include/clang/Rewrite/Core/DeltaTree.h
+++ b/include/clang/Rewrite/Core/DeltaTree.h
@@ -27,7 +27,7 @@
   /// as well, without traversing the whole tree.
   class DeltaTree {
     void *Root;    // "DeltaTreeNode *"
-    void operator=(const DeltaTree &) LLVM_DELETED_FUNCTION;
+    void operator=(const DeltaTree &) = delete;
   public:
     DeltaTree();
 
diff --git a/include/clang/Rewrite/Core/RewriteRope.h b/include/clang/Rewrite/Core/RewriteRope.h
index 1c6f3eb..5002554 100644
--- a/include/clang/Rewrite/Core/RewriteRope.h
+++ b/include/clang/Rewrite/Core/RewriteRope.h
@@ -136,7 +136,7 @@
 
   class RopePieceBTree {
     void /*RopePieceBTreeNode*/ *Root;
-    void operator=(const RopePieceBTree &) LLVM_DELETED_FUNCTION;
+    void operator=(const RopePieceBTree &) = delete;
   public:
     RopePieceBTree();
     RopePieceBTree(const RopePieceBTree &RHS);
diff --git a/include/clang/Rewrite/Core/TokenRewriter.h b/include/clang/Rewrite/Core/TokenRewriter.h
index 598477f..0f71e81 100644
--- a/include/clang/Rewrite/Core/TokenRewriter.h
+++ b/include/clang/Rewrite/Core/TokenRewriter.h
@@ -43,8 +43,8 @@
     ///
     std::unique_ptr<ScratchBuffer> ScratchBuf;
 
-    TokenRewriter(const TokenRewriter &) LLVM_DELETED_FUNCTION;
-    void operator=(const TokenRewriter &) LLVM_DELETED_FUNCTION;
+    TokenRewriter(const TokenRewriter &) = delete;
+    void operator=(const TokenRewriter &) = delete;
   public:
     /// TokenRewriter - This creates a TokenRewriter for the file with the
     /// specified FileID.
diff --git a/include/clang/Rewrite/Frontend/ASTConsumers.h b/include/clang/Rewrite/Frontend/ASTConsumers.h
index 8a822ed..c9df889 100644
--- a/include/clang/Rewrite/Frontend/ASTConsumers.h
+++ b/include/clang/Rewrite/Frontend/ASTConsumers.h
@@ -15,7 +15,6 @@
 #define LLVM_CLANG_REWRITE_FRONTEND_ASTCONSUMERS_H
 
 #include "clang/Basic/LLVM.h"
-
 #include <memory>
 #include <string>
 
diff --git a/include/clang/Sema/AttributeList.h b/include/clang/Sema/AttributeList.h
index c8e8625..58b1b9e 100644
--- a/include/clang/Sema/AttributeList.h
+++ b/include/clang/Sema/AttributeList.h
@@ -204,10 +204,10 @@
     return *reinterpret_cast<const PropertyData*>(this + 1);
   }
 
-  AttributeList(const AttributeList &) LLVM_DELETED_FUNCTION;
-  void operator=(const AttributeList &) LLVM_DELETED_FUNCTION;
-  void operator delete(void *) LLVM_DELETED_FUNCTION;
-  ~AttributeList() LLVM_DELETED_FUNCTION;
+  AttributeList(const AttributeList &) = delete;
+  void operator=(const AttributeList &) = delete;
+  void operator delete(void *) = delete;
+  ~AttributeList() = delete;
 
   size_t allocated_size() const;
 
@@ -670,7 +670,7 @@
     : pool(factory), list(nullptr) {
   }
 
-  ParsedAttributes(const ParsedAttributes &) LLVM_DELETED_FUNCTION;
+  ParsedAttributes(const ParsedAttributes &) = delete;
 
   AttributePool &getPool() const { return pool; }
 
@@ -822,6 +822,7 @@
   ExpectedFunctionMethodOrClass,
   ExpectedFunctionMethodOrParameter,
   ExpectedClass,
+  ExpectedEnum,
   ExpectedVariable,
   ExpectedMethod,
   ExpectedVariableFunctionOrLabel,
@@ -842,8 +843,10 @@
   ExpectedFunctionVariableOrClass,
   ExpectedObjectiveCProtocol,
   ExpectedFunctionGlobalVarMethodOrProperty,
+  ExpectedStructOrUnionOrTypedef,
   ExpectedStructOrTypedef,
-  ExpectedObjectiveCInterfaceOrProtocol
+  ExpectedObjectiveCInterfaceOrProtocol,
+  ExpectedKernelFunction
 };
 
 }  // end namespace clang
diff --git a/include/clang/Sema/CodeCompleteConsumer.h b/include/clang/Sema/CodeCompleteConsumer.h
index 92a4e9a..647eb8b 100644
--- a/include/clang/Sema/CodeCompleteConsumer.h
+++ b/include/clang/Sema/CodeCompleteConsumer.h
@@ -17,6 +17,7 @@
 #include "clang/AST/CanonicalType.h"
 #include "clang/AST/Type.h"
 #include "clang/Sema/CodeCompleteOptions.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Allocator.h"
@@ -440,8 +441,8 @@
   /// entity being completed by this result.
   const char *BriefComment;
   
-  CodeCompletionString(const CodeCompletionString &) LLVM_DELETED_FUNCTION;
-  void operator=(const CodeCompletionString &) LLVM_DELETED_FUNCTION;
+  CodeCompletionString(const CodeCompletionString &) = delete;
+  void operator=(const CodeCompletionString &) = delete;
 
   CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
                        unsigned Priority, CXAvailabilityKind Availability,
@@ -885,7 +886,8 @@
     CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
                                                 Sema &S,
                                       CodeCompletionAllocator &Allocator,
-                                      CodeCompletionTUInfo &CCTUInfo) const;
+                                      CodeCompletionTUInfo &CCTUInfo,
+                                      bool IncludeBriefComments) const;
   };
 
   CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
diff --git a/include/clang/Sema/DeclSpec.h b/include/clang/Sema/DeclSpec.h
index 43fcde1..76ccb1d 100644
--- a/include/clang/Sema/DeclSpec.h
+++ b/include/clang/Sema/DeclSpec.h
@@ -57,7 +57,7 @@
 /// These can be in 3 states:
 ///   1) Not present, identified by isEmpty()
 ///   2) Present, identified by isNotEmpty()
-///      2.a) Valid, idenified by isValid()
+///      2.a) Valid, identified by isValid()
 ///      2.b) Invalid, identified by isInvalid().
 ///
 /// isSet() is deprecated because it mostly corresponded to "valid" but was
@@ -407,8 +407,8 @@
     return (T == TST_typeofExpr || T == TST_decltype);
   }
 
-  DeclSpec(const DeclSpec &) LLVM_DELETED_FUNCTION;
-  void operator=(const DeclSpec &) LLVM_DELETED_FUNCTION;
+  DeclSpec(const DeclSpec &) = delete;
+  void operator=(const DeclSpec &) = delete;
 public:
   static bool isDeclRep(TST T) {
     return (T == TST_enum || T == TST_struct ||
@@ -845,8 +845,8 @@
 /// \brief Represents a C++ unqualified-id that has been parsed. 
 class UnqualifiedId {
 private:
-  UnqualifiedId(const UnqualifiedId &Other) LLVM_DELETED_FUNCTION;
-  const UnqualifiedId &operator=(const UnqualifiedId &) LLVM_DELETED_FUNCTION;
+  UnqualifiedId(const UnqualifiedId &Other) = delete;
+  const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
 
 public:
   /// \brief Describes the kind of unqualified-id parsed.
@@ -1070,6 +1070,12 @@
   /// EndLoc - If valid, the place where this chunck ends.
   SourceLocation EndLoc;
 
+  SourceRange getSourceRange() const {
+    if (EndLoc.isInvalid())
+      return SourceRange(Loc, Loc);
+    return SourceRange(Loc, EndLoc);
+  }
+
   struct TypeInfoCommon {
     AttributeList *AttrList;
   };
@@ -1493,7 +1499,8 @@
                                           SourceLocation Loc) {
     DeclaratorChunk I;
     I.Kind          = MemberPointer;
-    I.Loc           = Loc;
+    I.Loc           = SS.getBeginLoc();
+    I.EndLoc        = Loc;
     I.Mem.TypeQuals = TypeQuals;
     I.Mem.AttrList  = nullptr;
     new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
@@ -1916,6 +1923,14 @@
     return DeclTypeInfo[i];
   }
 
+  typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
+  typedef llvm::iterator_range<type_object_iterator> type_object_range;
+
+  /// Returns the range of type objects, from the identifier outwards.
+  type_object_range type_objects() const {
+    return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
+  }
+
   void DropFirstTypeObject() {
     assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
     DeclTypeInfo.front().destroy();
diff --git a/include/clang/Sema/DelayedDiagnostic.h b/include/clang/Sema/DelayedDiagnostic.h
index 7fd6779..e19d111 100644
--- a/include/clang/Sema/DelayedDiagnostic.h
+++ b/include/clang/Sema/DelayedDiagnostic.h
@@ -240,8 +240,8 @@
   const DelayedDiagnosticPool *Parent;
   SmallVector<DelayedDiagnostic, 4> Diagnostics;
 
-  DelayedDiagnosticPool(const DelayedDiagnosticPool &) LLVM_DELETED_FUNCTION;
-  void operator=(const DelayedDiagnosticPool &) LLVM_DELETED_FUNCTION;
+  DelayedDiagnosticPool(const DelayedDiagnosticPool &) = delete;
+  void operator=(const DelayedDiagnosticPool &) = delete;
 public:
   DelayedDiagnosticPool(const DelayedDiagnosticPool *parent) : Parent(parent) {}
   ~DelayedDiagnosticPool() {
diff --git a/include/clang/Sema/Initialization.h b/include/clang/Sema/Initialization.h
index 9f342b2..6110d22 100644
--- a/include/clang/Sema/Initialization.h
+++ b/include/clang/Sema/Initialization.h
@@ -921,7 +921,7 @@
   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
   
   /// \brief Determine whether the initialization sequence is valid.
-  LLVM_EXPLICIT operator bool() const { return !Failed(); }
+  explicit operator bool() const { return !Failed(); }
 
   /// \brief Determine whether the initialization sequence is invalid.
   bool Failed() const { return SequenceKind == FailedSequence; }
diff --git a/include/clang/Sema/Lookup.h b/include/clang/Sema/Lookup.h
index 1c6c7bb..8ba78be 100644
--- a/include/clang/Sema/Lookup.h
+++ b/include/clang/Sema/Lookup.h
@@ -735,22 +735,18 @@
   }
 
   class iterator
-      : public std::iterator<std::forward_iterator_tag, NamedDecl *> {
-    typedef llvm::DenseMap<NamedDecl*,NamedDecl*>::iterator inner_iterator;
-    inner_iterator iter;
-
+      : public llvm::iterator_adaptor_base<
+            iterator, llvm::DenseMap<NamedDecl *, NamedDecl *>::iterator,
+            std::forward_iterator_tag, NamedDecl *> {
     friend class ADLResult;
-    iterator(const inner_iterator &iter) : iter(iter) {}
+
+    iterator(llvm::DenseMap<NamedDecl *, NamedDecl *>::iterator Iter)
+        : iterator_adaptor_base(std::move(Iter)) {}
+
   public:
     iterator() {}
 
-    iterator &operator++() { ++iter; return *this; }
-    iterator operator++(int) { return iterator(iter++); }
-
-    value_type operator*() const { return iter->second; }
-
-    bool operator==(const iterator &other) const { return iter == other.iter; }
-    bool operator!=(const iterator &other) const { return iter != other.iter; }
+    value_type operator*() const { return I->second; }
   };
 
   iterator begin() { return iterator(Decls.begin()); }
diff --git a/include/clang/Sema/ObjCMethodList.h b/include/clang/Sema/ObjCMethodList.h
index 956e088..b618e38 100644
--- a/include/clang/Sema/ObjCMethodList.h
+++ b/include/clang/Sema/ObjCMethodList.h
@@ -20,22 +20,37 @@
 
 class ObjCMethodDecl;
 
-/// ObjCMethodList - a linked list of methods with different signatures.
+/// \brief a linked list of methods with the same selector name but different
+/// signatures.
 struct ObjCMethodList {
-  ObjCMethodDecl *Method;
-  /// \brief count of methods with same signature.
-  unsigned Count;
+  // NOTE: If you add any members to this struct, make sure to serialize them.
+  /// \brief If there is more than one decl with this signature.
+  llvm::PointerIntPair<ObjCMethodDecl *, 1> MethodAndHasMoreThanOneDecl;
   /// \brief The next list object and 2 bits for extra info.
   llvm::PointerIntPair<ObjCMethodList *, 2> NextAndExtraBits;
 
-  ObjCMethodList() : Method(nullptr), Count(0) { }
-  ObjCMethodList(ObjCMethodDecl *M, unsigned count, ObjCMethodList *C)
-    : Method(M), Count(count), NextAndExtraBits(C, 0) { }
+  ObjCMethodList() { }
+  ObjCMethodList(ObjCMethodDecl *M)
+      : MethodAndHasMoreThanOneDecl(M, 0) {}
 
   ObjCMethodList *getNext() const { return NextAndExtraBits.getPointer(); }
   unsigned getBits() const { return NextAndExtraBits.getInt(); }
   void setNext(ObjCMethodList *L) { NextAndExtraBits.setPointer(L); }
   void setBits(unsigned B) { NextAndExtraBits.setInt(B); }
+
+  ObjCMethodDecl *getMethod() const {
+    return MethodAndHasMoreThanOneDecl.getPointer();
+  }
+  void setMethod(ObjCMethodDecl *M) {
+    return MethodAndHasMoreThanOneDecl.setPointer(M);
+  }
+
+  bool hasMoreThanOneDecl() const {
+    return MethodAndHasMoreThanOneDecl.getInt();
+  }
+  void setHasMoreThanOneDecl(bool B) {
+    return MethodAndHasMoreThanOneDecl.setInt(B);
+  }
 };
 
 }
diff --git a/include/clang/Sema/Overload.h b/include/clang/Sema/Overload.h
index 41dcf97..2007dcb 100644
--- a/include/clang/Sema/Overload.h
+++ b/include/clang/Sema/Overload.h
@@ -553,6 +553,17 @@
     /// conversion.
     ovl_fail_trivial_conversion,
 
+    /// This conversion candidate was not considered because it is
+    /// an illegal instantiation of a constructor temploid: it is
+    /// callable with one argument, we only have one argument, and
+    /// its first parameter type is exactly the type of the class.
+    ///
+    /// Defining such a constructor directly is illegal, and
+    /// template-argument deduction is supposed to ignore such
+    /// instantiations, but we can still get one with the right
+    /// kind of implicit instantiation.
+    ovl_fail_illegal_constructor,
+
     /// This conversion candidate is not viable because its result
     /// type is not implicitly convertible to the desired type.
     ovl_fail_bad_final_conversion,
@@ -707,8 +718,8 @@
     llvm::AlignedCharArray<llvm::AlignOf<ImplicitConversionSequence>::Alignment,
                            16 * sizeof(ImplicitConversionSequence)> InlineSpace;
 
-    OverloadCandidateSet(const OverloadCandidateSet &) LLVM_DELETED_FUNCTION;
-    void operator=(const OverloadCandidateSet &) LLVM_DELETED_FUNCTION;
+    OverloadCandidateSet(const OverloadCandidateSet &) = delete;
+    void operator=(const OverloadCandidateSet &) = delete;
 
     void destroyCandidates();
 
diff --git a/include/clang/Sema/Ownership.h b/include/clang/Sema/Ownership.h
index 8031562..8acf9e8 100644
--- a/include/clang/Sema/Ownership.h
+++ b/include/clang/Sema/Ownership.h
@@ -79,7 +79,7 @@
       Ptr = Traits::getAsVoidPointer(P);
     }
 
-    LLVM_EXPLICIT operator bool() const { return Ptr != nullptr; }
+    explicit operator bool() const { return Ptr != nullptr; }
 
     void *getAsOpaquePtr() const { return Ptr; }
     static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }
diff --git a/include/clang/Sema/Scope.h b/include/clang/Sema/Scope.h
index 97e447d..cc6d9cc 100644
--- a/include/clang/Sema/Scope.h
+++ b/include/clang/Sema/Scope.h
@@ -115,8 +115,14 @@
     /// This scope corresponds to an enum.
     EnumScope = 0x40000,
 
-    /// This scope corresponds to a SEH try.
+    /// This scope corresponds to an SEH try.
     SEHTryScope = 0x80000,
+
+    /// This scope corresponds to an SEH except.
+    SEHExceptScope = 0x100000,
+
+    /// We are currently in the filter expression of an SEH except block.
+    SEHFilterScope = 0x200000,
   };
 private:
   /// The parent scope for this scope.  This is null for the translation-unit
@@ -407,6 +413,9 @@
   /// \brief Determine whether this scope is a SEH '__try' block.
   bool isSEHTryScope() const { return getFlags() & Scope::SEHTryScope; }
 
+  /// \brief Determine whether this scope is a SEH '__except' block.
+  bool isSEHExceptScope() const { return getFlags() & Scope::SEHExceptScope; }
+
   /// containedInPrototypeScope - Return true if this or a parent scope
   /// is a FunctionPrototypeScope.
   bool containedInPrototypeScope() const;
diff --git a/include/clang/Sema/ScopeInfo.h b/include/clang/Sema/ScopeInfo.h
index d63b734..ec8e56b 100644
--- a/include/clang/Sema/ScopeInfo.h
+++ b/include/clang/Sema/ScopeInfo.h
@@ -124,6 +124,12 @@
   /// false if there is an invocation of an initializer on 'self'.
   bool ObjCWarnForNoInitDelegation;
 
+  /// First C++ 'try' statement in the current function.
+  SourceLocation FirstCXXTryLoc;
+
+  /// First SEH '__try' statement in the current function.
+  SourceLocation FirstSEHTryLoc;
+
   /// \brief Used to determine if errors occurred in this function or block.
   DiagnosticErrorTrap ErrorTrap;
 
@@ -321,6 +327,16 @@
     HasDroppedStmt = true;
   }
 
+  void setHasCXXTry(SourceLocation TryLoc) {
+    setHasBranchProtectedScope();
+    FirstCXXTryLoc = TryLoc;
+  }
+
+  void setHasSEHTry(SourceLocation TryLoc) {
+    setHasBranchProtectedScope();
+    FirstSEHTryLoc = TryLoc;
+  }
+
   bool NeedsScopeChecking() const {
     return !HasDroppedStmt &&
         (HasIndirectGoto ||
diff --git a/include/clang/Sema/Sema.h b/include/clang/Sema/Sema.h
index 8b13b9d..712e0ce 100644
--- a/include/clang/Sema/Sema.h
+++ b/include/clang/Sema/Sema.h
@@ -199,6 +199,11 @@
   class TemplateDeductionInfo;
 }
 
+namespace threadSafety {
+  class BeforeSet;
+  void threadSafetyCleanup(BeforeSet* Cache);
+}
+
 // FIXME: No way to easily map from TemplateTypeParmTypes to
 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
@@ -206,8 +211,8 @@
 
 /// Sema - This implements semantic analysis and AST building for C.
 class Sema {
-  Sema(const Sema &) LLVM_DELETED_FUNCTION;
-  void operator=(const Sema &) LLVM_DELETED_FUNCTION;
+  Sema(const Sema &) = delete;
+  void operator=(const Sema &) = delete;
 
   ///\brief Source of additional semantic information.
   ExternalSemaSource *ExternalSource;
@@ -458,12 +463,11 @@
   /// cycle detection at the end of the TU.
   DelegatingCtorDeclsType DelegatingCtorDecls;
 
-  /// \brief All the overriding destructors seen during a class definition
-  /// (there could be multiple due to nested classes) that had their exception
-  /// spec checks delayed, plus the overridden destructor.
-  SmallVector<std::pair<const CXXDestructorDecl*,
-                              const CXXDestructorDecl*>, 2>
-      DelayedDestructorExceptionSpecChecks;
+  /// \brief All the overriding functions seen during a class definition
+  /// that had their exception spec checks delayed, plus the overridden
+  /// function.
+  SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
+    DelayedExceptionSpecChecks;
 
   /// \brief All the members seen during a class definition which were both
   /// explicitly defaulted and had explicitly-specified exception
@@ -1252,7 +1256,7 @@
   static QualType getPrintable(QualType T) { return T; }
   static SourceRange getPrintable(SourceRange R) { return R; }
   static SourceRange getPrintable(SourceLocation L) { return L; }
-  static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); }
+  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
 
   template<typename T1>
@@ -1400,7 +1404,10 @@
                              const CXXScopeSpec &SS, QualType T);
 
   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
-  QualType BuildDecltypeType(Expr *E, SourceLocation Loc);
+  /// If AsUnevaluated is false, E is treated as though it were an evaluated
+  /// context, such as when building a type for decltype(auto).
+  QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
+                             bool AsUnevaluated = true);
   QualType BuildUnaryTransformType(QualType BaseType,
                                    UnaryTransformType::UTTKind UKind,
                                    SourceLocation Loc);
@@ -2006,6 +2013,13 @@
                               int FirstArg, unsigned AttrSpellingListIndex);
   SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
                                 unsigned AttrSpellingListIndex);
+  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
+                                          IdentifierInfo *Ident,
+                                          unsigned AttrSpellingListIndex);
+  MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
+                                unsigned AttrSpellingListIndex);
+  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
+                                          unsigned AttrSpellingListIndex);
 
   /// \brief Describes the kind of merge to perform for availability
   /// attributes (including "deprecated", "unavailable", and "availability").
@@ -2149,6 +2163,8 @@
   };
   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
                                               llvm::APSInt &Value, CCEKind CCE);
+  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
+                                              APValue &Value, CCEKind CCE);
 
   /// \brief Abstract base class used to perform a contextual implicit
   /// conversion from an expression to any type passing a filter.
@@ -2268,8 +2284,9 @@
   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
                       ArrayRef<Expr *> Args,
                       OverloadCandidateSet &CandidateSet,
+                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
                       bool SuppressUserConversions = false,
-                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
+                      bool PartialOverloading = false);
   void AddMethodCandidate(DeclAccessPair FoundDecl,
                           QualType ObjectType,
                           Expr::Classification ObjectClassification,
@@ -2282,7 +2299,8 @@
                           Expr::Classification ObjectClassification,
                           ArrayRef<Expr *> Args,
                           OverloadCandidateSet& CandidateSet,
-                          bool SuppressUserConversions = false);
+                          bool SuppressUserConversions = false,
+                          bool PartialOverloading = false);
   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
                                   DeclAccessPair FoundDecl,
                                   CXXRecordDecl *ActingContext,
@@ -2291,13 +2309,15 @@
                                   Expr::Classification ObjectClassification,
                                   ArrayRef<Expr *> Args,
                                   OverloadCandidateSet& CandidateSet,
-                                  bool SuppressUserConversions = false);
+                                  bool SuppressUserConversions = false,
+                                  bool PartialOverloading = false);
   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
                                     DeclAccessPair FoundDecl,
                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
                                     ArrayRef<Expr *> Args,
                                     OverloadCandidateSet& CandidateSet,
-                                    bool SuppressUserConversions = false);
+                                    bool SuppressUserConversions = false,
+                                    bool PartialOverloading = false);
   void AddConversionCandidate(CXXConversionDecl *Conversion,
                               DeclAccessPair FoundDecl,
                               CXXRecordDecl *ActingContext,
@@ -2623,7 +2643,7 @@
                              std::unique_ptr<CorrectionCandidateCallback> CCC,
                              DeclContext *MemberContext, bool EnteringContext,
                              const ObjCObjectPointerType *OPT,
-                             bool ErrorRecovery, bool &IsUnqualifiedLookup);
+                             bool ErrorRecovery);
 
 public:
   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
@@ -2645,6 +2665,8 @@
                   bool AllowBuiltinCreation = false);
   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
                            bool InUnqualifiedLookup = false);
+  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
+                           CXXScopeSpec &SS);
   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
                         bool AllowBuiltinCreation = false,
                         bool EnteringContext = false);
@@ -2976,10 +2998,7 @@
 
   /// \brief Record the typo correction failure and return an empty correction.
   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
-                                  bool RecordFailure = true,
-                                  bool IsUnqualifiedLookup = false) {
-    if (IsUnqualifiedLookup)
-      (void)UnqualifiedTyposCorrected[Typo];
+                                  bool RecordFailure = true) {
     if (RecordFailure)
       TypoCorrectionFailures[Typo].insert(TypoLoc);
     return TypoCorrection();
@@ -3098,6 +3117,18 @@
     Sema &S;
   };
 
+  /// An RAII helper that pops function a function scope on exit.
+  struct FunctionScopeRAII {
+    Sema &S;
+    bool Active;
+    FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
+    ~FunctionScopeRAII() {
+      if (Active)
+        S.PopFunctionScopeInfo();
+    }
+    void disable() { Active = false; }
+  };
+
   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
                                    SourceLocation StartLoc,
                                    SourceLocation EndLoc);
@@ -3305,6 +3336,10 @@
   void DiagnoseEmptyLoopBody(const Stmt *S,
                              const Stmt *PossibleBody);
 
+  /// Warn if a value is moved to itself.
+  void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
+                        SourceLocation OpLoc);
+
   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
     return DelayedDiagnostics.push(pool);
   }
@@ -3427,6 +3462,9 @@
                           TryCaptureKind Kind = TryCapture_Implicit,
                           SourceLocation EllipsisLoc = SourceLocation());
 
+  /// \brief Checks if the variable must be captured.
+  bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
+
   /// \brief Given a variable, determine the type that a reference to that
   /// variable will have in the given scope.
   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
@@ -3627,7 +3665,6 @@
     Scope *S;
     UnqualifiedId &Id;
     Decl *ObjCImpDecl;
-    bool HasTrailingLParen;
   };
 
   ExprResult BuildMemberReferenceExpr(
@@ -3666,8 +3703,7 @@
                                    CXXScopeSpec &SS,
                                    SourceLocation TemplateKWLoc,
                                    UnqualifiedId &Member,
-                                   Decl *ObjCImpDecl,
-                                   bool HasTrailingLParen);
+                                   Decl *ObjCImpDecl);
 
   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
@@ -4460,7 +4496,7 @@
   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
                                        QualType Param1,
                                        QualType Param2 = QualType(),
-                                       bool addMallocAttr = false);
+                                       bool addRestrictAttr = false);
 
   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
                                 DeclarationName Name, FunctionDecl* &Operator,
@@ -4525,8 +4561,6 @@
                                           ParsedType &ObjectType,
                                           bool &MayBePseudoDestructor);
 
-  ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr);
-
   ExprResult BuildPseudoDestructorExpr(Expr *Base,
                                        SourceLocation OpLoc,
                                        tok::TokenKind OpKind,
@@ -4534,8 +4568,7 @@
                                        TypeSourceInfo *ScopeType,
                                        SourceLocation CCLoc,
                                        SourceLocation TildeLoc,
-                                     PseudoDestructorTypeStorage DestroyedType,
-                                       bool HasTrailingLParen);
+                                     PseudoDestructorTypeStorage DestroyedType);
 
   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
                                        SourceLocation OpLoc,
@@ -4544,15 +4577,13 @@
                                        UnqualifiedId &FirstTypeName,
                                        SourceLocation CCLoc,
                                        SourceLocation TildeLoc,
-                                       UnqualifiedId &SecondTypeName,
-                                       bool HasTrailingLParen);
+                                       UnqualifiedId &SecondTypeName);
 
   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
                                        SourceLocation OpLoc,
                                        tok::TokenKind OpKind,
                                        SourceLocation TildeLoc,
-                                       const DeclSpec& DS,
-                                       bool HasTrailingLParen);
+                                       const DeclSpec& DS);
 
   /// MaybeCreateExprWithCleanups - If the current full-expression
   /// requires any cleanups, surround it with a ExprWithCleanups node.
@@ -4603,7 +4634,8 @@
   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
 
-  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD);
+  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
+                                       bool *CanCorrect = nullptr);
   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
 
   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
@@ -5148,8 +5180,6 @@
   // FIXME: I don't like this name.
   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
 
-  bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath);
-
   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
                                     SourceLocation Loc, SourceRange Range,
                                     CXXCastPath *BasePath = nullptr,
@@ -6152,14 +6182,16 @@
                                   unsigned NumExplicitlySpecified,
                                   FunctionDecl *&Specialization,
                                   sema::TemplateDeductionInfo &Info,
-           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr);
+           SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
+                                  bool PartialOverloading = false);
 
   TemplateDeductionResult
   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
                           TemplateArgumentListInfo *ExplicitTemplateArgs,
                           ArrayRef<Expr *> Args,
                           FunctionDecl *&Specialization,
-                          sema::TemplateDeductionInfo &Info);
+                          sema::TemplateDeductionInfo &Info,
+                          bool PartialOverloading = false);
 
   TemplateDeductionResult
   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
@@ -6573,10 +6605,10 @@
         ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
 
-    InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
+    InstantiatingTemplate(const InstantiatingTemplate&) = delete;
 
     InstantiatingTemplate&
-    operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION;
+    operator=(const InstantiatingTemplate&) = delete;
   };
 
   void PrintInstantiationStack();
@@ -6664,17 +6696,6 @@
   /// \brief The number of typos corrected by CorrectTypo.
   unsigned TyposCorrected;
 
-  typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
-    UnqualifiedTyposCorrectedMap;
-
-  /// \brief A cache containing the results of typo correction for unqualified
-  /// name lookup.
-  ///
-  /// The string is the string that we corrected to (which may be empty, if
-  /// there was no correction), while the boolean will be true when the
-  /// string represents a keyword.
-  UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
-
   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
 
@@ -6685,6 +6706,7 @@
 
   /// \brief Worker object for performing CFG-based warnings.
   sema::AnalysisBasedWarnings AnalysisWarnings;
+  threadSafety::BeforeSet *ThreadSafetyDeclCache;
 
   /// \brief An entity for which implicit template instantiation is required.
   ///
@@ -6702,12 +6724,17 @@
 
   class SavePendingInstantiationsAndVTableUsesRAII {
   public:
-    SavePendingInstantiationsAndVTableUsesRAII(Sema &S): S(S) {
+    SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
+        : S(S), Enabled(Enabled) {
+      if (!Enabled) return;
+
       SavedPendingInstantiations.swap(S.PendingInstantiations);
       SavedVTableUses.swap(S.VTableUses);
     }
 
     ~SavePendingInstantiationsAndVTableUsesRAII() {
+      if (!Enabled) return;
+
       // Restore the set of pending vtables.
       assert(S.VTableUses.empty() &&
              "VTableUses should be empty before it is discarded.");
@@ -6723,6 +6750,7 @@
     Sema &S;
     SmallVector<VTableUse, 16> SavedVTableUses;
     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
+    bool Enabled;
   };
 
   /// \brief The queue of implicit template instantiations that are required
@@ -7461,6 +7489,10 @@
   void DestroyDataSharingAttributesStack();
   ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
                                                    OpenMPClauseKind CKind);
+  /// \brief Checks if the specified variable is used in one of the private
+  /// clauses in OpenMP constructs.
+  bool IsOpenMPCapturedVar(VarDecl *VD);
+
 public:
   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
                                                     Expr *Op);
@@ -7949,6 +7981,12 @@
                                 Expr *SrcExpr, AssignmentAction Action,
                                 bool *Complained = nullptr);
 
+  /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
+  /// enum. If AllowMask is true, then we also allow the complement of a valid
+  /// value, to be used as a mask.
+  bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
+                         bool AllowMask) const;
+
   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
   /// integer not in the range of enum values.
   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
@@ -8291,9 +8329,6 @@
 
   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
 
-  bool CheckCUDATarget(CUDAFunctionTarget CallerTarget,
-                       CUDAFunctionTarget CalleeTarget);
-
   bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
 
   /// Given a implicit special member, infer its CUDA target from the
@@ -8379,6 +8414,8 @@
   void CodeCompleteTypeQualifiers(DeclSpec &DS);
   void CodeCompleteCase(Scope *S);
   void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
+  void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
+                               ArrayRef<Expr *> Args);
   void CodeCompleteInitializer(Scope *S, Decl *D);
   void CodeCompleteReturn(Scope *S);
   void CodeCompleteAfterIf(Scope *S);
@@ -8547,6 +8584,8 @@
     FST_Strftime,
     FST_Strfmon,
     FST_Kprintf,
+    FST_FreeBSDKPrintf,
+    FST_OSTrace,
     FST_Unknown
   };
   static FormatStringType GetFormatStringType(const FormatAttr *Format);
@@ -8697,6 +8736,16 @@
       DC = CatD->getClassInterface();
     return DC;
   }
+
+  /// \brief To be used for checking whether the arguments being passed to
+  /// function exceeds the number of parameters expected for it.
+  static bool TooManyArguments(size_t NumParams, size_t NumArgs,
+                               bool PartialOverloading = false) {
+    // We check whether we're just after a comma in code-completion.
+    if (NumArgs > 0 && PartialOverloading)
+      return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
+    return NumArgs > NumParams;
+  }
 };
 
 /// \brief RAII object that enters a new expression evaluation context.
diff --git a/include/clang/Sema/SemaInternal.h b/include/clang/Sema/SemaInternal.h
index 045bacf..005d882 100644
--- a/include/clang/Sema/SemaInternal.h
+++ b/include/clang/Sema/SemaInternal.h
@@ -101,7 +101,7 @@
                          DeclContext *MemberContext,
                          bool EnteringContext)
       : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
-        SemaRef(SemaRef), S(S),
+        SavedTCIndex(0), SemaRef(SemaRef), S(S),
         SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
         CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
         Result(SemaRef, TypoName, LookupKind),
@@ -187,6 +187,17 @@
            CurrentTCIndex >= ValidatedCorrections.size();
   }
 
+  /// \brief Save the current position in the correction stream (overwriting any
+  /// previously saved position).
+  void saveCurrentPosition() {
+    SavedTCIndex = CurrentTCIndex;
+  }
+
+  /// \brief Restore the saved position in the correction stream.
+  void restoreSavedPosition() {
+    CurrentTCIndex = SavedTCIndex;
+  }
+
   ASTContext &getContext() const { return SemaRef.Context; }
   const LookupResult &getLookupResult() const { return Result; }
 
@@ -267,6 +278,7 @@
 
   SmallVector<TypoCorrection, 4> ValidatedCorrections;
   size_t CurrentTCIndex;
+  size_t SavedTCIndex;
 
   Sema &SemaRef;
   Scope *S;
diff --git a/include/clang/Sema/Template.h b/include/clang/Sema/Template.h
index c08a5df..6c34e58 100644
--- a/include/clang/Sema/Template.h
+++ b/include/clang/Sema/Template.h
@@ -239,8 +239,8 @@
 
     // This class is non-copyable
     LocalInstantiationScope(
-      const LocalInstantiationScope &) LLVM_DELETED_FUNCTION;
-    void operator=(const LocalInstantiationScope &) LLVM_DELETED_FUNCTION;
+      const LocalInstantiationScope &) = delete;
+    void operator=(const LocalInstantiationScope &) = delete;
 
   public:
     LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope = false)
diff --git a/include/clang/Sema/TemplateDeduction.h b/include/clang/Sema/TemplateDeduction.h
index 8338d97..229eb71 100644
--- a/include/clang/Sema/TemplateDeduction.h
+++ b/include/clang/Sema/TemplateDeduction.h
@@ -44,8 +44,8 @@
   /// SFINAE while performing template argument deduction.
   SmallVector<PartialDiagnosticAt, 4> SuppressedDiagnostics;
 
-  TemplateDeductionInfo(const TemplateDeductionInfo &) LLVM_DELETED_FUNCTION;
-  void operator=(const TemplateDeductionInfo &) LLVM_DELETED_FUNCTION;
+  TemplateDeductionInfo(const TemplateDeductionInfo &) = delete;
+  void operator=(const TemplateDeductionInfo &) = delete;
 
 public:
   TemplateDeductionInfo(SourceLocation Loc)
@@ -91,9 +91,7 @@
     if (HasSFINAEDiagnostic)
       return;
     SuppressedDiagnostics.clear();
-    SuppressedDiagnostics.push_back(
-        std::make_pair(Loc, PartialDiagnostic::NullDiagnostic()));
-    SuppressedDiagnostics.back().second.swap(PD);
+    SuppressedDiagnostics.emplace_back(Loc, std::move(PD));
     HasSFINAEDiagnostic = true;
   }
 
@@ -102,9 +100,7 @@
                                PartialDiagnostic PD) {
     if (HasSFINAEDiagnostic)
       return;
-    SuppressedDiagnostics.push_back(
-        std::make_pair(Loc, PartialDiagnostic::NullDiagnostic()));
-    SuppressedDiagnostics.back().second.swap(PD);
+    SuppressedDiagnostics.emplace_back(Loc, std::move(PD));
   }
 
   /// \brief Iterator over the set of suppressed diagnostics.
@@ -252,8 +248,8 @@
   SourceLocation Loc;
 
   TemplateSpecCandidateSet(
-      const TemplateSpecCandidateSet &) LLVM_DELETED_FUNCTION;
-  void operator=(const TemplateSpecCandidateSet &) LLVM_DELETED_FUNCTION;
+      const TemplateSpecCandidateSet &) = delete;
+  void operator=(const TemplateSpecCandidateSet &) = delete;
 
   void destroyCandidates();
 
@@ -277,7 +273,7 @@
   /// \brief Add a new candidate with NumConversions conversion sequence slots
   /// to the overload set.
   TemplateSpecCandidate &addCandidate() {
-    Candidates.push_back(TemplateSpecCandidate());
+    Candidates.emplace_back();
     return Candidates.back();
   }
 
diff --git a/include/clang/Sema/TypoCorrection.h b/include/clang/Sema/TypoCorrection.h
index 922d0ff..958aab0 100644
--- a/include/clang/Sema/TypoCorrection.h
+++ b/include/clang/Sema/TypoCorrection.h
@@ -165,7 +165,7 @@
   }
 
   /// \brief Returns whether this TypoCorrection has a non-empty DeclarationName
-  LLVM_EXPLICIT operator bool() const { return bool(CorrectionName); }
+  explicit operator bool() const { return bool(CorrectionName); }
 
   /// \brief Mark this TypoCorrection as being a keyword.
   /// Since addCorrectionDeclsand setCorrectionDecl don't allow NULL to be
diff --git a/include/clang/Serialization/ASTBitCodes.h b/include/clang/Serialization/ASTBitCodes.h
index 8549583..ef5f1dd 100644
--- a/include/clang/Serialization/ASTBitCodes.h
+++ b/include/clang/Serialization/ASTBitCodes.h
@@ -35,7 +35,7 @@
     /// Version 4 of AST files also requires that the version control branch and
     /// revision match exactly, since there is no backward compatibility of
     /// AST files at this time.
-    const unsigned VERSION_MAJOR = 5;
+    const unsigned VERSION_MAJOR = 6;
 
     /// \brief AST file minor version number supported by this version of
     /// Clang.
@@ -291,7 +291,10 @@
       MODULE_MAP_FILE = 14,
 
       /// \brief Record code for the signature that identifiers this AST file.
-      SIGNATURE = 15
+      SIGNATURE = 15,
+
+      /// \brief Record code for the module build directory.
+      MODULE_DIRECTORY = 16,
     };
 
     /// \brief Record types that occur within the input-files block
@@ -1091,13 +1094,13 @@
     ///
     /// These constants describe the records that describe statements
     /// or expressions. These records  occur within type and declarations
-    /// block, so they begin with record values of 100.  Each constant 
+    /// block, so they begin with record values of 128.  Each constant 
     /// describes a record for a specific statement or expression class in the
     /// AST.
     enum StmtCode {
       /// \brief A marker record that indicates that we are at the end
       /// of an expression.
-      STMT_STOP = 100,
+      STMT_STOP = 128,
       /// \brief A NULL expression.
       STMT_NULL_PTR,
       /// \brief A reference to a previously [de]serialized Stmt record.
diff --git a/include/clang/Serialization/ASTReader.h b/include/clang/Serialization/ASTReader.h
index 1b0347e..27af999 100644
--- a/include/clang/Serialization/ASTReader.h
+++ b/include/clang/Serialization/ASTReader.h
@@ -153,6 +153,7 @@
   /// \returns true to indicate the header search options are invalid, or false
   /// otherwise.
   virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                       StringRef SpecificModuleCachePath,
                                        bool Complain) {
     return false;
   }
@@ -230,6 +231,7 @@
                              bool Complain) override;
 
   bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                               StringRef SpecificModuleCachePath,
                                bool Complain) override;
   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
                                bool Complain,
@@ -261,6 +263,9 @@
                              bool Complain) override;
   bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
                                std::string &SuggestedPredefines) override;
+  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                               StringRef SpecificModuleCachePath,
+                               bool Complain) override;
   void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override;
 
 private:
@@ -435,6 +440,12 @@
   llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16>
       PendingUpdateRecords;
 
+  enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded };
+
+  /// \brief The DefinitionData pointers that we faked up for class definitions
+  /// that we needed but hadn't loaded yet.
+  llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData;
+
   struct ReplacedDeclInfo {
     ModuleFile *Mod;
     uint64_t Offset;
@@ -1071,8 +1082,8 @@
     ASTReader &Reader;
     enum ReadingKind PrevKind;
 
-    ReadingKindTracker(const ReadingKindTracker &) LLVM_DELETED_FUNCTION;
-    void operator=(const ReadingKindTracker &) LLVM_DELETED_FUNCTION;
+    ReadingKindTracker(const ReadingKindTracker &) = delete;
+    void operator=(const ReadingKindTracker &) = delete;
 
   public:
     ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
@@ -1113,12 +1124,11 @@
   serialization::InputFile getInputFile(ModuleFile &F, unsigned ID,
                                         bool Complain = true);
 
-  /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
-  /// into account all the necessary relocations.
-  const FileEntry *getFileEntry(StringRef filename);
+public:
+  void ResolveImportedPath(ModuleFile &M, std::string &Filename);
+  static void ResolveImportedPath(std::string &Filename, StringRef Prefix);
 
-  void MaybeAddSystemRootToFilename(ModuleFile &M, std::string &Filename);
-
+private:
   struct ImportedModule {
     ModuleFile *Mod;
     ModuleFile *ImportedBy;
@@ -1141,7 +1151,7 @@
                                  const ModuleFile *ImportedBy,
                                  unsigned ClientLoadCapabilities);
   ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities);
-  bool ParseLineTable(ModuleFile &F, SmallVectorImpl<uint64_t> &Record);
+  bool ParseLineTable(ModuleFile &F, const RecordData &Record);
   bool ReadSourceManagerBlock(ModuleFile &F);
   llvm::BitstreamCursor &SLocCursorForID(int ID);
   SourceLocation getImportLocation(ModuleFile *F);
@@ -1213,66 +1223,38 @@
 
   /// \brief Returns (begin, end) pair for the preprocessed entities of a
   /// particular module.
-  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
-    getModulePreprocessedEntities(ModuleFile &Mod) const;
+  llvm::iterator_range<PreprocessingRecord::iterator>
+  getModulePreprocessedEntities(ModuleFile &Mod) const;
 
-  class ModuleDeclIterator {
+  class ModuleDeclIterator
+      : public llvm::iterator_adaptor_base<
+            ModuleDeclIterator, const serialization::LocalDeclID *,
+            std::random_access_iterator_tag, const Decl *, ptrdiff_t,
+            const Decl *, const Decl *> {
     ASTReader *Reader;
     ModuleFile *Mod;
-    const serialization::LocalDeclID *Pos;
 
   public:
-    typedef const Decl *value_type;
-    typedef value_type&         reference;
-    typedef value_type*         pointer;
-
-    ModuleDeclIterator() : Reader(nullptr), Mod(nullptr), Pos(nullptr) { }
+    ModuleDeclIterator()
+        : iterator_adaptor_base(nullptr), Reader(nullptr), Mod(nullptr) {}
 
     ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod,
                        const serialization::LocalDeclID *Pos)
-      : Reader(Reader), Mod(Mod), Pos(Pos) { }
+        : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {}
 
     value_type operator*() const {
-      return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *Pos));
+      return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I));
     }
+    value_type operator->() const { return **this; }
 
-    ModuleDeclIterator &operator++() {
-      ++Pos;
-      return *this;
-    }
-
-    ModuleDeclIterator operator++(int) {
-      ModuleDeclIterator Prev(*this);
-      ++Pos;
-      return Prev;
-    }
-
-    ModuleDeclIterator &operator--() {
-      --Pos;
-      return *this;
-    }
-
-    ModuleDeclIterator operator--(int) {
-      ModuleDeclIterator Prev(*this);
-      --Pos;
-      return Prev;
-    }
-
-    friend bool operator==(const ModuleDeclIterator &LHS,
-                           const ModuleDeclIterator &RHS) {
-      assert(LHS.Reader == RHS.Reader && LHS.Mod == RHS.Mod);
-      return LHS.Pos == RHS.Pos;
-    }
-
-    friend bool operator!=(const ModuleDeclIterator &LHS,
-                           const ModuleDeclIterator &RHS) {
-      assert(LHS.Reader == RHS.Reader && LHS.Mod == RHS.Mod);
-      return LHS.Pos != RHS.Pos;
+    bool operator==(const ModuleDeclIterator &RHS) const {
+      assert(Reader == RHS.Reader && Mod == RHS.Mod);
+      return I == RHS.I;
     }
   };
 
-  std::pair<ModuleDeclIterator, ModuleDeclIterator>
-    getModuleFileLevelDecls(ModuleFile &Mod);
+  llvm::iterator_range<ModuleDeclIterator>
+  getModuleFileLevelDecls(ModuleFile &Mod);
 
   void PassInterestingDeclsToConsumer();
   void PassInterestingDeclToConsumer(Decl *D);
@@ -1298,8 +1280,8 @@
   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
              StringRef Arg2 = StringRef());
 
-  ASTReader(const ASTReader &) LLVM_DELETED_FUNCTION;
-  void operator=(const ASTReader &) LLVM_DELETED_FUNCTION;
+  ASTReader(const ASTReader &) = delete;
+  void operator=(const ASTReader &) = delete;
 public:
   /// \brief Load the AST file and validate its contents against the given
   /// Preprocessor.
@@ -1519,7 +1501,8 @@
                                   FileManager &FileMgr,
                                   const LangOptions &LangOpts,
                                   const TargetOptions &TargetOpts,
-                                  const PreprocessorOptions &PPOpts);
+                                  const PreprocessorOptions &PPOpts,
+                                  std::string ExistingModuleCachePath);
 
   /// \brief Returns the suggested contents of the predefines buffer,
   /// which contains a (typically-empty) subset of the predefines
@@ -2045,6 +2028,9 @@
   // \brief Read a string
   static std::string ReadString(const RecordData &Record, unsigned &Idx);
 
+  // \brief Read a path
+  std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx);
+
   /// \brief Read a version tuple.
   static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
 
diff --git a/include/clang/Serialization/ASTWriter.h b/include/clang/Serialization/ASTWriter.h
index 20e9935..1d2fa55 100644
--- a/include/clang/Serialization/ASTWriter.h
+++ b/include/clang/Serialization/ASTWriter.h
@@ -111,7 +111,10 @@
 
   /// \brief The module we're currently writing, if any.
   Module *WritingModule;
-                    
+
+  /// \brief The base directory for any relative paths we emit.
+  std::string BaseDirectory;
+
   /// \brief Indicates when the AST writing is actively performing
   /// serialization, rather than just queueing updates.
   bool WritingAST;
@@ -457,13 +460,11 @@
                          StringRef isysroot, const std::string &OutputFile);
   void WriteInputFiles(SourceManager &SourceMgr,
                        HeaderSearchOptions &HSOpts,
-                       StringRef isysroot,
                        bool Modules);
   void WriteSourceManagerBlock(SourceManager &SourceMgr,
-                               const Preprocessor &PP,
-                               StringRef isysroot);
+                               const Preprocessor &PP);
   void WritePreprocessor(const Preprocessor &PP, bool IsModule);
-  void WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot);
+  void WriteHeaderSearch(const HeaderSearch &HS);
   void WritePreprocessorDetail(PreprocessingRecord &PPRec);
   void WriteSubmodules(Module *WritingModule);
                                         
@@ -530,6 +531,8 @@
   ASTWriter(llvm::BitstreamWriter &Stream);
   ~ASTWriter();
 
+  const LangOptions &getLangOpts() const;
+
   /// \brief Write a precompiled header for the given semantic analysis.
   ///
   /// \param SemaRef a reference to the semantic analysis object that processed
@@ -539,7 +542,8 @@
   /// writing a precompiled header.
   ///
   /// \param isysroot if non-empty, write a relocatable file whose headers
-  /// are relative to the given system root.
+  /// are relative to the given system root. If we're writing a module, its
+  /// build directory will be used in preference to this if both are available.
   void WriteAST(Sema &SemaRef,
                 const std::string &OutputFile,
                 Module *WritingModule, StringRef isysroot,
@@ -686,6 +690,17 @@
   /// \brief Add a string to the given record.
   void AddString(StringRef Str, RecordDataImpl &Record);
 
+  /// \brief Convert a path from this build process into one that is appropriate
+  /// for emission in the module file.
+  bool PreparePathForOutput(SmallVectorImpl<char> &Path);
+
+  /// \brief Add a path to the given record.
+  void AddPath(StringRef Path, RecordDataImpl &Record);
+
+  /// \brief Emit the current record with the given path as a blob.
+  void EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
+                          StringRef Path);
+
   /// \brief Add a version tuple to the given record
   void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
 
diff --git a/include/clang/Serialization/ContinuousRangeMap.h b/include/clang/Serialization/ContinuousRangeMap.h
index 5f8ae1f..244b01b 100644
--- a/include/clang/Serialization/ContinuousRangeMap.h
+++ b/include/clang/Serialization/ContinuousRangeMap.h
@@ -109,8 +109,8 @@
   class Builder {
     ContinuousRangeMap &Self;
     
-    Builder(const Builder&) LLVM_DELETED_FUNCTION;
-    Builder &operator=(const Builder&) LLVM_DELETED_FUNCTION;
+    Builder(const Builder&) = delete;
+    Builder &operator=(const Builder&) = delete;
     
   public:
     explicit Builder(ContinuousRangeMap &Self) : Self(Self) { }
diff --git a/include/clang/Serialization/GlobalModuleIndex.h b/include/clang/Serialization/GlobalModuleIndex.h
index d8a57be..640c7bb 100644
--- a/include/clang/Serialization/GlobalModuleIndex.h
+++ b/include/clang/Serialization/GlobalModuleIndex.h
@@ -118,8 +118,8 @@
   explicit GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer,
                              llvm::BitstreamCursor Cursor);
 
-  GlobalModuleIndex(const GlobalModuleIndex &) LLVM_DELETED_FUNCTION;
-  GlobalModuleIndex &operator=(const GlobalModuleIndex &) LLVM_DELETED_FUNCTION;
+  GlobalModuleIndex(const GlobalModuleIndex &) = delete;
+  GlobalModuleIndex &operator=(const GlobalModuleIndex &) = delete;
 
 public:
   ~GlobalModuleIndex();
diff --git a/include/clang/Serialization/Module.h b/include/clang/Serialization/Module.h
index f6889cf..3eec83c 100644
--- a/include/clang/Serialization/Module.h
+++ b/include/clang/Serialization/Module.h
@@ -125,6 +125,9 @@
   /// \brief The name of the module.
   std::string ModuleName;
 
+  /// \brief The base directory of the module.
+  std::string BaseDirectory;
+
   std::string getTimestampFilename() const {
     return FileName + ".timestamp";
   }
@@ -203,7 +206,7 @@
   llvm::BitstreamCursor InputFilesCursor;
 
   /// \brief Offsets for all of the input file entries in the AST file.
-  const uint32_t *InputFileOffsets;
+  const uint64_t *InputFileOffsets;
 
   /// \brief The input files that have been loaded from this AST file.
   std::vector<InputFile> InputFilesLoaded;
diff --git a/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h b/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
index b03371c..8f8036e 100644
--- a/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ b/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -290,7 +290,7 @@
   }
 
   /// \brief Get the SourceRanges associated with the report.
-  virtual std::pair<ranges_iterator, ranges_iterator> getRanges();
+  virtual llvm::iterator_range<ranges_iterator> getRanges();
 
   /// \brief Add custom or predefined bug report visitors to this report.
   ///
diff --git a/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h b/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
index b4ab1ea..ce4dfb2 100644
--- a/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
+++ b/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
@@ -352,9 +352,9 @@
 
   std::vector<SourceRange> ranges;
 
-  PathDiagnosticPiece() LLVM_DELETED_FUNCTION;
-  PathDiagnosticPiece(const PathDiagnosticPiece &P) LLVM_DELETED_FUNCTION;
-  void operator=(const PathDiagnosticPiece &P) LLVM_DELETED_FUNCTION;
+  PathDiagnosticPiece() = delete;
+  PathDiagnosticPiece(const PathDiagnosticPiece &P) = delete;
+  void operator=(const PathDiagnosticPiece &P) = delete;
 
 protected:
   PathDiagnosticPiece(StringRef s, Kind k, DisplayHint hint = Below);
@@ -730,7 +730,7 @@
   PathDiagnosticLocation UniqueingLoc;
   const Decl *UniqueingDecl;
 
-  PathDiagnostic() LLVM_DELETED_FUNCTION;
+  PathDiagnostic() = delete;
 public:
   PathDiagnostic(StringRef CheckName, const Decl *DeclWithIssue,
                  StringRef bugtype, StringRef verboseDesc, StringRef shortDesc,
diff --git a/include/clang/StaticAnalyzer/Core/Checker.h b/include/clang/StaticAnalyzer/Core/Checker.h
index 8cc3514..099d763 100644
--- a/include/clang/StaticAnalyzer/Core/Checker.h
+++ b/include/clang/StaticAnalyzer/Core/Checker.h
@@ -25,10 +25,6 @@
 
 namespace check {
 
-struct _VoidCheck {
-  static void _register(void *checker, CheckerManager &mgr) { }
-};
-
 template <typename DECL>
 class ASTDecl {
   template <typename CHECKER>
@@ -476,49 +472,22 @@
   CheckerProgramPointTag(const CheckerBase *Checker, StringRef Msg);
 };
 
-template <typename CHECK1, typename CHECK2=check::_VoidCheck,
-          typename CHECK3=check::_VoidCheck, typename CHECK4=check::_VoidCheck,
-          typename CHECK5=check::_VoidCheck, typename CHECK6=check::_VoidCheck,
-          typename CHECK7=check::_VoidCheck, typename CHECK8=check::_VoidCheck,
-          typename CHECK9=check::_VoidCheck, typename CHECK10=check::_VoidCheck,
-          typename CHECK11=check::_VoidCheck,typename CHECK12=check::_VoidCheck,
-          typename CHECK13=check::_VoidCheck,typename CHECK14=check::_VoidCheck,
-          typename CHECK15=check::_VoidCheck,typename CHECK16=check::_VoidCheck,
-          typename CHECK17=check::_VoidCheck,typename CHECK18=check::_VoidCheck,
-          typename CHECK19=check::_VoidCheck,typename CHECK20=check::_VoidCheck,
-          typename CHECK21=check::_VoidCheck,typename CHECK22=check::_VoidCheck,
-          typename CHECK23=check::_VoidCheck,typename CHECK24=check::_VoidCheck>
-class Checker;
-
-template <>
-class Checker<check::_VoidCheck>
-  : public CheckerBase 
-{
-  virtual void anchor();
-public:
-  static void _register(void *checker, CheckerManager &mgr) { }
-};
-
-template <typename CHECK1, typename CHECK2, typename CHECK3, typename CHECK4,
-          typename CHECK5, typename CHECK6, typename CHECK7, typename CHECK8,
-          typename CHECK9, typename CHECK10,typename CHECK11,typename CHECK12,
-          typename CHECK13,typename CHECK14,typename CHECK15,typename CHECK16,
-          typename CHECK17,typename CHECK18,typename CHECK19,typename CHECK20,
-          typename CHECK21,typename CHECK22,typename CHECK23,typename CHECK24>
-class Checker
-    : public CHECK1,
-      public Checker<CHECK2, CHECK3, CHECK4, CHECK5, CHECK6, CHECK7,
-                     CHECK8, CHECK9, CHECK10,CHECK11,CHECK12,CHECK13,
-                     CHECK14,CHECK15,CHECK16,CHECK17,CHECK18,CHECK19,
-                     CHECK20,CHECK21,CHECK22,CHECK23,CHECK24> {
+template <typename CHECK1, typename... CHECKs>
+class Checker : public CHECK1, public CHECKs..., public CheckerBase {
 public:
   template <typename CHECKER>
   static void _register(CHECKER *checker, CheckerManager &mgr) {
     CHECK1::_register(checker, mgr);
-    Checker<CHECK2, CHECK3, CHECK4, CHECK5, CHECK6, CHECK7,
-            CHECK8, CHECK9, CHECK10,CHECK11,CHECK12,CHECK13,
-            CHECK14,CHECK15,CHECK16,CHECK17,CHECK18,CHECK19,
-            CHECK20,CHECK21,CHECK22,CHECK23,CHECK24>::_register(checker, mgr);
+    Checker<CHECKs...>::_register(checker, mgr);
+  }
+};
+
+template <typename CHECK1>
+class Checker<CHECK1> : public CHECK1, public CheckerBase {
+public:
+  template <typename CHECKER>
+  static void _register(CHECKER *checker, CheckerManager &mgr) {
+    CHECK1::_register(checker, mgr);
   }
 };
 
diff --git a/include/clang/StaticAnalyzer/Core/CheckerManager.h b/include/clang/StaticAnalyzer/Core/CheckerManager.h
index 30b0480..8a1a82b 100644
--- a/include/clang/StaticAnalyzer/Core/CheckerManager.h
+++ b/include/clang/StaticAnalyzer/Core/CheckerManager.h
@@ -47,71 +47,18 @@
 
 template <typename T> class CheckerFn;
 
-template <typename RET, typename P1, typename P2, typename P3, typename P4,
-          typename P5>
-class CheckerFn<RET(P1, P2, P3, P4, P5)> {
-  typedef RET (*Func)(void *, P1, P2, P3, P4, P5);
+template <typename RET, typename... Ps>
+class CheckerFn<RET(Ps...)> {
+  typedef RET (*Func)(void *, Ps...);
   Func Fn;
 public:
   CheckerBase *Checker;
   CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
-  RET operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) const {
-    return Fn(Checker, p1, p2, p3, p4, p5);
+  RET operator()(Ps... ps) const {
+    return Fn(Checker, ps...);
   }
 };
 
-template <typename RET, typename P1, typename P2, typename P3, typename P4>
-class CheckerFn<RET(P1, P2, P3, P4)> {
-  typedef RET (*Func)(void *, P1, P2, P3, P4);
-  Func Fn;
-public:
-  CheckerBase *Checker;
-  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
-  RET operator()(P1 p1, P2 p2, P3 p3, P4 p4) const { 
-    return Fn(Checker, p1, p2, p3, p4);
-  } 
-};
-
-template <typename RET, typename P1, typename P2, typename P3>
-class CheckerFn<RET(P1, P2, P3)> {
-  typedef RET (*Func)(void *, P1, P2, P3);
-  Func Fn;
-public:
-  CheckerBase *Checker;
-  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
-  RET operator()(P1 p1, P2 p2, P3 p3) const { return Fn(Checker, p1, p2, p3); } 
-};
-
-template <typename RET, typename P1, typename P2>
-class CheckerFn<RET(P1, P2)> {
-  typedef RET (*Func)(void *, P1, P2);
-  Func Fn;
-public:
-  CheckerBase *Checker;
-  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
-  RET operator()(P1 p1, P2 p2) const { return Fn(Checker, p1, p2); } 
-};
-
-template <typename RET, typename P1>
-class CheckerFn<RET(P1)> {
-  typedef RET (*Func)(void *, P1);
-  Func Fn;
-public:
-  CheckerBase *Checker;
-  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
-  RET operator()(P1 p1) const { return Fn(Checker, p1); } 
-};
-
-template <typename RET>
-class CheckerFn<RET()> {
-  typedef RET (*Func)(void *);
-  Func Fn;
-public:
-  CheckerBase *Checker;
-  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
-  RET operator()() const { return Fn(Checker); } 
-};
-
 /// \brief Describes the different reasons a pointer escapes
 /// during analysis.
 enum PointerEscapeKind {
diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 00deaa6..63b8631 100644
--- a/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -119,7 +119,7 @@
   const LocationContext *LCtx;
   llvm::PointerUnion<const Expr *, const Decl *> Origin;
 
-  void operator=(const CallEvent &) LLVM_DELETED_FUNCTION;
+  void operator=(const CallEvent &) = delete;
 
 protected:
   // This is user data for subclasses.
diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h b/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index 0dafd5f..77b8f2a 100644
--- a/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -103,8 +103,8 @@
                         ExplodedNode *Pred);
 
 private:
-  CoreEngine(const CoreEngine &) LLVM_DELETED_FUNCTION;
-  void operator=(const CoreEngine &) LLVM_DELETED_FUNCTION;
+  CoreEngine(const CoreEngine &) = delete;
+  void operator=(const CoreEngine &) = delete;
 
   ExplodedNode *generateCallExitBeginNode(ExplodedNode *N);
 
diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h b/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
index e819b88..ac4e452 100644
--- a/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ b/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -76,7 +76,7 @@
   typedef llvm::ImmutableMap<void*, void*>                 GenericDataMap;
 
 private:
-  void operator=(const ProgramState& R) LLVM_DELETED_FUNCTION;
+  void operator=(const ProgramState& R) = delete;
 
   friend class ProgramStateManager;
   friend class ExplodedGraph;
diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
index ef43fe0..642e11a 100644
--- a/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ b/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -203,8 +203,8 @@
 private:
   // We want calling these methods to be a compiler error since they are
   // tautologically false.
-  bool isUndef() const LLVM_DELETED_FUNCTION;
-  bool isValid() const LLVM_DELETED_FUNCTION;
+  bool isUndef() const = delete;
+  bool isValid() const = delete;
   
 protected:
   DefinedOrUnknownSVal() {}
@@ -236,9 +236,9 @@
 private:
   // We want calling these methods to be a compiler error since they are
   // tautologically true/false.
-  bool isUnknown() const LLVM_DELETED_FUNCTION;
-  bool isUnknownOrUndef() const LLVM_DELETED_FUNCTION;
-  bool isValid() const LLVM_DELETED_FUNCTION;
+  bool isUnknown() const = delete;
+  bool isUnknownOrUndef() const = delete;
+  bool isValid() const = delete;
 protected:
   DefinedSVal() {}
   explicit DefinedSVal(const void *d, bool isLoc, unsigned ValKind)
diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
index 5500c3c..a03b630 100644
--- a/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
+++ b/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
@@ -225,7 +225,7 @@
 
     bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
                        SVal val) override;
-    LLVM_EXPLICIT operator bool() { return First && Binding; }
+    explicit operator bool() { return First && Binding; }
     const MemRegion *getRegion() { return Binding; }
   };
 
diff --git a/include/clang/StaticAnalyzer/Frontend/FrontendActions.h b/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
index f18b8cc..36afb4b 100644
--- a/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
+++ b/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
@@ -11,8 +11,8 @@
 #define LLVM_CLANG_STATICANALYZER_FRONTEND_FRONTENDACTIONS_H
 
 #include "clang/Frontend/FrontendAction.h"
-#include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
 
 namespace clang {
 
diff --git a/include/clang/Tooling/ArgumentsAdjusters.h b/include/clang/Tooling/ArgumentsAdjusters.h
index 30bca9b..a92e021 100644
--- a/include/clang/Tooling/ArgumentsAdjusters.h
+++ b/include/clang/Tooling/ArgumentsAdjusters.h
@@ -7,74 +7,61 @@
 //
 //===----------------------------------------------------------------------===//
 //
-// This file declares base abstract class ArgumentsAdjuster and its descendants.
-// These classes are intended to modify command line arguments obtained from
-// a compilation database before they are used to run a frontend action.
+// This file declares typedef ArgumentsAdjuster and functions to create several
+// useful argument adjusters.
+// ArgumentsAdjusters modify command line arguments obtained from a compilation
+// database before they are used to run a frontend action.
 //
 //===----------------------------------------------------------------------===//
 
 #ifndef LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H
 #define LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H
 
+#include <functional>
 #include <string>
 #include <vector>
 
 namespace clang {
-
 namespace tooling {
 
 /// \brief A sequence of command line arguments.
 typedef std::vector<std::string> CommandLineArguments;
 
-/// \brief Abstract interface for a command line adjusters.
+/// \brief A prototype of a command line adjuster.
 ///
-/// This abstract interface describes a command line argument adjuster,
-/// which is responsible for command line arguments modification before
-/// the arguments are used to run a frontend action.
-class ArgumentsAdjuster {
-  virtual void anchor();
-public:
-  /// \brief Returns adjusted command line arguments.
-  ///
-  /// \param Args Input sequence of command line arguments.
-  ///
-  /// \returns Modified sequence of command line arguments.
-  virtual CommandLineArguments Adjust(const CommandLineArguments &Args) = 0;
-  virtual ~ArgumentsAdjuster() {}
-};
+/// Command line argument adjuster is responsible for command line arguments
+/// modification before the arguments are used to run a frontend action.
+typedef std::function<CommandLineArguments(const CommandLineArguments &)>
+    ArgumentsAdjuster;
 
-/// \brief Syntax check only command line adjuster.
-///
-/// This class implements ArgumentsAdjuster interface and converts input
-/// command line arguments to the "syntax check only" variant.
-class ClangSyntaxOnlyAdjuster : public ArgumentsAdjuster {
-  CommandLineArguments Adjust(const CommandLineArguments &Args) override;
-};
+/// \brief Gets an argument adjuster that converts input command line arguments
+/// to the "syntax check only" variant.
+ArgumentsAdjuster getClangSyntaxOnlyAdjuster();
 
-/// \brief An argument adjuster which removes output-related command line
+/// \brief Gets an argument adjuster which removes output-related command line
 /// arguments.
-class ClangStripOutputAdjuster : public ArgumentsAdjuster {
-  CommandLineArguments Adjust(const CommandLineArguments &Args) override;
-};
+ArgumentsAdjuster getClangStripOutputAdjuster();
 
-class InsertArgumentAdjuster : public ArgumentsAdjuster {
-public:
-  enum Position { BEGIN, END };
+enum class ArgumentInsertPosition { BEGIN, END };
 
-  InsertArgumentAdjuster(const CommandLineArguments &Extra, Position Pos)
-      : Extra(Extra), Pos(Pos) {}
+/// \brief Gets an argument adjuster which inserts \p Extra arguments in the
+/// specified position.
+ArgumentsAdjuster getInsertArgumentAdjuster(const CommandLineArguments &Extra,
+                                            ArgumentInsertPosition Pos);
 
-  InsertArgumentAdjuster(const char *Extra, Position Pos)
-      : Extra(1, std::string(Extra)), Pos(Pos) {}
+/// \brief Gets an argument adjuster which inserts an \p Extra argument in the
+/// specified position.
+ArgumentsAdjuster getInsertArgumentAdjuster(
+    const char *Extra,
+    ArgumentInsertPosition Pos = ArgumentInsertPosition::END);
 
-  CommandLineArguments Adjust(const CommandLineArguments &Args) override;
+/// \brief Gets an argument adjuster which adjusts the arguments in sequence
+/// with the \p First adjuster and then with the \p Second one.
+ArgumentsAdjuster combineAdjusters(ArgumentsAdjuster First,
+                                   ArgumentsAdjuster Second);
 
-private:
-  const CommandLineArguments Extra;
-  const Position Pos;
-};
-} // end namespace tooling
-} // end namespace clang
+} // namespace tooling
+} // namespace clang
 
 #endif // LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H
 
diff --git a/include/clang/Tooling/Tooling.h b/include/clang/Tooling/Tooling.h
index 89a4798..393cc1d 100644
--- a/include/clang/Tooling/Tooling.h
+++ b/include/clang/Tooling/Tooling.h
@@ -143,6 +143,10 @@
 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
                    const Twine &FileName = "input.cc");
 
+/// The first part of the pair is the filename, the second part the
+/// file-content.
+typedef std::vector<std::pair<std::string, std::string>> FileContentMappings;
+
 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and
 ///        with additional other flags.
 ///
@@ -152,9 +156,10 @@
 /// \param FileName The file name which 'Code' will be mapped as.
 ///
 /// \return - True if 'ToolAction' was successfully executed.
-bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
-                           const std::vector<std::string> &Args,
-                           const Twine &FileName = "input.cc");
+bool runToolOnCodeWithArgs(
+    clang::FrontendAction *ToolAction, const Twine &Code,
+    const std::vector<std::string> &Args, const Twine &FileName = "input.cc",
+    const FileContentMappings &VirtualMappedFiles = FileContentMappings());
 
 /// \brief Builds an AST for 'Code'.
 ///
@@ -269,7 +274,7 @@
   ///
   /// \param Adjuster An argument adjuster, which will be run on the output of
   ///        previous argument adjusters.
-  void appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster);
+  void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster);
 
   /// \brief Clear the command line arguments adjuster chain.
   void clearArgumentsAdjusters();
@@ -296,7 +301,7 @@
   // Contains a list of pairs (<file name>, <file content>).
   std::vector< std::pair<StringRef, StringRef> > MappedFileContents;
 
-  SmallVector<std::unique_ptr<ArgumentsAdjuster>, 2> ArgsAdjusters;
+  ArgumentsAdjuster ArgsAdjuster;
 
   DiagnosticConsumer *DiagConsumer;
 };
diff --git a/include/clang/module.modulemap b/include/clang/module.modulemap
index 5058d15..29fa008 100644
--- a/include/clang/module.modulemap
+++ b/include/clang/module.modulemap
@@ -2,8 +2,7 @@
   requires cplusplus
   umbrella "Analysis"
 
-  // This file is intended for repeated textual inclusion.
-  exclude header "Analysis/Analyses/ThreadSafetyOps.def"
+  textual header "Analysis/Analyses/ThreadSafetyOps.def"
 
   module * { export * }
 }
@@ -12,10 +11,9 @@
   requires cplusplus
   umbrella "AST"
 
-  // These files are intended for repeated textual inclusion.
-  exclude header "AST/BuiltinTypes.def"
-  exclude header "AST/TypeLocNodes.def"
-  exclude header "AST/TypeNodes.def"
+  textual header "AST/BuiltinTypes.def"
+  textual header "AST/TypeLocNodes.def"
+  textual header "AST/TypeNodes.def"
 
   module * { export * }
 }
@@ -26,33 +24,25 @@
   requires cplusplus
   umbrella "Basic"
 
-  // These files are intended for repeated textual inclusion.
-  exclude header "Basic/BuiltinsAArch64.def"
-  exclude header "Basic/BuiltinsARM64.def"
-  exclude header "Basic/BuiltinsARM.def"
-  exclude header "Basic/Builtins.def"
-  exclude header "Basic/BuiltinsHexagon.def"
-  exclude header "Basic/BuiltinsMips.def"
-  exclude header "Basic/BuiltinsNEON.def"
-  exclude header "Basic/BuiltinsNVPTX.def"
-  exclude header "Basic/BuiltinsPPC.def"
-  exclude header "Basic/BuiltinsR600.def"
-  exclude header "Basic/BuiltinsX86.def"
-  exclude header "Basic/BuiltinsXCore.def"
-  exclude header "Basic/BuiltinsLe64.def"
-  exclude header "Basic/DiagnosticOptions.def"
-  exclude header "Basic/LangOptions.def"
-  exclude header "Basic/OpenCLExtensions.def"
-  exclude header "Basic/OpenMPKinds.def"
-  exclude header "Basic/OperatorKinds.def"
-  exclude header "Basic/Sanitizers.def"
-  exclude header "Basic/TokenKinds.def"
-
-  // This file includes a header from Lex.
-  exclude header "Basic/PlistSupport.h"
-
-  // FIXME: This is logically a part of Basic, but has been put in the wrong place.
-  header "StaticAnalyzer/Core/AnalyzerOptions.h"
+  textual header "Basic/BuiltinsAArch64.def"
+  textual header "Basic/BuiltinsARM.def"
+  textual header "Basic/Builtins.def"
+  textual header "Basic/BuiltinsHexagon.def"
+  textual header "Basic/BuiltinsLe64.def"
+  textual header "Basic/BuiltinsMips.def"
+  textual header "Basic/BuiltinsNEON.def"
+  textual header "Basic/BuiltinsNVPTX.def"
+  textual header "Basic/BuiltinsPPC.def"
+  textual header "Basic/BuiltinsR600.def"
+  textual header "Basic/BuiltinsX86.def"
+  textual header "Basic/BuiltinsXCore.def"
+  textual header "Basic/DiagnosticOptions.def"
+  textual header "Basic/LangOptions.def"
+  textual header "Basic/OpenCLExtensions.def"
+  textual header "Basic/OpenMPKinds.def"
+  textual header "Basic/OperatorKinds.def"
+  textual header "Basic/Sanitizers.def"
+  textual header "Basic/TokenKinds.def"
 
   module * { export * }
 }
@@ -82,8 +72,7 @@
   requires cplusplus
   umbrella "Driver"
 
-  // This file is intended for repeated textual inclusion.
-  exclude header "Driver/Types.def"
+  textual header "Driver/Types.def"
 
   module * { export * }
 }
@@ -95,9 +84,8 @@
   requires cplusplus
   umbrella "Frontend"
 
-  // These files are intended for repeated textual inclusion.
-  exclude header "Frontend/CodeGenOptions.def"
-  exclude header "Frontend/LangStandards.def"
+  textual header "Frontend/CodeGenOptions.def"
+  textual header "Frontend/LangStandards.def"
 
   module * { export * }
 }
@@ -110,14 +98,25 @@
 module Clang_Sema { requires cplusplus umbrella "Sema" module * { export * } }
 module Clang_Serialization { requires cplusplus umbrella "Serialization" module * { export * } }
 
-module Clang_StaticAnalyzer {
+module Clang_StaticAnalyzer_Core {
   requires cplusplus
-  umbrella "StaticAnalyzer"
+  umbrella "StaticAnalyzer/Core"
 
-  // This file is intended for repeated textual inclusion.
-  exclude header "StaticAnalyzer/Core/Analyses.def"
+  textual header "StaticAnalyzer/Core/Analyses.def"
 
   module * { export * }
 }
 
+module Clang_StaticAnalyzer_Checkers {
+  requires cplusplus
+  umbrella "StaticAnalyzer/Checkers"
+  module * { export * }
+}
+
+module Clang_StaticAnalyzer_Frontend {
+  requires cplusplus
+  umbrella "StaticAnalyzer/Frontend"
+  module * { export * }
+}
+
 module Clang_Tooling { requires cplusplus umbrella "Tooling" module * { export * } }
diff --git a/lib/ARCMigrate/ObjCMT.cpp b/lib/ARCMigrate/ObjCMT.cpp
index af9c472..ddb802e 100644
--- a/lib/ARCMigrate/ObjCMT.cpp
+++ b/lib/ARCMigrate/ObjCMT.cpp
@@ -242,8 +242,13 @@
                                   const NSAPI &NS, edit::Commit &commit,
                                   const ParentMap *PMap) {
     if (!Msg || Msg->isImplicit() ||
-        Msg->getReceiverKind() != ObjCMessageExpr::Instance)
+        (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
+         Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
       return false;
+    if (const Expr *Receiver = Msg->getInstanceReceiver())
+      if (Receiver->getType()->isObjCBuiltinType())
+        return false;
+      
     const ObjCMethodDecl *Method = Msg->getMethodDecl();
     if (!Method)
       return false;
@@ -260,12 +265,17 @@
       return false;
     
     SourceRange MsgRange = Msg->getSourceRange();
+    bool ReceiverIsSuper =
+      (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
+    // for 'super' receiver is nullptr.
     const Expr *receiver = Msg->getInstanceReceiver();
-    bool NeedsParen = subscriptOperatorNeedsParens(receiver);
+    bool NeedsParen =
+      ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
     bool IsGetter = (Msg->getNumArgs() == 0);
     if (IsGetter) {
       // Find space location range between receiver expression and getter method.
-      SourceLocation BegLoc = receiver->getLocEnd();
+      SourceLocation BegLoc =
+        ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
       BegLoc = PP.getLocForEndOfToken(BegLoc);
       SourceLocation EndLoc = Msg->getSelectorLoc(0);
       SourceRange SpaceRange(BegLoc, EndLoc);
@@ -285,9 +295,8 @@
       commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
       commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
     } else {
-      SourceRange ReceiverRange = receiver->getSourceRange();
       if (NeedsParen)
-        commit.insertWrap("(", ReceiverRange, ")");
+        commit.insertWrap("(", receiver->getSourceRange(), ")");
       std::string PropertyDotString = ".";
       PropertyDotString += Prop->getName();
       PropertyDotString += " =";
@@ -295,10 +304,15 @@
       const Expr *RHS = Args[0];
       if (!RHS)
         return false;
-      SourceLocation BegLoc = ReceiverRange.getEnd();
+      SourceLocation BegLoc =
+        ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
       BegLoc = PP.getLocForEndOfToken(BegLoc);
       SourceLocation EndLoc = RHS->getLocStart();
       EndLoc = EndLoc.getLocWithOffset(-1);
+      const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
+      // Add a space after '=' if there is no space between RHS and '='
+      if (colon && colon[0] == ':')
+        PropertyDotString += " ";
       SourceRange Range(BegLoc, EndLoc);
       commit.replace(Range, PropertyDotString);
       // remove '[' ']'
@@ -610,7 +624,7 @@
       if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
         continue;
       HasAtleastOneRequiredProperty = true;
-      DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
+      DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
       if (R.size() == 0) {
         // Relax the rule and look into class's implementation for a synthesize
         // or dynamic declaration. Class is implementing a property coming from
@@ -641,7 +655,7 @@
         continue;
       if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
         continue;
-      DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
+      DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
       if (R.size() == 0)
         return false;
       bool match = false;
@@ -757,15 +771,39 @@
   return false;
 }
 
-static void rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
+static void rewriteToNSMacroDecl(ASTContext &Ctx,
+                                 const EnumDecl *EnumDcl,
                                 const TypedefDecl *TypedefDcl,
                                 const NSAPI &NS, edit::Commit &commit,
                                  bool IsNSIntegerType) {
-  std::string ClassString =
-    IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
+  QualType EnumUnderlyingT = EnumDcl->getPromotionType();
+  assert(!EnumUnderlyingT.isNull()
+         && "rewriteToNSMacroDecl - underlying enum type is null");
+  
+  PrintingPolicy Policy(Ctx.getPrintingPolicy());
+  std::string TypeString = EnumUnderlyingT.getAsString(Policy);
+  std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
+  ClassString += TypeString;
+  ClassString += ", ";
+  
   ClassString += TypedefDcl->getIdentifier()->getName();
   ClassString += ')';
-  SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
+  SourceLocation EndLoc;
+  if (EnumDcl->getIntegerTypeSourceInfo()) {
+    TypeSourceInfo *TSourceInfo = EnumDcl->getIntegerTypeSourceInfo();
+    TypeLoc TLoc = TSourceInfo->getTypeLoc();
+    EndLoc = TLoc.getLocEnd();
+    const char *lbrace = Ctx.getSourceManager().getCharacterData(EndLoc);
+    unsigned count = 0;
+    if (lbrace)
+      while (lbrace[count] != '{')
+        ++count;
+    if (count > 0)
+      EndLoc = EndLoc.getLocWithOffset(count-1);
+  }
+  else
+    EndLoc = EnumDcl->getLocStart();
+  SourceRange R(EnumDcl->getLocStart(), EndLoc);
   commit.replace(R, ClassString);
   // This is to remove spaces between '}' and typedef name.
   SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
@@ -887,7 +925,7 @@
                                            const EnumDecl *EnumDcl,
                                            const TypedefDecl *TypedefDcl) {
   if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
-      EnumDcl->isDeprecated() || EnumDcl->getIntegerTypeSourceInfo())
+      EnumDcl->isDeprecated())
     return false;
   if (!TypedefDcl) {
     if (NSIntegerTypedefed) {
@@ -921,7 +959,7 @@
         if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
           return false;
         edit::Commit commit(*Editor);
-        rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
+        rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
         Editor->commit(commit);
         return true;
       }
diff --git a/lib/ARCMigrate/PlistReporter.cpp b/lib/ARCMigrate/PlistReporter.cpp
index 53398b2..9a51690 100644
--- a/lib/ARCMigrate/PlistReporter.cpp
+++ b/lib/ARCMigrate/PlistReporter.cpp
@@ -100,16 +100,18 @@
 
     // Output the location of the bug.
     o << "  <key>location</key>\n";
-    EmitLocation(o, SM, LangOpts, D.getLocation(), FM, 2);
+    EmitLocation(o, SM, D.getLocation(), FM, 2);
 
     // Output the ranges (if any).
-    StoredDiagnostic::range_iterator RI = D.range_begin(), RE = D.range_end();
-
-    if (RI != RE) {
+    if (!D.getRanges().empty()) {
       o << "   <key>ranges</key>\n";
       o << "   <array>\n";
-      for (; RI != RE; ++RI)
-        EmitRange(o, SM, LangOpts, *RI, FM, 4);
+      for (auto &R : D.getRanges()) {
+        CharSourceRange ExpansionRange(SM.getExpansionRange(R.getAsRange()),
+                                       R.isTokenRange());
+        EmitRange(o, SM, Lexer::getAsCharRange(ExpansionRange, SM, LangOpts),
+                  FM, 4);
+      }
       o << "   </array>\n";
     }
 
diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp
index 1804c00..8a99162 100644
--- a/lib/AST/ASTContext.cpp
+++ b/lib/AST/ASTContext.cpp
@@ -682,6 +682,7 @@
   case TargetCXXABI::iOS:
   case TargetCXXABI::iOS64:
   case TargetCXXABI::GenericAArch64:
+  case TargetCXXABI::GenericMIPS:
   case TargetCXXABI::GenericItanium:
     return CreateItaniumCXXABI(*this);
   case TargetCXXABI::Microsoft:
@@ -699,9 +700,10 @@
       1, // opencl_global
       2, // opencl_local
       3, // opencl_constant
-      4, // cuda_device
-      5, // cuda_constant
-      6  // cuda_shared
+      4, // opencl_generic
+      5, // cuda_device
+      6, // cuda_constant
+      7  // cuda_shared
     };
     return &FakeAddrSpaceMap;
   } else {
@@ -736,9 +738,8 @@
       FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
       ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
       BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
-      NullTypeSourceInfo(QualType()), FirstLocalImport(), LastLocalImport(),
-      SourceMgr(SM), LangOpts(LOpts),
-      SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)),
+      FirstLocalImport(), LastLocalImport(), SourceMgr(SM), LangOpts(LOpts),
+      SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
       AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
       Idents(idents), Selectors(sels), BuiltinInfo(builtins),
       DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
@@ -875,6 +876,8 @@
     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
                                  &Idents.get(Name));
   NewDecl->setImplicit();
+  NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
+      const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
   return NewDecl;
 }
 
@@ -1667,13 +1670,23 @@
       break;
     }
 
-    if (const EnumType *ET = dyn_cast<EnumType>(TT))
-      return getTypeInfo(ET->getDecl()->getIntegerType());
+    if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
+      const EnumDecl *ED = ET->getDecl();
+      TypeInfo Info =
+          getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
+      if (unsigned AttrAlign = ED->getMaxAlignment()) {
+        Info.Align = AttrAlign;
+        Info.AlignIsRequired = true;
+      }
+      return Info;
+    }
 
     const RecordType *RT = cast<RecordType>(TT);
-    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
+    const RecordDecl *RD = RT->getDecl();
+    const ASTRecordLayout &Layout = getASTRecordLayout(RD);
     Width = toBits(Layout.getSize());
     Align = toBits(Layout.getAlignment());
+    AlignIsRequired = RD->hasAttr<AlignedAttr>();
     break;
   }
 
@@ -1783,6 +1796,8 @@
   T = T->getBaseElementTypeUnsafe();
   if (const ComplexType *CT = T->getAs<ComplexType>())
     T = CT->getElementType().getTypePtr();
+  if (const EnumType *ET = T->getAs<EnumType>())
+    T = ET->getDecl()->getIntegerType().getTypePtr();
   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
       T->isSpecificBuiltinType(BuiltinType::ULongLong))
@@ -7542,7 +7557,7 @@
       break;
     case 'U':
       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
-      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
+      assert(!Unsigned && "Can't use 'U' modifier multiple times!");
       Unsigned = true;
       break;
     case 'L':
@@ -7577,7 +7592,7 @@
     break;
   case 'h':
     assert(HowLong == 0 && !Signed && !Unsigned &&
-           "Bad modifiers used with 'f'!");
+           "Bad modifiers used with 'h'!");
     Type = Context.HalfTy;
     break;
   case 'f':
@@ -8040,7 +8055,9 @@
   if (IsCXXMethod)
     return ABI->getDefaultMethodCallConv(IsVariadic);
 
-  return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
+  if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
+
+  return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
 }
 
 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
@@ -8063,6 +8080,7 @@
   case TargetCXXABI::GenericAArch64:
   case TargetCXXABI::GenericItanium:
   case TargetCXXABI::GenericARM:
+  case TargetCXXABI::GenericMIPS:
   case TargetCXXABI::iOS:
   case TargetCXXABI::iOS64:
     return ItaniumMangleContext::create(*this, getDiagnostics());
diff --git a/lib/AST/ASTDiagnostic.cpp b/lib/AST/ASTDiagnostic.cpp
index 3212359..000588f 100644
--- a/lib/AST/ASTDiagnostic.cpp
+++ b/lib/AST/ASTDiagnostic.cpp
@@ -998,29 +998,27 @@
             (!HasFromValueDecl && !HasToValueDecl)) &&
            "Template argument cannot be both integer and declaration");
 
-    unsigned ParamWidth = 128; // Safe default
-    if (FromDefaultNonTypeDecl->getType()->isIntegralOrEnumerationType())
-      ParamWidth = Context.getIntWidth(FromDefaultNonTypeDecl->getType());
-
     if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
       Tree.SetNode(FromExpr, ToExpr);
       Tree.SetDefault(FromIter.isEnd() && FromExpr, ToIter.isEnd() && ToExpr);
       if (FromDefaultNonTypeDecl->getType()->isIntegralOrEnumerationType()) {
         if (FromExpr)
-          HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt);
+          HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt,
+                              FromDefaultNonTypeDecl->getType());
         if (ToExpr)
-          HasToInt = GetInt(Context, ToIter, ToExpr, ToInt);
+          HasToInt = GetInt(Context, ToIter, ToExpr, ToInt,
+                            ToDefaultNonTypeDecl->getType());
       }
       if (HasFromInt && HasToInt) {
         Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
-        Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
+        Tree.SetSame(FromInt == ToInt);
         Tree.SetKind(DiffTree::Integer);
       } else if (HasFromInt || HasToInt) {
         Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
         Tree.SetSame(false);
         Tree.SetKind(DiffTree::Integer);
       } else {
-        Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr) ||
+        Tree.SetSame(IsEqualExpr(Context, FromExpr, ToExpr) ||
                      (FromNullPtr && ToNullPtr));
         Tree.SetNullPtr(FromNullPtr, ToNullPtr);
         Tree.SetKind(DiffTree::Expression);
@@ -1030,11 +1028,17 @@
 
     if (HasFromInt || HasToInt) {
       if (!HasFromInt && FromExpr)
-        HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt);
+        HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt,
+                            FromDefaultNonTypeDecl->getType());
       if (!HasToInt && ToExpr)
-        HasToInt = GetInt(Context, ToIter, ToExpr, ToInt);
+        HasToInt = GetInt(Context, ToIter, ToExpr, ToInt,
+                          ToDefaultNonTypeDecl->getType());
       Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
-      Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
+      if (HasFromInt && HasToInt) {
+        Tree.SetSame(FromInt == ToInt);
+      } else {
+        Tree.SetSame(false);
+      }
       Tree.SetDefault(FromIter.isEnd() && HasFromInt,
                       ToIter.isEnd() && HasToInt);
       Tree.SetKind(DiffTree::Integer);
@@ -1210,9 +1214,11 @@
   }
 
   /// GetInt - Retrieves the template integer argument, including evaluating
-  /// default arguments.
+  /// default arguments.  If the value comes from an expression, extend the
+  /// APSInt to size of IntegerType to match the behavior in
+  /// Sema::CheckTemplateArgument
   static bool GetInt(ASTContext &Context, const TSTiterator &Iter,
-                     Expr *ArgExpr, llvm::APInt &Int) {
+                     Expr *ArgExpr, llvm::APSInt &Int, QualType IntegerType) {
     // Default, value-depenedent expressions require fetching
     // from the desugared TemplateArgument, otherwise expression needs to
     // be evaluatable.
@@ -1224,12 +1230,14 @@
         case TemplateArgument::Expression:
           ArgExpr = Iter.getDesugar().getAsExpr();
           Int = ArgExpr->EvaluateKnownConstInt(Context);
+          Int = Int.extOrTrunc(Context.getTypeSize(IntegerType));
           return true;
         default:
           llvm_unreachable("Unexpected template argument kind");
       }
     } else if (ArgExpr->isEvaluatable(Context)) {
       Int = ArgExpr->EvaluateKnownConstInt(Context);
+      Int = Int.extOrTrunc(Context.getTypeSize(IntegerType));
       return true;
     }
 
@@ -1302,18 +1310,8 @@
     return nullptr;
   }
 
-  /// IsSameConvertedInt - Returns true if both integers are equal when
-  /// converted to an integer type with the given width.
-  static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
-                                 const llvm::APSInt &Y) {
-    llvm::APInt ConvertedX = X.extOrTrunc(Width);
-    llvm::APInt ConvertedY = Y.extOrTrunc(Width);
-    return ConvertedX == ConvertedY;
-  }
-
   /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
-  static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
-                          Expr *FromExpr, Expr *ToExpr) {
+  static bool IsEqualExpr(ASTContext &Context, Expr *FromExpr, Expr *ToExpr) {
     if (FromExpr == ToExpr)
       return true;
 
@@ -1345,7 +1343,7 @@
 
     switch (FromVal.getKind()) {
       case APValue::Int:
-        return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
+        return FromVal.getInt() == ToVal.getInt();
       case APValue::LValue: {
         APValue::LValueBase FromBase = FromVal.getLValueBase();
         APValue::LValueBase ToBase = ToVal.getLValueBase();
@@ -1655,11 +1653,14 @@
     }
     Unbold();
   }
-  
+
   /// HasExtraInfo - Returns true if E is not an integer literal or the
   /// negation of an integer literal
   bool HasExtraInfo(Expr *E) {
     if (!E) return false;
+
+    E = E->IgnoreImpCasts();
+
     if (isa<IntegerLiteral>(E)) return false;
 
     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp
index ce32f50..3a9aee6 100644
--- a/lib/AST/ASTDumper.cpp
+++ b/lib/AST/ASTDumper.cpp
@@ -516,6 +516,7 @@
       VisitExpr(Node);
       dumpDecl(Node->getLambdaClass());
     }
+    void VisitSizeOfPackExpr(const SizeOfPackExpr *Node);
 
     // ObjC
     void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node);
@@ -987,6 +988,10 @@
       OS << " referenced";
     if (D->isInvalidDecl())
       OS << " invalid";
+    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
+      if (FD->isConstexpr())
+        OS << " constexpr";
+
 
     ConstDeclVisitor<ASTDumper>::Visit(D);
 
@@ -1095,10 +1100,13 @@
        E = D->getDeclsInPrototypeScope().end(); I != E; ++I)
     dumpDecl(*I);
 
-  for (FunctionDecl::param_const_iterator I = D->param_begin(),
-                                          E = D->param_end();
-       I != E; ++I)
-    dumpDecl(*I);
+  if (!D->param_begin() && D->getNumParams())
+    dumpChild([=] { OS << "<<NULL params x " << D->getNumParams() << ">>"; });
+  else
+    for (FunctionDecl::param_const_iterator I = D->param_begin(),
+                                            E = D->param_end();
+         I != E; ++I)
+      dumpDecl(*I);
 
   if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(D))
     for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
@@ -1930,6 +1938,13 @@
   OS << ")";
 }
 
+void ASTDumper::VisitSizeOfPackExpr(const SizeOfPackExpr *Node) {
+  VisitExpr(Node);
+  dumpPointer(Node->getPack());
+  dumpName(Node->getPack());
+}
+
+
 //===----------------------------------------------------------------------===//
 // Obj-C Expressions
 //===----------------------------------------------------------------------===//
diff --git a/lib/AST/ASTImporter.cpp b/lib/AST/ASTImporter.cpp
index 07b2a73..2442e8e 100644
--- a/lib/AST/ASTImporter.cpp
+++ b/lib/AST/ASTImporter.cpp
@@ -151,6 +151,7 @@
     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
+    Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
@@ -2253,7 +2254,7 @@
   } else {
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(Name, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
         continue;
@@ -2316,7 +2317,7 @@
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     unsigned IDNS = Decl::IDNS_Ordinary;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(Name, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
         continue;
@@ -2396,7 +2397,7 @@
   if (!DC->isFunctionOrMethod() && SearchName) {
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(SearchName, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
         continue;
@@ -2482,7 +2483,7 @@
   if (!DC->isFunctionOrMethod()) {
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(SearchName, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
         continue;
@@ -2604,7 +2605,7 @@
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     unsigned IDNS = Decl::IDNS_Ordinary;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(Name, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
         continue;
@@ -2656,7 +2657,7 @@
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     unsigned IDNS = Decl::IDNS_Ordinary;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(Name, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
         continue;
@@ -2859,7 +2860,7 @@
 
   // Determine whether we've already imported this field. 
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
       // For anonymous fields, match up by index.
@@ -2915,7 +2916,7 @@
 
   // Determine whether we've already imported this field. 
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (IndirectFieldDecl *FoundField 
                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
@@ -2982,7 +2983,7 @@
 
   // Determine whether we've already imported this ivar 
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
       if (Importer.IsStructurallyEquivalent(D->getType(), 
@@ -3037,7 +3038,7 @@
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     unsigned IDNS = Decl::IDNS_Ordinary;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(Name, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
         continue;
@@ -3207,7 +3208,7 @@
     return nullptr;
 
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
@@ -3443,7 +3444,7 @@
 
   ObjCProtocolDecl *MergeWithProtocol = nullptr;
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
       continue;
@@ -3470,6 +3471,36 @@
   return ToProto;
 }
 
+Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
+  DeclContext *DC = Importer.ImportContext(D->getDeclContext());
+  DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
+
+  SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
+  SourceLocation LangLoc = Importer.Import(D->getLocation());
+
+  bool HasBraces = D->hasBraces();
+ 
+  LinkageSpecDecl *ToLinkageSpec =
+    LinkageSpecDecl::Create(Importer.getToContext(),
+                            DC,
+                            ExternLoc,
+                            LangLoc,
+                            D->getLanguage(),
+                            HasBraces);
+
+  if (HasBraces) {
+    SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
+    ToLinkageSpec->setRBraceLoc(RBraceLoc);
+  }
+
+  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
+  LexicalDC->addDeclInternal(ToLinkageSpec);
+
+  Importer.Imported(D, ToLinkageSpec);
+
+  return ToLinkageSpec;
+}
+
 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, 
                                        ObjCInterfaceDecl *To,
                                        ImportDefinitionKind Kind) {
@@ -3589,7 +3620,7 @@
   // Look for an existing interface with the same name.
   ObjCInterfaceDecl *MergeWithIface = nullptr;
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
       continue;
@@ -3743,7 +3774,7 @@
 
   // Check whether we have already imported this property.
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (ObjCPropertyDecl *FoundProp
                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
@@ -3976,7 +4007,7 @@
   if (!DC->isFunctionOrMethod()) {
     SmallVector<NamedDecl *, 4> ConflictingDecls;
     SmallVector<NamedDecl *, 2> FoundDecls;
-    DC->localUncachedLookup(Name, FoundDecls);
+    DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
         continue;
@@ -4165,7 +4196,7 @@
          "Variable templates cannot be declared at function scope");
   SmallVector<NamedDecl *, 4> ConflictingDecls;
   SmallVector<NamedDecl *, 2> FoundDecls;
-  DC->localUncachedLookup(Name, FoundDecls);
+  DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
       continue;
@@ -4375,7 +4406,7 @@
                                          Importer.Import(E->getQualifierLoc()),
                                    Importer.Import(E->getTemplateKeywordLoc()),
                                          ToD,
-                                         E->refersToEnclosingLocal(),
+                                        E->refersToEnclosingVariableOrCapture(),
                                          Importer.Import(E->getLocation()),
                                          T, E->getValueKind(),
                                          FoundD,
@@ -4893,7 +4924,10 @@
   FromLoc = FromSM.getSpellingLoc(FromLoc);
   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
   SourceManager &ToSM = ToContext.getSourceManager();
-  return ToSM.getLocForStartOfFile(Import(Decomposed.first))
+  FileID ToFileID = Import(Decomposed.first);
+  if (ToFileID.isInvalid())
+    return SourceLocation();
+  return ToSM.getLocForStartOfFile(ToFileID)
              .getLocWithOffset(Decomposed.second);
 }
 
@@ -4924,6 +4958,8 @@
     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
     // than mmap the files several times.
     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
+    if (!Entry)
+      return FileID();
     ToID = ToSM.createFileID(Entry, ToIncludeLoc, 
                              FromSLoc.getFile().getFileCharacteristic());
   } else {
diff --git a/lib/AST/CXXInheritance.cpp b/lib/AST/CXXInheritance.cpp
index 6e80ee7..800c8f8 100644
--- a/lib/AST/CXXInheritance.cpp
+++ b/lib/AST/CXXInheritance.cpp
@@ -318,48 +318,36 @@
   //
   // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
   // way to make it any faster.
-  for (CXXBasePaths::paths_iterator P = Paths.begin(), PEnd = Paths.end();
-       P != PEnd; /* increment in loop */) {
-    bool Hidden = false;
+  Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) {
+    for (const CXXBasePathElement &PE : Path) {
+      if (!PE.Base->isVirtual())
+        continue;
 
-    for (CXXBasePath::iterator PE = P->begin(), PEEnd = P->end();
-         PE != PEEnd && !Hidden; ++PE) {
-      if (PE->Base->isVirtual()) {
-        CXXRecordDecl *VBase = nullptr;
-        if (const RecordType *Record = PE->Base->getType()->getAs<RecordType>())
-          VBase = cast<CXXRecordDecl>(Record->getDecl());
-        if (!VBase)
+      CXXRecordDecl *VBase = nullptr;
+      if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>())
+        VBase = cast<CXXRecordDecl>(Record->getDecl());
+      if (!VBase)
+        break;
+
+      // The declaration(s) we found along this path were found in a
+      // subobject of a virtual base. Check whether this virtual
+      // base is a subobject of any other path; if so, then the
+      // declaration in this path are hidden by that patch.
+      for (const CXXBasePath &HidingP : Paths) {
+        CXXRecordDecl *HidingClass = nullptr;
+        if (const RecordType *Record =
+                HidingP.back().Base->getType()->getAs<RecordType>())
+          HidingClass = cast<CXXRecordDecl>(Record->getDecl());
+        if (!HidingClass)
           break;
 
-        // The declaration(s) we found along this path were found in a
-        // subobject of a virtual base. Check whether this virtual
-        // base is a subobject of any other path; if so, then the
-        // declaration in this path are hidden by that patch.
-        for (CXXBasePaths::paths_iterator HidingP = Paths.begin(),
-                                       HidingPEnd = Paths.end();
-             HidingP != HidingPEnd;
-             ++HidingP) {
-          CXXRecordDecl *HidingClass = nullptr;
-          if (const RecordType *Record
-                       = HidingP->back().Base->getType()->getAs<RecordType>())
-            HidingClass = cast<CXXRecordDecl>(Record->getDecl());
-          if (!HidingClass)
-            break;
-
-          if (HidingClass->isVirtuallyDerivedFrom(VBase)) {
-            Hidden = true;
-            break;
-          }
-        }
+        if (HidingClass->isVirtuallyDerivedFrom(VBase))
+          return true;
       }
     }
+    return false;
+  });
 
-    if (Hidden)
-      P = Paths.Paths.erase(P);
-    else
-      ++P;
-  }
-  
   return true;
 }
 
@@ -569,18 +557,14 @@
     // overrider. To do so, we dig down to the original virtual
     // functions using data recursion and update all of the methods it
     // overrides.
-    typedef std::pair<CXXMethodDecl::method_iterator, 
-                      CXXMethodDecl::method_iterator> OverriddenMethods;
+    typedef llvm::iterator_range<CXXMethodDecl::method_iterator>
+        OverriddenMethods;
     SmallVector<OverriddenMethods, 4> Stack;
-    Stack.push_back(std::make_pair(CanonM->begin_overridden_methods(),
-                                   CanonM->end_overridden_methods()));
+    Stack.push_back(llvm::make_range(CanonM->begin_overridden_methods(),
+                                     CanonM->end_overridden_methods()));
     while (!Stack.empty()) {
-      OverriddenMethods OverMethods = Stack.back();
-      Stack.pop_back();
-
-      for (; OverMethods.first != OverMethods.second; ++OverMethods.first) {
-        const CXXMethodDecl *CanonOM
-          = cast<CXXMethodDecl>((*OverMethods.first)->getCanonicalDecl());
+      for (const CXXMethodDecl *OM : Stack.pop_back_val()) {
+        const CXXMethodDecl *CanonOM = OM->getCanonicalDecl();
 
         // C++ [class.virtual]p2:
         //   A virtual member function C::vf of a class object S is
@@ -601,8 +585,8 @@
 
         // Continue recursion to the methods that this virtual method
         // overrides.
-        Stack.push_back(std::make_pair(CanonOM->begin_overridden_methods(),
-                                       CanonOM->end_overridden_methods()));
+        Stack.push_back(llvm::make_range(CanonOM->begin_overridden_methods(),
+                                         CanonOM->end_overridden_methods()));
       }
     }
 
@@ -630,54 +614,32 @@
   // Weed out any final overriders that come from virtual base class
   // subobjects that were hidden by other subobjects along any path.
   // This is the final-overrider variant of C++ [class.member.lookup]p10.
-  for (CXXFinalOverriderMap::iterator OM = FinalOverriders.begin(), 
-                           OMEnd = FinalOverriders.end();
-       OM != OMEnd;
-       ++OM) {
-    for (OverridingMethods::iterator SO = OM->second.begin(), 
-                                  SOEnd = OM->second.end();
-         SO != SOEnd; 
-         ++SO) {
-      SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO->second;
+  for (auto &OM : FinalOverriders) {
+    for (auto &SO : OM.second) {
+      SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second;
       if (Overriding.size() < 2)
         continue;
 
-      for (SmallVectorImpl<UniqueVirtualMethod>::iterator
-             Pos = Overriding.begin(), PosEnd = Overriding.end();
-           Pos != PosEnd;
-           /* increment in loop */) {
-        if (!Pos->InVirtualSubobject) {
-          ++Pos;
-          continue;
-        }
+      auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) {
+        if (!M.InVirtualSubobject)
+          return false;
 
         // We have an overriding method in a virtual base class
         // subobject (or non-virtual base class subobject thereof);
         // determine whether there exists an other overriding method
         // in a base class subobject that hides the virtual base class
         // subobject.
-        bool Hidden = false;
-        for (SmallVectorImpl<UniqueVirtualMethod>::iterator
-               OP = Overriding.begin(), OPEnd = Overriding.end();
-             OP != OPEnd && !Hidden; 
-             ++OP) {
-          if (Pos == OP)
-            continue;
+        for (const UniqueVirtualMethod &OP : Overriding)
+          if (&M != &OP &&
+              OP.Method->getParent()->isVirtuallyDerivedFrom(
+                  M.InVirtualSubobject))
+            return true;
+        return false;
+      };
 
-          if (OP->Method->getParent()->isVirtuallyDerivedFrom(
-                         const_cast<CXXRecordDecl *>(Pos->InVirtualSubobject)))
-            Hidden = true;
-        }
-
-        if (Hidden) {
-          // The current overriding function is hidden by another
-          // overriding function; remove this one.
-          Pos = Overriding.erase(Pos);
-          PosEnd = Overriding.end();
-        } else {
-          ++Pos;
-        }
-      }
+      Overriding.erase(
+          std::remove_if(Overriding.begin(), Overriding.end(), IsHidden),
+          Overriding.end());
     }
   }
 }
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index a937fdf..e7e9941 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -619,9 +619,12 @@
     // Explicitly declared static.
     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
+  } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
+    //   - a data member of an anonymous union.
+    const VarDecl *VD = IFD->getVarDecl();
+    assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
+    return getLVForNamespaceScopeDecl(VD, computation);
   }
-  //   - a data member of an anonymous union.
-  assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
 
   if (D->isInAnonymousNamespace()) {
@@ -1189,7 +1192,7 @@
   } else {
     const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
     if (!FD->isInlined() &&
-        FD->getTemplateSpecializationKind() == TSK_Undeclared)
+        !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
       return LinkageInfo::none();
 
     LV = getLVForDecl(FD, computation);
@@ -1442,74 +1445,122 @@
     printName(OS);
 }
 
-bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
+static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) {
+  // For method declarations, we never replace.
+  if (ObjCMethodDecl::classofKind(NewK))
+    return false;
+
+  if (OldK == NewK)
+    return true;
+
+  // A compatibility alias for a class can be replaced by an interface.
+  if (ObjCCompatibleAliasDecl::classofKind(OldK) &&
+      ObjCInterfaceDecl::classofKind(NewK))
+    return true;
+
+  // A typedef-declaration, alias-declaration, or Objective-C class declaration
+  // can replace another declaration of the same type. Semantic analysis checks
+  // that we have matching types.
+  if ((TypedefNameDecl::classofKind(OldK) ||
+       ObjCInterfaceDecl::classofKind(OldK)) &&
+      (TypedefNameDecl::classofKind(NewK) ||
+       ObjCInterfaceDecl::classofKind(NewK)))
+    return true;
+
+  // Otherwise, a kind mismatch implies that the declaration is not replaced.
+  return false;
+}
+
+template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
+  return true;
+}
+static bool isRedeclarableImpl(...) { return false; }
+static bool isRedeclarable(Decl::Kind K) {
+  switch (K) {
+#define DECL(Type, Base) \
+  case Decl::Type: \
+    return isRedeclarableImpl((Type##Decl *)nullptr);
+#define ABSTRACT_DECL(DECL)
+#include "clang/AST/DeclNodes.inc"
+  }
+  llvm_unreachable("unknown decl kind");
+}
+
+bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
 
-  // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
-  // We want to keep it, unless it nominates same namespace.
-  if (getKind() == Decl::UsingDirective) {
-    return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
-             ->getOriginalNamespace() ==
-           cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
-             ->getOriginalNamespace();
-  }
+  if (!isKindReplaceableBy(OldD->getKind(), getKind()))
+    return false;
+
+  // Inline namespaces can give us two declarations with the same
+  // name and kind in the same scope but different contexts; we should
+  // keep both declarations in this case.
+  if (!this->getDeclContext()->getRedeclContext()->Equals(
+          OldD->getDeclContext()->getRedeclContext()))
+    return false;
 
   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
     // For function declarations, we keep track of redeclarations.
-    return FD->getPreviousDecl() == OldD;
+    // FIXME: This returns false for functions that should in fact be replaced.
+    // Instead, perform some kind of type check?
+    if (FD->getPreviousDecl() != OldD)
+      return false;
 
   // For function templates, the underlying function declarations are linked.
-  if (const FunctionTemplateDecl *FunctionTemplate
-        = dyn_cast<FunctionTemplateDecl>(this))
-    if (const FunctionTemplateDecl *OldFunctionTemplate
-          = dyn_cast<FunctionTemplateDecl>(OldD))
-      return FunctionTemplate->getTemplatedDecl()
-               ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
+  if (const FunctionTemplateDecl *FunctionTemplate =
+          dyn_cast<FunctionTemplateDecl>(this))
+    return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
+        cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
 
-  // For method declarations, we keep track of redeclarations.
-  if (isa<ObjCMethodDecl>(this))
-    return false;
+  // Using shadow declarations can be overloaded on their target declarations
+  // if they introduce functions.
+  // FIXME: If our target replaces the old target, can we replace the old
+  //        shadow declaration?
+  if (auto *USD = dyn_cast<UsingShadowDecl>(this))
+    if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl())
+      return false;
 
-  // FIXME: Is this correct if one of the decls comes from an inline namespace?
-  if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
-    return true;
-
-  if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
-    return cast<UsingShadowDecl>(this)->getTargetDecl() ==
-           cast<UsingShadowDecl>(OldD)->getTargetDecl();
-
-  if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
+  // Using declarations can be overloaded if they introduce functions.
+  if (auto *UD = dyn_cast<UsingDecl>(this)) {
     ASTContext &Context = getASTContext();
-    return Context.getCanonicalNestedNameSpecifier(
-                                     cast<UsingDecl>(this)->getQualifier()) ==
+    return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
            Context.getCanonicalNestedNameSpecifier(
-                                        cast<UsingDecl>(OldD)->getQualifier());
+               cast<UsingDecl>(OldD)->getQualifier());
   }
-
-  if (isa<UnresolvedUsingValueDecl>(this) &&
-      isa<UnresolvedUsingValueDecl>(OldD)) {
+  if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
     ASTContext &Context = getASTContext();
-    return Context.getCanonicalNestedNameSpecifier(
-                      cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
+    return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
            Context.getCanonicalNestedNameSpecifier(
                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
   }
 
-  // A typedef of an Objective-C class type can replace an Objective-C class
-  // declaration or definition, and vice versa.
-  // FIXME: Is this correct if one of the decls comes from an inline namespace?
-  if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
-      (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
-    return true;
+  // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
+  // We want to keep it, unless it nominates same namespace.
+  if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
+    return UD->getNominatedNamespace()->getOriginalNamespace() ==
+           cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
+               ->getOriginalNamespace();
 
-  // For non-function declarations, if the declarations are of the
-  // same kind and have the same parent then this must be a redeclaration,
-  // or semantic analysis would not have given us the new declaration.
-  // Note that inline namespaces can give us two declarations with the same
-  // name and kind in the same scope but different contexts.
-  return this->getKind() == OldD->getKind() &&
-         this->getDeclContext()->getRedeclContext()->Equals(
-             OldD->getDeclContext()->getRedeclContext());
+  if (!IsKnownNewer && isRedeclarable(getKind())) {
+    // Check whether this is actually newer than OldD. We want to keep the
+    // newer declaration. This loop will usually only iterate once, because
+    // OldD is usually the previous declaration.
+    for (auto D : redecls()) {
+      if (D == OldD)
+        break;
+
+      // If we reach the canonical declaration, then OldD is not actually older
+      // than this one.
+      //
+      // FIXME: In this case, we should not add this decl to the lookup table.
+      if (D->isCanonicalDecl())
+        return false;
+    }
+  }
+
+  // It's a newer declaration of the same kind of declaration in the same scope,
+  // and not an overload: we want this decl instead of the existing one.
+  return true;
 }
 
 bool NamedDecl::hasLinkage() const {
@@ -2481,8 +2532,8 @@
 
   // This is a sized deallocation function. Find the corresponding unsized
   // deallocation function.
-  lookup_const_result R = getDeclContext()->lookup(getDeclName());
-  for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
+  lookup_result R = getDeclContext()->lookup(getDeclName());
+  for (lookup_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
        ++RI)
     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
       if (FD->getNumParams() == 1 && !FD->isVariadic())
@@ -3586,7 +3637,7 @@
 /// This which can be turned on with an attribute, pragma, or the
 /// -mms-bitfields command-line option.
 bool RecordDecl::isMsStruct(const ASTContext &C) const {
-  return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
+  return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
 }
 
 static bool isFieldOrIndirectField(Decl::Kind K) {
@@ -3667,6 +3718,22 @@
   return ReasonToReject < 0;
 }
 
+const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
+  for (const auto *I : fields()) {
+    if (I->getIdentifier())
+      return I;
+
+    if (const RecordType *RT = I->getType()->getAs<RecordType>())
+      if (const FieldDecl *NamedDataMember =
+          RT->getDecl()->findFirstNamedDataMember())
+        return NamedDataMember;
+  }
+
+  // We didn't find a named data member.
+  return nullptr;
+}
+
+
 //===----------------------------------------------------------------------===//
 // BlockDecl Implementation
 //===----------------------------------------------------------------------===//
diff --git a/lib/AST/DeclBase.cpp b/lib/AST/DeclBase.cpp
index a46787f..75a219a 100644
--- a/lib/AST/DeclBase.cpp
+++ b/lib/AST/DeclBase.cpp
@@ -846,6 +846,10 @@
       return getLexicalParent()->isDependentContext();
   }
 
+  // FIXME: A variable template is a dependent context, but is not a
+  // DeclContext. A context within it (such as a lambda-expression)
+  // should be considered dependent.
+
   return getParent() && getParent()->isDependentContext();
 }
 
@@ -1078,7 +1082,7 @@
     // first.
     llvm::SmallVector<unsigned, 8> Skip;
     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
-      if (List.HandleRedeclaration(Decls[I]))
+      if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
         Skip.push_back(I);
     Skip.push_back(Decls.size());
 
@@ -1251,7 +1255,7 @@
   collectAllContexts(Contexts);
   for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
     buildLookupImpl<&DeclContext::decls_begin,
-                    &DeclContext::decls_end>(Contexts[I]);
+                    &DeclContext::decls_end>(Contexts[I], false);
 
   // We no longer have any lazy decls.
   LookupPtr.setInt(false);
@@ -1264,7 +1268,7 @@
 /// nested within it.
 template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
          DeclContext::decl_iterator (DeclContext::*End)() const>
-void DeclContext::buildLookupImpl(DeclContext *DCtx) {
+void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
   for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
        I != E; ++I) {
     Decl *D = *I;
@@ -1282,39 +1286,46 @@
           (!ND->isFromASTFile() ||
            (isTranslationUnit() &&
             !getParentASTContext().getLangOpts().CPlusPlus)))
-        makeDeclVisibleInContextImpl(ND, false);
+        makeDeclVisibleInContextImpl(ND, Internal);
 
     // If this declaration is itself a transparent declaration context
     // or inline namespace, add the members of this declaration of that
     // context (recursively).
     if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
-        buildLookupImpl<Begin, End>(InnerCtx);
+        buildLookupImpl<Begin, End>(InnerCtx, Internal);
   }
 }
 
+NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
+
 DeclContext::lookup_result
-DeclContext::lookup(DeclarationName Name) {
+DeclContext::lookup(DeclarationName Name) const {
   assert(DeclKind != Decl::LinkageSpec &&
          "Should not perform lookups into linkage specs!");
 
-  DeclContext *PrimaryContext = getPrimaryContext();
+  const DeclContext *PrimaryContext = getPrimaryContext();
   if (PrimaryContext != this)
     return PrimaryContext->lookup(Name);
 
-  // If this is a namespace, ensure that any later redeclarations of it have
-  // been loaded, since they may add names to the result of this lookup.
-  if (auto *ND = dyn_cast<NamespaceDecl>(this))
-    (void)ND->getMostRecentDecl();
+  // If we have an external source, ensure that any later redeclarations of this
+  // context have been loaded, since they may add names to the result of this
+  // lookup (or add external visible storage).
+  ExternalASTSource *Source = getParentASTContext().getExternalSource();
+  if (Source)
+    (void)cast<Decl>(this)->getMostRecentDecl();
 
   if (hasExternalVisibleStorage()) {
+    assert(Source && "external visible storage but no external source?");
+
     if (NeedToReconcileExternalVisibleStorage)
       reconcileExternalVisibleStorage();
 
     StoredDeclsMap *Map = LookupPtr.getPointer();
 
     if (LookupPtr.getInt())
-      Map = buildLookup();
+      // FIXME: Make buildLookup const?
+      Map = const_cast<DeclContext*>(this)->buildLookup();
 
     if (!Map)
       Map = CreateStoredDeclsMap(getParentASTContext());
@@ -1325,7 +1336,6 @@
     if (!R.second && !R.first->second.hasExternalDecls())
       return R.first->second.getLookupResult();
 
-    ExternalASTSource *Source = getParentASTContext().getExternalSource();
     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
       if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
         StoredDeclsMap::iterator I = Map->find(Name);
@@ -1334,19 +1344,19 @@
       }
     }
 
-    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
+    return lookup_result();
   }
 
   StoredDeclsMap *Map = LookupPtr.getPointer();
   if (LookupPtr.getInt())
-    Map = buildLookup();
+    Map = const_cast<DeclContext*>(this)->buildLookup();
 
   if (!Map)
-    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
+    return lookup_result();
 
   StoredDeclsMap::iterator I = Map->find(Name);
   if (I == Map->end())
-    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
+    return lookup_result();
 
   return I->second.getLookupResult();
 }
@@ -1369,7 +1379,7 @@
     collectAllContexts(Contexts);
     for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
       buildLookupImpl<&DeclContext::noload_decls_begin,
-                      &DeclContext::noload_decls_end>(Contexts[I]);
+                      &DeclContext::noload_decls_end>(Contexts[I], true);
 
     // We no longer have any lazy decls.
     LookupPtr.setInt(false);
@@ -1383,12 +1393,11 @@
   }
 
   if (!Map)
-    return lookup_result(lookup_iterator(nullptr), lookup_iterator(nullptr));
+    return lookup_result();
 
   StoredDeclsMap::iterator I = Map->find(Name);
   return I != Map->end() ? I->second.getLookupResult()
-                         : lookup_result(lookup_iterator(nullptr),
-                                         lookup_iterator(nullptr));
+                         : lookup_result();
 }
 
 void DeclContext::localUncachedLookup(DeclarationName Name,
@@ -1555,12 +1564,12 @@
     return;
   }
 
-  else if (DeclNameEntries.isNull()) {
+  if (DeclNameEntries.isNull()) {
     DeclNameEntries.setOnlyValue(D);
     return;
   }
 
-  if (DeclNameEntries.HandleRedeclaration(D)) {
+  if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
     // This declaration has replaced an existing one for which
     // declarationReplaces returns true.
     return;
@@ -1570,15 +1579,17 @@
   DeclNameEntries.AddSubsequentDecl(D);
 }
 
+UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
+  return cast<UsingDirectiveDecl>(*I);
+}
+
 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
 /// this context.
 DeclContext::udir_range DeclContext::using_directives() const {
   // FIXME: Use something more efficient than normal lookup for using
   // directives. In C++, using directives are looked up more than anything else.
-  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
-  return udir_range(
-      reinterpret_cast<UsingDirectiveDecl *const *>(Result.begin()),
-      reinterpret_cast<UsingDirectiveDecl *const *>(Result.end()));
+  lookup_result Result = lookup(UsingDirectiveDecl::getName());
+  return udir_range(Result.begin(), Result.end());
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/lib/AST/DeclCXX.cpp b/lib/AST/DeclCXX.cpp
index 0ee3e3e..87a0634 100644
--- a/lib/AST/DeclCXX.cpp
+++ b/lib/AST/DeclCXX.cpp
@@ -991,7 +991,7 @@
   if (!isLambda()) return nullptr;
   DeclarationName Name = 
     getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
-  DeclContext::lookup_const_result Calls = lookup(Name);
+  DeclContext::lookup_result Calls = lookup(Name);
 
   assert(!Calls.empty() && "Missing lambda call operator!");
   assert(Calls.size() == 1 && "More than one lambda call operator!"); 
@@ -1008,7 +1008,7 @@
   if (!isLambda()) return nullptr;
   DeclarationName Name = 
     &getASTContext().Idents.get(getLambdaStaticInvokerName());
-  DeclContext::lookup_const_result Invoker = lookup(Name);
+  DeclContext::lookup_result Invoker = lookup(Name);
   if (Invoker.empty()) return nullptr;
   assert(Invoker.size() == 1 && "More than one static invoker operator!");  
   NamedDecl *InvokerFun = Invoker.front();
@@ -1173,7 +1173,7 @@
 
 /// getVisibleConversionFunctions - get all conversion functions visible
 /// in current class; including conversion function templates.
-std::pair<CXXRecordDecl::conversion_iterator,CXXRecordDecl::conversion_iterator>
+llvm::iterator_range<CXXRecordDecl::conversion_iterator>
 CXXRecordDecl::getVisibleConversionFunctions() {
   ASTContext &Ctx = getASTContext();
 
@@ -1189,7 +1189,7 @@
       data().ComputedVisibleConversions = true;
     }
   }
-  return std::make_pair(Set->begin(), Set->end());
+  return llvm::make_range(Set->begin(), Set->end());
 }
 
 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
@@ -1307,7 +1307,7 @@
     = Context.DeclarationNames.getCXXDestructorName(
                                           Context.getCanonicalType(ClassType));
 
-  DeclContext::lookup_const_result R = lookup(Name);
+  DeclContext::lookup_result R = lookup(Name);
   if (R.empty())
     return nullptr;
 
@@ -1418,9 +1418,8 @@
     return nullptr;
   }
 
-  lookup_const_result Candidates = RD->lookup(getDeclName());
-  for (NamedDecl * const * I = Candidates.begin(); I != Candidates.end(); ++I) {
-    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I);
+  for (auto *ND : RD->lookup(getDeclName())) {
+    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND);
     if (!MD)
       continue;
     if (recursivelyOverrides(MD, this))
@@ -1491,8 +1490,8 @@
                  
   // This function is a usual deallocation function if there are no 
   // single-parameter deallocation functions of the same kind.
-  DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
-  for (DeclContext::lookup_const_result::iterator I = R.begin(), E = R.end();
+  DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
+  for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
        I != E; ++I) {
     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
       if (FD->getNumParams() == 1)
@@ -1693,12 +1692,12 @@
 }
 
 SourceLocation CXXCtorInitializer::getSourceLocation() const {
-  if (isAnyMemberInitializer())
-    return getMemberLocation();
-
   if (isInClassMemberInitializer())
     return getAnyMember()->getLocation();
   
+  if (isAnyMemberInitializer())
+    return getMemberLocation();
+
   if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>())
     return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
   
@@ -1831,7 +1830,6 @@
 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
   if ((getNumParams() < 1) ||
       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
-      (getPrimaryTemplate() == nullptr) ||
       (getDescribedFunctionTemplate() != nullptr))
     return false;
 
diff --git a/lib/AST/DeclObjC.cpp b/lib/AST/DeclObjC.cpp
index 5deef58..6e74784 100644
--- a/lib/AST/DeclObjC.cpp
+++ b/lib/AST/DeclObjC.cpp
@@ -54,8 +54,8 @@
 ///
 ObjCIvarDecl *
 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
-  lookup_const_result R = lookup(Id);
-  for (lookup_const_iterator Ivar = R.begin(), IvarEnd = R.end();
+  lookup_result R = lookup(Id);
+  for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end();
        Ivar != IvarEnd; ++Ivar) {
     if (ObjCIvarDecl *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
       return ivar;
@@ -83,8 +83,8 @@
   // + (float) class_method;
   // @end
   //
-  lookup_const_result R = lookup(Sel);
-  for (lookup_const_iterator Meth = R.begin(), MethEnd = R.end();
+  lookup_result R = lookup(Sel);
+  for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
        Meth != MethEnd; ++Meth) {
     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
     if (MD && MD->isInstanceMethod() == isInstance)
@@ -93,16 +93,16 @@
   return nullptr;
 }
 
-/// HasUserDeclaredSetterMethod - This routine returns 'true' if a user declared setter
-/// method was found in the class, its protocols, its super classes or categories.
-/// It also returns 'true' if one of its categories has declared a 'readwrite' property.
-/// This is because, user must provide a setter method for the category's 'readwrite'
-/// property.
-bool
-ObjCContainerDecl::HasUserDeclaredSetterMethod(const ObjCPropertyDecl *Property) const {
+/// \brief This routine returns 'true' if a user declared setter method was
+/// found in the class, its protocols, its super classes or categories.
+/// It also returns 'true' if one of its categories has declared a 'readwrite'
+/// property.  This is because, user must provide a setter method for the
+/// category's 'readwrite' property.
+bool ObjCContainerDecl::HasUserDeclaredSetterMethod(
+    const ObjCPropertyDecl *Property) const {
   Selector Sel = Property->getSetterName();
-  lookup_const_result R = lookup(Sel);
-  for (lookup_const_iterator Meth = R.begin(), MethEnd = R.end();
+  lookup_result R = lookup(Sel);
+  for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
        Meth != MethEnd; ++Meth) {
     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
     if (MD && MD->isInstanceMethod() && !MD->isImplicit())
@@ -118,9 +118,10 @@
           return true;
       if (Cat->IsClassExtension())
         continue;
-      // Also search through the categories looking for a 'readwrite' declaration
-      // of this property. If one found, presumably a setter will be provided
-      // (properties declared in categories will not get auto-synthesized).
+      // Also search through the categories looking for a 'readwrite'
+      // declaration of this property. If one found, presumably a setter will
+      // be provided (properties declared in categories will not get
+      // auto-synthesized).
       for (const auto *P : Cat->properties())
         if (P->getIdentifier() == Property->getIdentifier()) {
           if (P->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite)
@@ -160,8 +161,8 @@
         return nullptr;
   }
 
-  DeclContext::lookup_const_result R = DC->lookup(propertyID);
-  for (DeclContext::lookup_const_iterator I = R.begin(), E = R.end(); I != E;
+  DeclContext::lookup_result R = DC->lookup(propertyID);
+  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
        ++I)
     if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I))
       return PD;
@@ -333,9 +334,8 @@
     return;
 
   // Merge ProtocolRefs into class's protocol list;
-  for (auto *P : all_referenced_protocols()) {
-    ProtocolRefs.push_back(P);
-  }
+  ProtocolRefs.append(all_referenced_protocol_begin(),
+                      all_referenced_protocol_end());
 
   data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
 }
@@ -1100,7 +1100,7 @@
   if (NumArgs > 1)
     return nullptr;
 
-  if (!isInstanceMethod() || getMethodFamily() != OMF_None)
+  if (!isInstanceMethod())
     return nullptr;
 
   if (isPropertyAccessor()) {
diff --git a/lib/AST/DeclTemplate.cpp b/lib/AST/DeclTemplate.cpp
index 0d1d2a4..6374a92 100644
--- a/lib/AST/DeclTemplate.cpp
+++ b/lib/AST/DeclTemplate.cpp
@@ -160,17 +160,43 @@
   return Common;
 }
 
-template <class EntryType>
-typename RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::DeclType*
+template<class EntryType>
+typename RedeclarableTemplateDecl::SpecEntryTraits<EntryType>::DeclType *
 RedeclarableTemplateDecl::findSpecializationImpl(
-                                 llvm::FoldingSetVector<EntryType> &Specs,
-                                 ArrayRef<TemplateArgument> Args,
-                                 void *&InsertPos) {
+    llvm::FoldingSetVector<EntryType> &Specs, ArrayRef<TemplateArgument> Args,
+    void *&InsertPos) {
   typedef SpecEntryTraits<EntryType> SETraits;
   llvm::FoldingSetNodeID ID;
   EntryType::Profile(ID,Args, getASTContext());
   EntryType *Entry = Specs.FindNodeOrInsertPos(ID, InsertPos);
-  return Entry ? SETraits::getMostRecentDecl(Entry) : nullptr;
+  return Entry ? SETraits::getDecl(Entry)->getMostRecentDecl() : nullptr;
+}
+
+template<class Derived, class EntryType>
+void RedeclarableTemplateDecl::addSpecializationImpl(
+    llvm::FoldingSetVector<EntryType> &Specializations, EntryType *Entry,
+    void *InsertPos) {
+  typedef SpecEntryTraits<EntryType> SETraits;
+  if (InsertPos) {
+#ifndef NDEBUG
+    void *CorrectInsertPos;
+    assert(!findSpecializationImpl(Specializations,
+                                   SETraits::getTemplateArgs(Entry),
+                                   CorrectInsertPos) &&
+           InsertPos == CorrectInsertPos &&
+           "given incorrect InsertPos for specialization");
+#endif
+    Specializations.InsertNode(Entry, InsertPos);
+  } else {
+    EntryType *Existing = Specializations.GetOrInsertNode(Entry);
+    (void)Existing;
+    assert(SETraits::getDecl(Existing)->isCanonicalDecl() &&
+           "non-canonical specialization?");
+  }
+
+  if (ASTMutationListener *L = getASTMutationListener())
+    L->AddedCXXTemplateSpecialization(cast<Derived>(this),
+                                      SETraits::getDecl(Entry));
 }
 
 /// \brief Generate the injected template arguments for the given template
@@ -246,7 +272,11 @@
 }
 
 void FunctionTemplateDecl::LoadLazySpecializations() const {
-  Common *CommonPtr = getCommonPtr();
+  // Grab the most recent declaration to ensure we've loaded any lazy
+  // redeclarations of this template.
+  //
+  // FIXME: Avoid walking the entire redeclaration chain here.
+  Common *CommonPtr = getMostRecentDecl()->getCommonPtr();
   if (CommonPtr->LazySpecializations) {
     ASTContext &Context = getASTContext();
     uint32_t *Specs = CommonPtr->LazySpecializations;
@@ -270,12 +300,8 @@
 
 void FunctionTemplateDecl::addSpecialization(
       FunctionTemplateSpecializationInfo *Info, void *InsertPos) {
-  if (InsertPos)
-    getSpecializations().InsertNode(Info, InsertPos);
-  else
-    getSpecializations().GetOrInsertNode(Info);
-  if (ASTMutationListener *L = getASTMutationListener())
-    L->AddedCXXTemplateSpecialization(this, Info->Function);
+  addSpecializationImpl<FunctionTemplateDecl>(getSpecializations(), Info,
+                                              InsertPos);
 }
 
 ArrayRef<TemplateArgument> FunctionTemplateDecl::getInjectedTemplateArgs() {
@@ -320,7 +346,11 @@
 }
 
 void ClassTemplateDecl::LoadLazySpecializations() const {
-  Common *CommonPtr = getCommonPtr();
+  // Grab the most recent declaration to ensure we've loaded any lazy
+  // redeclarations of this template.
+  //
+  // FIXME: Avoid walking the entire redeclaration chain here.
+  Common *CommonPtr = getMostRecentDecl()->getCommonPtr();
   if (CommonPtr->LazySpecializations) {
     ASTContext &Context = getASTContext();
     uint32_t *Specs = CommonPtr->LazySpecializations;
@@ -357,16 +387,7 @@
 
 void ClassTemplateDecl::AddSpecialization(ClassTemplateSpecializationDecl *D,
                                           void *InsertPos) {
-  if (InsertPos)
-    getSpecializations().InsertNode(D, InsertPos);
-  else {
-    ClassTemplateSpecializationDecl *Existing 
-      = getSpecializations().GetOrInsertNode(D);
-    (void)Existing;
-    assert(Existing->isCanonicalDecl() && "Non-canonical specialization?");
-  }
-  if (ASTMutationListener *L = getASTMutationListener())
-    L->AddedCXXTemplateSpecialization(this, D);
+  addSpecializationImpl<ClassTemplateDecl>(getSpecializations(), D, InsertPos);
 }
 
 ClassTemplatePartialSpecializationDecl *
@@ -953,7 +974,11 @@
 // TODO: Unify across class, function and variable templates?
 //       May require moving this and Common to RedeclarableTemplateDecl.
 void VarTemplateDecl::LoadLazySpecializations() const {
-  Common *CommonPtr = getCommonPtr();
+  // Grab the most recent declaration to ensure we've loaded any lazy
+  // redeclarations of this template.
+  //
+  // FIXME: Avoid walking the entire redeclaration chain here.
+  Common *CommonPtr = getMostRecentDecl()->getCommonPtr();
   if (CommonPtr->LazySpecializations) {
     ASTContext &Context = getASTContext();
     uint32_t *Specs = CommonPtr->LazySpecializations;
@@ -990,16 +1015,7 @@
 
 void VarTemplateDecl::AddSpecialization(VarTemplateSpecializationDecl *D,
                                         void *InsertPos) {
-  if (InsertPos)
-    getSpecializations().InsertNode(D, InsertPos);
-  else {
-    VarTemplateSpecializationDecl *Existing =
-        getSpecializations().GetOrInsertNode(D);
-    (void)Existing;
-    assert(Existing->isCanonicalDecl() && "Non-canonical specialization?");
-  }
-  if (ASTMutationListener *L = getASTMutationListener())
-    L->AddedCXXTemplateSpecialization(this, D);
+  addSpecializationImpl<VarTemplateDecl>(getSpecializations(), D, InsertPos);
 }
 
 VarTemplatePartialSpecializationDecl *
diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp
index 23c5dfa..ae80790 100644
--- a/lib/AST/Expr.cpp
+++ b/lib/AST/Expr.cpp
@@ -322,7 +322,7 @@
 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
                          NestedNameSpecifierLoc QualifierLoc,
                          SourceLocation TemplateKWLoc,
-                         ValueDecl *D, bool RefersToEnclosingLocal,
+                         ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
                          const DeclarationNameInfo &NameInfo,
                          NamedDecl *FoundD,
                          const TemplateArgumentListInfo *TemplateArgs,
@@ -343,7 +343,8 @@
     getInternalFoundDecl() = FoundD;
   DeclRefExprBits.HasTemplateKWAndArgsInfo
     = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
-  DeclRefExprBits.RefersToEnclosingLocal = RefersToEnclosingLocal;
+  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
+      RefersToEnclosingVariableOrCapture;
   if (TemplateArgs) {
     bool Dependent = false;
     bool InstantiationDependent = false;
@@ -367,14 +368,14 @@
                                  NestedNameSpecifierLoc QualifierLoc,
                                  SourceLocation TemplateKWLoc,
                                  ValueDecl *D,
-                                 bool RefersToEnclosingLocal,
+                                 bool RefersToEnclosingVariableOrCapture,
                                  SourceLocation NameLoc,
                                  QualType T,
                                  ExprValueKind VK,
                                  NamedDecl *FoundD,
                                  const TemplateArgumentListInfo *TemplateArgs) {
   return Create(Context, QualifierLoc, TemplateKWLoc, D,
-                RefersToEnclosingLocal,
+                RefersToEnclosingVariableOrCapture,
                 DeclarationNameInfo(D->getDeclName(), NameLoc),
                 T, VK, FoundD, TemplateArgs);
 }
@@ -383,7 +384,7 @@
                                  NestedNameSpecifierLoc QualifierLoc,
                                  SourceLocation TemplateKWLoc,
                                  ValueDecl *D,
-                                 bool RefersToEnclosingLocal,
+                                 bool RefersToEnclosingVariableOrCapture,
                                  const DeclarationNameInfo &NameInfo,
                                  QualType T,
                                  ExprValueKind VK,
@@ -405,7 +406,7 @@
 
   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
   return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
-                               RefersToEnclosingLocal,
+                               RefersToEnclosingVariableOrCapture,
                                NameInfo, FoundD, TemplateArgs, T, VK);
 }
 
@@ -1270,16 +1271,21 @@
   return false;
 }
 
-QualType CallExpr::getCallReturnType() const {
-  QualType CalleeType = getCallee()->getType();
-  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
+QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
+  const Expr *Callee = getCallee();
+  QualType CalleeType = Callee->getType();
+  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
     CalleeType = FnTypePtr->getPointeeType();
-  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
+  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
     CalleeType = BPT->getPointeeType();
-  else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
+  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
+    if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
+      return Ctx.VoidTy;
+
     // This should never be overloaded and so should never return null.
-    CalleeType = Expr::findBoundMemberType(getCallee());
-    
+    CalleeType = Expr::findBoundMemberType(Callee);
+  }
+
   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
   return FnType->getReturnType();
 }
@@ -1359,6 +1365,44 @@
   return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
 }
 
+UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
+    UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
+    SourceLocation op, SourceLocation rp)
+    : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
+           false, // Never type-dependent (C++ [temp.dep.expr]p3).
+           // Value-dependent if the argument is type-dependent.
+           E->isTypeDependent(), E->isInstantiationDependent(),
+           E->containsUnexpandedParameterPack()),
+      OpLoc(op), RParenLoc(rp) {
+  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
+  UnaryExprOrTypeTraitExprBits.IsType = false;
+  Argument.Ex = E;
+
+  // Check to see if we are in the situation where alignof(decl) should be
+  // dependent because decl's alignment is dependent.
+  if (ExprKind == UETT_AlignOf) {
+    if (!isValueDependent() || !isInstantiationDependent()) {
+      E = E->IgnoreParens();
+
+      const ValueDecl *D = nullptr;
+      if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
+        D = DRE->getDecl();
+      else if (const auto *ME = dyn_cast<MemberExpr>(E))
+        D = ME->getMemberDecl();
+
+      if (D) {
+        for (const auto *I : D->specific_attrs<AlignedAttr>()) {
+          if (I->isAlignmentDependent()) {
+            setValueDependent(true);
+            setInstantiationDependent(true);
+            break;
+          }
+        }
+      }
+    }
+  }
+}
+
 MemberExpr *MemberExpr::Create(const ASTContext &C, Expr *base, bool isarrow,
                                NestedNameSpecifierLoc QualifierLoc,
                                SourceLocation TemplateKWLoc,
@@ -2131,8 +2175,8 @@
     case OO_Greater:
     case OO_GreaterEqual:
     case OO_LessEqual:
-      if (Op->getCallReturnType()->isReferenceType() ||
-          Op->getCallReturnType()->isVoidType())
+      if (Op->getCallReturnType(Ctx)->isReferenceType() ||
+          Op->getCallReturnType(Ctx)->isVoidType())
         break;
       WarnE = this;
       Loc = Op->getOperatorLoc();
@@ -2199,9 +2243,7 @@
     }
 
     if (const ObjCMethodDecl *MD = ME->getMethodDecl())
-      if (MD->hasAttr<WarnUnusedResultAttr>() ||
-          (MD->isPropertyAccessor() && !MD->getReturnType()->isVoidType() &&
-           !ME->getReceiverType()->isObjCIdType())) {
+      if (MD->hasAttr<WarnUnusedResultAttr>()) {
         WarnE = this;
         Loc = getExprLoc();
         return true;
@@ -2386,7 +2428,7 @@
     return type;
   }
 
-  assert(isa<UnresolvedMemberExpr>(expr));
+  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
   return QualType();
 }
 
@@ -2866,9 +2908,16 @@
   return false;
 }
 
-bool Expr::HasSideEffects(const ASTContext &Ctx) const {
+bool Expr::HasSideEffects(const ASTContext &Ctx,
+                          bool IncludePossibleEffects) const {
+  // In circumstances where we care about definite side effects instead of
+  // potential side effects, we want to ignore expressions that are part of a
+  // macro expansion as a potential side effect.
+  if (!IncludePossibleEffects && getExprLoc().isMacroID())
+    return false;
+
   if (isInstantiationDependent())
-    return true;
+    return IncludePossibleEffects;
 
   switch (getStmtClass()) {
   case NoStmtClass:
@@ -2921,21 +2970,27 @@
     return false;
 
   case CallExprClass:
+  case CXXOperatorCallExprClass:
+  case CXXMemberCallExprClass:
+  case CUDAKernelCallExprClass:
+  case BlockExprClass:
+  case CXXBindTemporaryExprClass:
+  case UserDefinedLiteralClass:
+    // We don't know a call definitely has side effects, but we can check the
+    // call's operands.
+    if (!IncludePossibleEffects)
+      break;
+    return true;
+
   case MSPropertyRefExprClass:
   case CompoundAssignOperatorClass:
   case VAArgExprClass:
   case AtomicExprClass:
   case StmtExprClass:
-  case CXXOperatorCallExprClass:
-  case CXXMemberCallExprClass:
-  case UserDefinedLiteralClass:
   case CXXThrowExprClass:
   case CXXNewExprClass:
   case CXXDeleteExprClass:
   case ExprWithCleanupsClass:
-  case CXXBindTemporaryExprClass:
-  case BlockExprClass:
-  case CUDAKernelCallExprClass:
     // These always have a side-effect.
     return true;
 
@@ -2971,24 +3026,26 @@
   case InitListExprClass:
     // FIXME: The children for an InitListExpr doesn't include the array filler.
     if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
-      if (E->HasSideEffects(Ctx))
+      if (E->HasSideEffects(Ctx, IncludePossibleEffects))
         return true;
     break;
 
   case GenericSelectionExprClass:
     return cast<GenericSelectionExpr>(this)->getResultExpr()->
-        HasSideEffects(Ctx);
+        HasSideEffects(Ctx, IncludePossibleEffects);
 
   case ChooseExprClass:
-    return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(Ctx);
+    return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
+        Ctx, IncludePossibleEffects);
 
   case CXXDefaultArgExprClass:
-    return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(Ctx);
+    return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
+        Ctx, IncludePossibleEffects);
 
   case CXXDefaultInitExprClass: {
     const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
     if (const Expr *E = FD->getInClassInitializer())
-      return E->HasSideEffects(Ctx);
+      return E->HasSideEffects(Ctx, IncludePossibleEffects);
     // If we've not yet parsed the initializer, assume it has side-effects.
     return true;
   }
@@ -3006,6 +3063,13 @@
   case CXXReinterpretCastExprClass:
   case CXXConstCastExprClass:
   case CXXFunctionalCastExprClass: {
+    // While volatile reads are side-effecting in both C and C++, we treat them
+    // as having possible (not definite) side-effects. This allows idiomatic
+    // code to behave without warning, such as sizeof(*v) for a volatile-
+    // qualified pointer.
+    if (!IncludePossibleEffects)
+      break;
+
     const CastExpr *CE = cast<CastExpr>(this);
     if (CE->getCastKind() == CK_LValueToRValue &&
         CE->getSubExpr()->getType().isVolatileQualified())
@@ -3021,7 +3085,7 @@
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
-    if (!CE->getConstructor()->isTrivial())
+    if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
       return true;
     // A trivial constructor does not add any side-effects of its own. Just look
     // at its arguments.
@@ -3049,7 +3113,7 @@
       const Expr *Subexpr = *I;
       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
         Subexpr = OVE->getSourceExpr();
-      if (Subexpr->HasSideEffects(Ctx))
+      if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
         return true;
     }
     return false;
@@ -3058,22 +3122,24 @@
   case ObjCBoxedExprClass:
   case ObjCArrayLiteralClass:
   case ObjCDictionaryLiteralClass:
-  case ObjCMessageExprClass:
   case ObjCSelectorExprClass:
   case ObjCProtocolExprClass:
-  case ObjCPropertyRefExprClass:
   case ObjCIsaExprClass:
   case ObjCIndirectCopyRestoreExprClass:
   case ObjCSubscriptRefExprClass:
   case ObjCBridgedCastExprClass:
-    // FIXME: Classify these cases better.
-    return true;
+  case ObjCMessageExprClass:
+  case ObjCPropertyRefExprClass:
+  // FIXME: Classify these cases better.
+    if (IncludePossibleEffects)
+      return true;
+    break;
   }
 
   // Recurse to children.
   for (const_child_range SubStmts = children(); SubStmts; ++SubStmts)
     if (const Stmt *S = *SubStmts)
-      if (cast<Expr>(S)->HasSideEffects(Ctx))
+      if (cast<Expr>(S)->HasSideEffects(Ctx, IncludePossibleEffects))
         return true;
 
   return false;
@@ -3803,7 +3869,7 @@
       // Compute type- and value-dependence.
       Expr *Index = IndexExprs[IndexIdx];
       if (Index->isTypeDependent() || Index->isValueDependent())
-        ExprBits.ValueDependent = true;
+        ExprBits.TypeDependent = ExprBits.ValueDependent = true;
       if (Index->isInstantiationDependent())
         ExprBits.InstantiationDependent = true;
       // Propagate unexpanded parameter packs.
@@ -3818,7 +3884,7 @@
       Expr *End = IndexExprs[IndexIdx + 1];
       if (Start->isTypeDependent() || Start->isValueDependent() ||
           End->isTypeDependent() || End->isValueDependent()) {
-        ExprBits.ValueDependent = true;
+        ExprBits.TypeDependent = ExprBits.ValueDependent = true;
         ExprBits.InstantiationDependent = true;
       } else if (Start->isInstantiationDependent() || 
                  End->isInstantiationDependent()) {
diff --git a/lib/AST/ExprCXX.cpp b/lib/AST/ExprCXX.cpp
index 9336166..f23b3eb 100644
--- a/lib/AST/ExprCXX.cpp
+++ b/lib/AST/ExprCXX.cpp
@@ -208,8 +208,9 @@
 }
 
 bool CXXNewExpr::shouldNullCheckAllocation(const ASTContext &Ctx) const {
-  return getOperatorNew()->getType()->
-    castAs<FunctionProtoType>()->isNothrow(Ctx);
+  return getOperatorNew()->getType()->castAs<FunctionProtoType>()->isNothrow(
+             Ctx) &&
+         !getOperatorNew()->isReservedGlobalPlacementOperator();
 }
 
 // CXXDeleteExpr
@@ -237,10 +238,7 @@
                 SourceLocation ColonColonLoc, SourceLocation TildeLoc, 
                 PseudoDestructorTypeStorage DestroyedType)
   : Expr(CXXPseudoDestructorExprClass,
-         Context.getPointerType(Context.getFunctionType(
-             Context.VoidTy, None,
-             FunctionProtoType::ExtProtoInfo(
-                 Context.getDefaultCallingConvention(false, true)))),
+         Context.BoundMemberTy,
          VK_RValue, OK_Ordinary,
          /*isTypeDependent=*/(Base->isTypeDependent() ||
            (DestroyedType.getTypeSourceInfo() &&
@@ -359,8 +357,7 @@
     Results = static_cast<DeclAccessPair *>(
                                 C.Allocate(sizeof(DeclAccessPair) * NumResults, 
                                            llvm::alignOf<DeclAccessPair>()));
-    memcpy(Results, &*Begin.getIterator(), 
-           NumResults * sizeof(DeclAccessPair));
+    memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));
   }
 
   // If we have explicit template arguments, check for dependent
@@ -401,8 +398,7 @@
                                C.Allocate(sizeof(DeclAccessPair) * NumResults,
  
                                           llvm::alignOf<DeclAccessPair>()));
-     memcpy(Results, &*Begin.getIterator(), 
-            NumResults * sizeof(DeclAccessPair));
+     memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));
   }
 }
 
diff --git a/lib/AST/ExprClassification.cpp b/lib/AST/ExprClassification.cpp
index 915ca16..3073a53 100644
--- a/lib/AST/ExprClassification.cpp
+++ b/lib/AST/ExprClassification.cpp
@@ -283,7 +283,7 @@
   case Expr::CXXMemberCallExprClass:
   case Expr::UserDefinedLiteralClass:
   case Expr::CUDAKernelCallExprClass:
-    return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType());
+    return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType(Ctx));
 
     // __builtin_choose_expr is equivalent to the chosen expression.
   case Expr::ChooseExprClass:
@@ -418,9 +418,10 @@
     islvalue = NTTParm->getType()->isReferenceType();
   else
     islvalue = isa<VarDecl>(D) || isa<FieldDecl>(D) ||
-	  isa<IndirectFieldDecl>(D) ||
-      (Ctx.getLangOpts().CPlusPlus &&
-        (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)));
+               isa<IndirectFieldDecl>(D) ||
+               (Ctx.getLangOpts().CPlusPlus &&
+                (isa<FunctionDecl>(D) || isa<MSPropertyDecl>(D) ||
+                 isa<FunctionTemplateDecl>(D)));
 
   return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
 }
@@ -615,14 +616,9 @@
     return Cl::CM_IncompleteType;
 
   // Records with any const fields (recursively) are not modifiable.
-  if (const RecordType *R = CT->getAs<RecordType>()) {
-    assert((E->getObjectKind() == OK_ObjCProperty ||
-            !Ctx.getLangOpts().CPlusPlus) &&
-           "C++ struct assignment should be resolved by the "
-           "copy assignment operator.");
+  if (const RecordType *R = CT->getAs<RecordType>())
     if (R->hasConstFields())
       return Cl::CM_ConstQualified;
-  }
 
   return Cl::CM_Modifiable;
 }
diff --git a/lib/AST/ExprConstant.cpp b/lib/AST/ExprConstant.cpp
index 9a2c552..083572b 100644
--- a/lib/AST/ExprConstant.cpp
+++ b/lib/AST/ExprConstant.cpp
@@ -1422,6 +1422,17 @@
   return Decl && Decl->isWeak();
 }
 
+static bool isZeroSized(const LValue &Value) {
+  const ValueDecl *Decl = GetLValueBaseDecl(Value);
+  if (Decl && isa<VarDecl>(Decl)) {
+    QualType Ty = Decl->getType();
+    if (Ty->isArrayType())
+      return Ty->isIncompleteType() ||
+             Decl->getASTContext().getTypeSize(Ty) == 0;
+  }
+  return false;
+}
+
 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
   // A null base expression indicates a null pointer.  These are always
   // evaluatable, and they are false unless the offset is zero.
@@ -2162,7 +2173,7 @@
     assert(Value && "missing value for complete object");
   }
 
-  LLVM_EXPLICIT operator bool() const { return Value; }
+  explicit operator bool() const { return Value; }
 };
 
 /// Find the designated sub-object of an rvalue.
@@ -4829,6 +4840,7 @@
   case CK_CPointerToObjCPointerCast:
   case CK_BlockPointerToObjCPointerCast:
   case CK_AnyPointerToBlockPointerCast:
+  case CK_AddressSpaceConversion:
     if (!Visit(SubExpr))
       return false;
     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
@@ -5462,6 +5474,9 @@
   bool VisitCallExpr(const CallExpr *E) {
     return VisitConstructExpr(E);
   }
+  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
+    return VisitConstructExpr(E);
+  }
 };
 } // end anonymous namespace
 
@@ -6819,7 +6834,7 @@
 }
 
 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
-  if (E->isAssignmentOp())
+  if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
     return Error(E);
 
   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
@@ -6831,7 +6846,11 @@
   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
     ComplexValue LHS, RHS;
     bool LHSOK;
-    if (E->getLHS()->getType()->isRealFloatingType()) {
+    if (E->isAssignmentOp()) {
+      LValue LV;
+      EvaluateLValue(E->getLHS(), LV, Info);
+      LHSOK = false;
+    } else if (LHSTy->isRealFloatingType()) {
       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
       if (LHSOK) {
         LHS.makeComplexFloat();
@@ -6978,6 +6997,11 @@
             (RHSValue.Base && RHSValue.Offset.isZero() &&
              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
           return Error(E);
+        // We can't tell whether an object is at the same address as another
+        // zero sized object.
+        if ((RHSValue.Base && isZeroSized(LHSValue)) ||
+            (LHSValue.Base && isZeroSized(RHSValue)))
+          return Error(E);
         // Pointers with different bases cannot represent the same object.
         // (Note that clang defaults to -fmerge-all-constants, which can
         // lead to inconsistent results for comparisons involving the address
@@ -7566,10 +7590,23 @@
   else if (S->getString().getAsInteger(0, fill))
     return false;
 
-  if (SNaN)
-    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
-  else
-    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
+  if (Context.getTargetInfo().isNan2008()) {
+    if (SNaN)
+      Result = llvm::APFloat::getSNaN(Sem, false, &fill);
+    else
+      Result = llvm::APFloat::getQNaN(Sem, false, &fill);
+  } else {
+    // Prior to IEEE 754-2008, architectures were allowed to choose whether
+    // the first bit of their significand was set for qNaN or sNaN. MIPS chose
+    // a different encoding to what became a standard in 2008, and for pre-
+    // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
+    // sNaN. This is now known as "legacy NaN" encoding.
+    if (SNaN)
+      Result = llvm::APFloat::getQNaN(Sem, false, &fill);
+    else
+      Result = llvm::APFloat::getSNaN(Sem, false, &fill);
+  }
+
   return true;
 }
 
@@ -9071,7 +9108,8 @@
   ArgVector ArgValues(Args.size());
   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
        I != E; ++I) {
-    if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
+    if ((*I)->isValueDependent() ||
+        !Evaluate(ArgValues[I - Args.begin()], Info, *I))
       // If evaluation fails, throw away the argument entirely.
       ArgValues[I - Args.begin()] = APValue();
     if (Info.EvalStatus.HasSideEffects)
diff --git a/lib/AST/ItaniumCXXABI.cpp b/lib/AST/ItaniumCXXABI.cpp
index 384c2ac..378121c 100644
--- a/lib/AST/ItaniumCXXABI.cpp
+++ b/lib/AST/ItaniumCXXABI.cpp
@@ -29,12 +29,33 @@
 
 namespace {
 
+/// According to Itanium C++ ABI 5.1.2:
+/// the name of an anonymous union is considered to be
+/// the name of the first named data member found by a pre-order,
+/// depth-first, declaration-order walk of the data members of
+/// the anonymous union.
+/// If there is no such data member (i.e., if all of the data members
+/// in the union are unnamed), then there is no way for a program to
+/// refer to the anonymous union, and there is therefore no need to mangle its name.
+///
+/// Returns the name of anonymous union VarDecl or nullptr if it is not found.
+static const IdentifierInfo *findAnonymousUnionVarDeclName(const VarDecl& VD) {
+  const RecordType *RT = VD.getType()->getAs<RecordType>();
+  assert(RT && "type of VarDecl is expected to be RecordType.");
+  assert(RT->getDecl()->isUnion() && "RecordType is expected to be a union.");
+  if (const FieldDecl *FD = RT->getDecl()->findFirstNamedDataMember()) {
+    return FD->getIdentifier();
+  }
+
+  return nullptr;
+}
+
 /// \brief Keeps track of the mangled names of lambda expressions and block
 /// literals within a particular context.
 class ItaniumNumberingContext : public MangleNumberingContext {
   llvm::DenseMap<const Type *, unsigned> ManglingNumbers;
-  llvm::DenseMap<IdentifierInfo *, unsigned> VarManglingNumbers;
-  llvm::DenseMap<IdentifierInfo *, unsigned> TagManglingNumbers;
+  llvm::DenseMap<const IdentifierInfo *, unsigned> VarManglingNumbers;
+  llvm::DenseMap<const IdentifierInfo *, unsigned> TagManglingNumbers;
 
 public:
   unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override {
@@ -60,7 +81,12 @@
 
   /// Variable decls are numbered by identifier.
   unsigned getManglingNumber(const VarDecl *VD, unsigned) override {
-    return ++VarManglingNumbers[VD->getIdentifier()];
+    const IdentifierInfo *Identifier = VD->getIdentifier();
+    if (!Identifier) {
+      // VarDecl without an identifier represents an anonymous union declaration.
+      Identifier = findAnonymousUnionVarDeclName(*VD);
+    }
+    return ++VarManglingNumbers[Identifier];
   }
 
   unsigned getManglingNumber(const TagDecl *TD, unsigned) override {
diff --git a/lib/AST/ItaniumMangle.cpp b/lib/AST/ItaniumMangle.cpp
index 9e9c171..b2a1b24 100644
--- a/lib/AST/ItaniumMangle.cpp
+++ b/lib/AST/ItaniumMangle.cpp
@@ -69,6 +69,14 @@
   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
     return getEffectiveDeclContext(CD);
 
+  if (const auto *VD = dyn_cast<VarDecl>(D))
+    if (VD->isExternC())
+      return VD->getASTContext().getTranslationUnitDecl();
+
+  if (const auto *FD = dyn_cast<FunctionDecl>(D))
+    if (FD->isExternC())
+      return FD->getASTContext().getTranslationUnitDecl();
+
   return DC;
 }
 
@@ -117,7 +125,7 @@
   typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
-  
+
 public:
   explicit ItaniumMangleContextImpl(ASTContext &Context,
                                     DiagnosticsEngine &Diags)
@@ -156,12 +164,16 @@
   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
   void mangleDynamicAtExitDestructor(const VarDecl *D,
                                      raw_ostream &Out) override;
+  void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
+                                 raw_ostream &Out) override;
   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
   void mangleItaniumThreadLocalWrapper(const VarDecl *D,
                                        raw_ostream &) override;
 
   void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
 
+  void mangleCXXVTableBitSet(const CXXRecordDecl *RD, raw_ostream &) override;
+
   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
     // Lambda closure types are already numbered.
     if (isLambda(ND))
@@ -284,7 +296,7 @@
 #endif
   raw_ostream &getStream() { return Out; }
 
-  void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
+  void mangle(const NamedDecl *D);
   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
   void mangleNumber(const llvm::APSInt &I);
   void mangleNumber(int64_t Number);
@@ -317,10 +329,8 @@
   void addSubstitution(uintptr_t Ptr);
 
   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
-                              NamedDecl *firstQualifierLookup,
                               bool recursive = false);
   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
-                            NamedDecl *firstQualifierLookup,
                             DeclarationName name,
                             unsigned KnownArity = UnknownArity);
 
@@ -350,6 +360,9 @@
   void manglePrefix(QualType type);
   void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
   void mangleTemplatePrefix(TemplateName Template);
+  bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
+                                      StringRef Prefix = "");
+  void mangleOperatorName(DeclarationName Name, unsigned Arity);
   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
   void mangleQualifiers(Qualifiers Quals);
   void mangleRefQualifier(RefQualifierKind RefQualifier);
@@ -370,12 +383,14 @@
   void mangleAArch64NeonVectorType(const VectorType *T);
 
   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
+  void mangleMemberExprBase(const Expr *base, bool isArrow);
   void mangleMemberExpr(const Expr *base, bool isArrow,
                         NestedNameSpecifier *qualifier,
                         NamedDecl *firstQualifierLookup,
                         DeclarationName name,
                         unsigned knownArity);
   void mangleCastExpression(const Expr *E, StringRef CastEncoding);
+  void mangleInitListElements(const InitListExpr *InitList);
   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
   void mangleCXXCtorType(CXXCtorType T);
   void mangleCXXDtorType(CXXDtorType T);
@@ -439,11 +454,11 @@
   return true;
 }
 
-void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
+void CXXNameMangler::mangle(const NamedDecl *D) {
   // <mangled-name> ::= _Z <encoding>
   //            ::= <data name>
   //            ::= <special-name>
-  Out << Prefix;
+  Out << "_Z";
   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
     mangleFunctionEncoding(FD);
   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
@@ -748,8 +763,7 @@
 }
 
 void CXXNameMangler::manglePrefix(QualType type) {
-  if (const TemplateSpecializationType *TST =
-        type->getAs<TemplateSpecializationType>()) {
+  if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
     if (!mangleSubstitution(QualType(TST, 0))) {
       mangleTemplatePrefix(TST->getTemplateName());
         
@@ -759,17 +773,19 @@
       mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
       addSubstitution(QualType(TST, 0));
     }
-  } else if (const DependentTemplateSpecializationType *DTST
-               = type->getAs<DependentTemplateSpecializationType>()) {
-    TemplateName Template
-      = getASTContext().getDependentTemplateName(DTST->getQualifier(), 
-                                                 DTST->getIdentifier());
-    mangleTemplatePrefix(Template);
+  } else if (const auto *DTST =
+                 type->getAs<DependentTemplateSpecializationType>()) {
+    if (!mangleSubstitution(QualType(DTST, 0))) {
+      TemplateName Template = getASTContext().getDependentTemplateName(
+          DTST->getQualifier(), DTST->getIdentifier());
+      mangleTemplatePrefix(Template);
 
-    // FIXME: GCC does not appear to mangle the template arguments when
-    // the template in question is a dependent template name. Should we
-    // emulate that badness?
-    mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
+      // FIXME: GCC does not appear to mangle the template arguments when
+      // the template in question is a dependent template name. Should we
+      // emulate that badness?
+      mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
+      addSubstitution(QualType(DTST, 0));
+    }
   } else {
     // We use the QualType mangle type variant here because it handles
     // substitutions.
@@ -779,12 +795,9 @@
 
 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
 ///
-/// \param firstQualifierLookup - the entity found by unqualified lookup
-///   for the first name in the qualifier, if this is for a member expression
 /// \param recursive - true if this is being called recursively,
 ///   i.e. if there is more prefix "to the right".
 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
-                                            NamedDecl *firstQualifierLookup,
                                             bool recursive) {
 
   // x, ::x
@@ -817,7 +830,7 @@
 
   case NestedNameSpecifier::Namespace:
     if (qualifier->getPrefix())
-      mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
+      mangleUnresolvedPrefix(qualifier->getPrefix(),
                              /*recursive*/ true);
     else
       Out << "sr";
@@ -825,7 +838,7 @@
     break;
   case NestedNameSpecifier::NamespaceAlias:
     if (qualifier->getPrefix())
-      mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
+      mangleUnresolvedPrefix(qualifier->getPrefix(),
                              /*recursive*/ true);
     else
       Out << "sr";
@@ -842,193 +855,26 @@
     //   - a template template parameter with arguments
     // In all of these cases, we should have no prefix.
     if (qualifier->getPrefix()) {
-      mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
+      mangleUnresolvedPrefix(qualifier->getPrefix(),
                              /*recursive*/ true);
     } else {
       // Otherwise, all the cases want this.
       Out << "sr";
     }
 
-    // Only certain other types are valid as prefixes;  enumerate them.
-    switch (type->getTypeClass()) {
-    case Type::Builtin:
-    case Type::Complex:
-    case Type::Adjusted:
-    case Type::Decayed:
-    case Type::Pointer:
-    case Type::BlockPointer:
-    case Type::LValueReference:
-    case Type::RValueReference:
-    case Type::MemberPointer:
-    case Type::ConstantArray:
-    case Type::IncompleteArray:
-    case Type::VariableArray:
-    case Type::DependentSizedArray:
-    case Type::DependentSizedExtVector:
-    case Type::Vector:
-    case Type::ExtVector:
-    case Type::FunctionProto:
-    case Type::FunctionNoProto:
-    case Type::Enum:
-    case Type::Paren:
-    case Type::Elaborated:
-    case Type::Attributed:
-    case Type::Auto:
-    case Type::PackExpansion:
-    case Type::ObjCObject:
-    case Type::ObjCInterface:
-    case Type::ObjCObjectPointer:
-    case Type::Atomic:
-      llvm_unreachable("type is illegal as a nested name specifier");
-
-    case Type::SubstTemplateTypeParmPack:
-      // FIXME: not clear how to mangle this!
-      // template <class T...> class A {
-      //   template <class U...> void foo(decltype(T::foo(U())) x...);
-      // };
-      Out << "_SUBSTPACK_";
-      break;
-
-    // <unresolved-type> ::= <template-param>
-    //                   ::= <decltype>
-    //                   ::= <template-template-param> <template-args>
-    // (this last is not official yet)
-    case Type::TypeOfExpr:
-    case Type::TypeOf:
-    case Type::Decltype:
-    case Type::TemplateTypeParm:
-    case Type::UnaryTransform:
-    case Type::SubstTemplateTypeParm:
-    unresolvedType:
-      assert(!qualifier->getPrefix());
-
-      // We only get here recursively if we're followed by identifiers.
-      if (recursive) Out << 'N';
-
-      // This seems to do everything we want.  It's not really
-      // sanctioned for a substituted template parameter, though.
-      mangleType(QualType(type, 0));
-
-      // We never want to print 'E' directly after an unresolved-type,
-      // so we return directly.
+    if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
       return;
 
-    case Type::Typedef:
-      mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
-      break;
-
-    case Type::UnresolvedUsing:
-      mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
-                         ->getIdentifier());
-      break;
-
-    case Type::Record:
-      mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
-      break;
-
-    case Type::TemplateSpecialization: {
-      const TemplateSpecializationType *tst
-        = cast<TemplateSpecializationType>(type);
-      TemplateName name = tst->getTemplateName();
-      switch (name.getKind()) {
-      case TemplateName::Template:
-      case TemplateName::QualifiedTemplate: {
-        TemplateDecl *temp = name.getAsTemplateDecl();
-
-        // If the base is a template template parameter, this is an
-        // unresolved type.
-        assert(temp && "no template for template specialization type");
-        if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
-
-        mangleSourceName(temp->getIdentifier());
-        break;
-      }
-
-      case TemplateName::OverloadedTemplate:
-      case TemplateName::DependentTemplate:
-        llvm_unreachable("invalid base for a template specialization type");
-
-      case TemplateName::SubstTemplateTemplateParm: {
-        SubstTemplateTemplateParmStorage *subst
-          = name.getAsSubstTemplateTemplateParm();
-        mangleExistingSubstitution(subst->getReplacement());
-        break;
-      }
-
-      case TemplateName::SubstTemplateTemplateParmPack: {
-        // FIXME: not clear how to mangle this!
-        // template <template <class U> class T...> class A {
-        //   template <class U...> void foo(decltype(T<U>::foo) x...);
-        // };
-        Out << "_SUBSTPACK_";
-        break;
-      }
-      }
-
-      mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
-      break;
-    }
-
-    case Type::InjectedClassName:
-      mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
-                         ->getIdentifier());
-      break;
-
-    case Type::DependentName:
-      mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
-      break;
-
-    case Type::DependentTemplateSpecialization: {
-      const DependentTemplateSpecializationType *tst
-        = cast<DependentTemplateSpecializationType>(type);
-      mangleSourceName(tst->getIdentifier());
-      mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
-      break;
-    }
-    }
     break;
   }
 
   case NestedNameSpecifier::Identifier:
     // Member expressions can have these without prefixes.
-    if (qualifier->getPrefix()) {
-      mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
+    if (qualifier->getPrefix())
+      mangleUnresolvedPrefix(qualifier->getPrefix(),
                              /*recursive*/ true);
-    } else if (firstQualifierLookup) {
-
-      // Try to make a proper qualifier out of the lookup result, and
-      // then just recurse on that.
-      NestedNameSpecifier *newQualifier;
-      if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
-        QualType type = getASTContext().getTypeDeclType(typeDecl);
-
-        // Pretend we had a different nested name specifier.
-        newQualifier = NestedNameSpecifier::Create(getASTContext(),
-                                                   /*prefix*/ nullptr,
-                                                   /*template*/ false,
-                                                   type.getTypePtr());
-      } else if (NamespaceDecl *nspace =
-                   dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
-        newQualifier = NestedNameSpecifier::Create(getASTContext(),
-                                                   /*prefix*/ nullptr,
-                                                   nspace);
-      } else if (NamespaceAliasDecl *alias =
-                   dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
-        newQualifier = NestedNameSpecifier::Create(getASTContext(),
-                                                   /*prefix*/ nullptr,
-                                                   alias);
-      } else {
-        // No sensible mangling to do here.
-        newQualifier = nullptr;
-      }
-
-      if (newQualifier)
-        return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr,
-                                      recursive);
-
-    } else {
+    else
       Out << "sr";
-    }
 
     mangleSourceName(qualifier->getAsIdentifier());
     break;
@@ -1043,34 +889,41 @@
 /// Mangle an unresolved-name, which is generally used for names which
 /// weren't resolved to specific entities.
 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
-                                          NamedDecl *firstQualifierLookup,
                                           DeclarationName name,
                                           unsigned knownArity) {
-  if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
-  mangleUnqualifiedName(nullptr, name, knownArity);
-}
-
-static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
-  assert(RD->isAnonymousStructOrUnion() &&
-         "Expected anonymous struct or union!");
-  
-  for (const auto *I : RD->fields()) {
-    if (I->getIdentifier())
-      return I;
-    
-    if (const RecordType *RT = I->getType()->getAs<RecordType>())
-      if (const FieldDecl *NamedDataMember = 
-          FindFirstNamedDataMember(RT->getDecl()))
-        return NamedDataMember;
+  if (qualifier) mangleUnresolvedPrefix(qualifier);
+  switch (name.getNameKind()) {
+    // <base-unresolved-name> ::= <simple-id>
+    case DeclarationName::Identifier:
+      mangleSourceName(name.getAsIdentifierInfo());
+      break;
+    // <base-unresolved-name> ::= dn <destructor-name>
+    case DeclarationName::CXXDestructorName:
+      Out << "dn";
+      mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
+      break;
+    // <base-unresolved-name> ::= on <operator-name>
+    case DeclarationName::CXXConversionFunctionName:
+    case DeclarationName::CXXLiteralOperatorName:
+    case DeclarationName::CXXOperatorName:
+      Out << "on";
+      mangleOperatorName(name, knownArity);
+      break;
+    case DeclarationName::CXXConstructorName:
+      llvm_unreachable("Can't mangle a constructor name!");
+    case DeclarationName::CXXUsingDirective:
+      llvm_unreachable("Can't mangle a using directive name!");
+    case DeclarationName::ObjCMultiArgSelector:
+    case DeclarationName::ObjCOneArgSelector:
+    case DeclarationName::ObjCZeroArgSelector:
+      llvm_unreachable("Can't mangle Objective-C selector names here!");
   }
-
-  // We didn't find a named data member.
-  return nullptr;
 }
 
 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
                                            DeclarationName Name,
                                            unsigned KnownArity) {
+  unsigned Arity = KnownArity;
   //  <unqualified-name> ::= <operator-name>
   //                     ::= <ctor-dtor-name>
   //                     ::= <source-name>
@@ -1104,9 +957,9 @@
 
     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
       // We must have an anonymous union or struct declaration.
-      const RecordDecl *RD = 
+      const RecordDecl *RD =
         cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
-      
+
       // Itanium C++ ABI 5.1.2:
       //
       //   For the purposes of mangling, the name of an anonymous union is
@@ -1116,14 +969,16 @@
       //   the data members in the union are unnamed), then there is no way for
       //   a program to refer to the anonymous union, and there is therefore no
       //   need to mangle its name.
-      const FieldDecl *FD = FindFirstNamedDataMember(RD);
+      assert(RD->isAnonymousStructOrUnion()
+             && "Expected anonymous struct or union!");
+      const FieldDecl *FD = RD->findFirstNamedDataMember();
 
       // It's actually possible for various reasons for us to get here
       // with an empty anonymous struct / union.  Fortunately, it
       // doesn't really matter what name we generate.
       if (!FD) break;
       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
-      
+
       mangleSourceName(FD->getIdentifier());
       break;
     }
@@ -1210,33 +1065,19 @@
       mangleCXXDtorType(Dtor_Complete);
     break;
 
-  case DeclarationName::CXXConversionFunctionName:
-    // <operator-name> ::= cv <type>    # (cast)
-    Out << "cv";
-    mangleType(Name.getCXXNameType());
-    break;
-
-  case DeclarationName::CXXOperatorName: {
-    unsigned Arity;
-    if (ND) {
+  case DeclarationName::CXXOperatorName:
+    if (ND && Arity == UnknownArity) {
       Arity = cast<FunctionDecl>(ND)->getNumParams();
 
-      // If we have a C++ member function, we need to include the 'this' pointer.
-      // FIXME: This does not make sense for operators that are static, but their
-      // names stay the same regardless of the arity (operator new for instance).
-      if (isa<CXXMethodDecl>(ND))
-        Arity++;
-    } else
-      Arity = KnownArity;
-
-    mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
-    break;
-  }
-
+      // If we have a member function, we need to include the 'this' pointer.
+      if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
+        if (!MD->isStatic())
+          Arity++;
+    }
+  // FALLTHROUGH
+  case DeclarationName::CXXConversionFunctionName:
   case DeclarationName::CXXLiteralOperatorName:
-    // FIXME: This mangling is not yet official.
-    Out << "li";
-    mangleSourceName(Name.getCXXLiteralIdentifier());
+    mangleOperatorName(Name, Arity);
     break;
 
   case DeclarationName::CXXUsingDirective:
@@ -1545,7 +1386,8 @@
    
   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
   assert(Dependent && "Unknown template name kind?");
-  manglePrefix(Dependent->getQualifier());
+  if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
+    manglePrefix(Qualifier);
   mangleUnscopedTemplateName(Template);
 }
 
@@ -1607,7 +1449,7 @@
 
     // <class-enum-type> ::= <name>
     // <name> ::= <nested-name>
-    mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr);
+    mangleUnresolvedPrefix(Dependent->getQualifier());
     mangleSourceName(Dependent->getIdentifier());
     break;
   }
@@ -1636,6 +1478,181 @@
   addSubstitution(TN);
 }
 
+bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
+                                                    StringRef Prefix) {
+  // Only certain other types are valid as prefixes;  enumerate them.
+  switch (Ty->getTypeClass()) {
+  case Type::Builtin:
+  case Type::Complex:
+  case Type::Adjusted:
+  case Type::Decayed:
+  case Type::Pointer:
+  case Type::BlockPointer:
+  case Type::LValueReference:
+  case Type::RValueReference:
+  case Type::MemberPointer:
+  case Type::ConstantArray:
+  case Type::IncompleteArray:
+  case Type::VariableArray:
+  case Type::DependentSizedArray:
+  case Type::DependentSizedExtVector:
+  case Type::Vector:
+  case Type::ExtVector:
+  case Type::FunctionProto:
+  case Type::FunctionNoProto:
+  case Type::Paren:
+  case Type::Attributed:
+  case Type::Auto:
+  case Type::PackExpansion:
+  case Type::ObjCObject:
+  case Type::ObjCInterface:
+  case Type::ObjCObjectPointer:
+  case Type::Atomic:
+    llvm_unreachable("type is illegal as a nested name specifier");
+
+  case Type::SubstTemplateTypeParmPack:
+    // FIXME: not clear how to mangle this!
+    // template <class T...> class A {
+    //   template <class U...> void foo(decltype(T::foo(U())) x...);
+    // };
+    Out << "_SUBSTPACK_";
+    break;
+
+  // <unresolved-type> ::= <template-param>
+  //                   ::= <decltype>
+  //                   ::= <template-template-param> <template-args>
+  // (this last is not official yet)
+  case Type::TypeOfExpr:
+  case Type::TypeOf:
+  case Type::Decltype:
+  case Type::TemplateTypeParm:
+  case Type::UnaryTransform:
+  case Type::SubstTemplateTypeParm:
+  unresolvedType:
+    // Some callers want a prefix before the mangled type.
+    Out << Prefix;
+
+    // This seems to do everything we want.  It's not really
+    // sanctioned for a substituted template parameter, though.
+    mangleType(Ty);
+
+    // We never want to print 'E' directly after an unresolved-type,
+    // so we return directly.
+    return true;
+
+  case Type::Typedef:
+    mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
+    break;
+
+  case Type::UnresolvedUsing:
+    mangleSourceName(
+        cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
+    break;
+
+  case Type::Enum:
+  case Type::Record:
+    mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
+    break;
+
+  case Type::TemplateSpecialization: {
+    const TemplateSpecializationType *TST =
+        cast<TemplateSpecializationType>(Ty);
+    TemplateName TN = TST->getTemplateName();
+    switch (TN.getKind()) {
+    case TemplateName::Template:
+    case TemplateName::QualifiedTemplate: {
+      TemplateDecl *TD = TN.getAsTemplateDecl();
+
+      // If the base is a template template parameter, this is an
+      // unresolved type.
+      assert(TD && "no template for template specialization type");
+      if (isa<TemplateTemplateParmDecl>(TD))
+        goto unresolvedType;
+
+      mangleSourceName(TD->getIdentifier());
+      break;
+    }
+
+    case TemplateName::OverloadedTemplate:
+    case TemplateName::DependentTemplate:
+      llvm_unreachable("invalid base for a template specialization type");
+
+    case TemplateName::SubstTemplateTemplateParm: {
+      SubstTemplateTemplateParmStorage *subst =
+          TN.getAsSubstTemplateTemplateParm();
+      mangleExistingSubstitution(subst->getReplacement());
+      break;
+    }
+
+    case TemplateName::SubstTemplateTemplateParmPack: {
+      // FIXME: not clear how to mangle this!
+      // template <template <class U> class T...> class A {
+      //   template <class U...> void foo(decltype(T<U>::foo) x...);
+      // };
+      Out << "_SUBSTPACK_";
+      break;
+    }
+    }
+
+    mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
+    break;
+  }
+
+  case Type::InjectedClassName:
+    mangleSourceName(
+        cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
+    break;
+
+  case Type::DependentName:
+    mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
+    break;
+
+  case Type::DependentTemplateSpecialization: {
+    const DependentTemplateSpecializationType *DTST =
+        cast<DependentTemplateSpecializationType>(Ty);
+    mangleSourceName(DTST->getIdentifier());
+    mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
+    break;
+  }
+
+  case Type::Elaborated:
+    return mangleUnresolvedTypeOrSimpleId(
+        cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
+  }
+
+  return false;
+}
+
+void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
+  switch (Name.getNameKind()) {
+  case DeclarationName::CXXConstructorName:
+  case DeclarationName::CXXDestructorName:
+  case DeclarationName::CXXUsingDirective:
+  case DeclarationName::Identifier:
+  case DeclarationName::ObjCMultiArgSelector:
+  case DeclarationName::ObjCOneArgSelector:
+  case DeclarationName::ObjCZeroArgSelector:
+    llvm_unreachable("Not an operator name");
+
+  case DeclarationName::CXXConversionFunctionName:
+    // <operator-name> ::= cv <type>    # (cast)
+    Out << "cv";
+    mangleType(Name.getCXXNameType());
+    break;
+
+  case DeclarationName::CXXLiteralOperatorName:
+    Out << "li";
+    mangleSourceName(Name.getCXXLiteralIdentifier());
+    return;
+
+  case DeclarationName::CXXOperatorName:
+    mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
+    break;
+  }
+}
+
+
+
 void
 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
   switch (OO) {
@@ -1840,6 +1857,19 @@
   Context.mangleObjCMethodName(MD, Out);
 }
 
+static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
+  if (Quals)
+    return true;
+  if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
+    return true;
+  if (Ty->isOpenCLSpecificType())
+    return true;
+  if (Ty->isBuiltinType())
+    return false;
+
+  return true;
+}
+
 void CXXNameMangler::mangleType(QualType T) {
   // If our type is instantiation-dependent but not dependent, we mangle
   // it as it was written in the source, removing any top-level sugar. 
@@ -1881,7 +1911,7 @@
   Qualifiers quals = split.Quals;
   const Type *ty = split.Ty;
 
-  bool isSubstitutable = quals || !isa<BuiltinType>(T);
+  bool isSubstitutable = isTypeSubstitutable(quals, ty);
   if (isSubstitutable && mangleSubstitution(T))
     return;
 
@@ -2522,6 +2552,29 @@
 
 }
 
+void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
+  // Ignore member expressions involving anonymous unions.
+  while (const auto *RT = Base->getType()->getAs<RecordType>()) {
+    if (!RT->getDecl()->isAnonymousStructOrUnion())
+      break;
+    const auto *ME = dyn_cast<MemberExpr>(Base);
+    if (!ME)
+      break;
+    Base = ME->getBase();
+    IsArrow = ME->isArrow();
+  }
+
+  if (Base->isImplicitCXXThis()) {
+    // Note: GCC mangles member expressions to the implicit 'this' as
+    // *this., whereas we represent them as this->. The Itanium C++ ABI
+    // does not specify anything here, so we follow GCC.
+    Out << "dtdefpT";
+  } else {
+    Out << (IsArrow ? "pt" : "dt");
+    mangleExpression(Base);
+  }
+}
+
 /// Mangles a member expression.
 void CXXNameMangler::mangleMemberExpr(const Expr *base,
                                       bool isArrow,
@@ -2531,30 +2584,9 @@
                                       unsigned arity) {
   // <expression> ::= dt <expression> <unresolved-name>
   //              ::= pt <expression> <unresolved-name>
-  if (base) {
-
-    // Ignore member expressions involving anonymous unions.
-    while (const auto *RT = base->getType()->getAs<RecordType>()) {
-      if (!RT->getDecl()->isAnonymousStructOrUnion())
-        break;
-      const auto *ME = dyn_cast<MemberExpr>(base);
-      if (!ME)
-        break;
-      base = ME->getBase();
-      isArrow = ME->isArrow();
-    }
-
-    if (base->isImplicitCXXThis()) {
-      // Note: GCC mangles member expressions to the implicit 'this' as
-      // *this., whereas we represent them as this->. The Itanium C++ ABI
-      // does not specify anything here, so we follow GCC.
-      Out << "dtdefpT";
-    } else {
-      Out << (isArrow ? "pt" : "dt");
-      mangleExpression(base);
-    }
-  }
-  mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
+  if (base)
+    mangleMemberExprBase(base, isArrow);
+  mangleUnresolvedName(qualifier, member, arity);
 }
 
 /// Look at the callee of the given call expression and determine if
@@ -2595,6 +2627,13 @@
   mangleExpression(ECE->getSubExpr());
 }
 
+void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
+  if (auto *Syntactic = InitList->getSyntacticForm())
+    InitList = Syntactic;
+  for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
+    mangleExpression(InitList->getInit(i));
+}
+
 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
   // <expression> ::= <unary operator-name> <expression>
   //              ::= <binary operator-name> <expression> <expression>
@@ -2644,7 +2683,6 @@
 
   // FIXME: invent manglings for all these.
   case Expr::BlockExprClass:
-  case Expr::CXXPseudoDestructorExprClass:
   case Expr::ChooseExprClass:
   case Expr::CompoundLiteralExprClass:
   case Expr::ExtVectorElementExprClass:
@@ -2716,9 +2754,7 @@
 
   case Expr::InitListExprClass: {
     Out << "il";
-    const InitListExpr *InitList = cast<InitListExpr>(E);
-    for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
-      mangleExpression(InitList->getInit(i));
+    mangleInitListElements(cast<InitListExpr>(E));
     Out << "E";
     break;
   }
@@ -2762,9 +2798,14 @@
       Out << "cl";
     }
 
-    mangleExpression(CE->getCallee(), CE->getNumArgs());
-    for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
-      mangleExpression(CE->getArg(I));
+    unsigned CallArity = CE->getNumArgs();
+    for (const Expr *Arg : CE->arguments())
+      if (isa<PackExpansionExpr>(Arg))
+        CallArity = UnknownArity;
+
+    mangleExpression(CE->getCallee(), CallArity);
+    for (const Expr *Arg : CE->arguments())
+      mangleExpression(Arg);
     Out << 'E';
     break;
   }
@@ -2796,9 +2837,7 @@
       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
                  isa<InitListExpr>(Init)) {
         // Only take InitListExprs apart for list-initialization.
-        const InitListExpr *InitList = cast<InitListExpr>(Init);
-        for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
-          mangleExpression(InitList->getInit(i));
+        mangleInitListElements(cast<InitListExpr>(Init));
       } else
         mangleExpression(Init);
     }
@@ -2806,6 +2845,33 @@
     break;
   }
 
+  case Expr::CXXPseudoDestructorExprClass: {
+    const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
+    if (const Expr *Base = PDE->getBase())
+      mangleMemberExprBase(Base, PDE->isArrow());
+    NestedNameSpecifier *Qualifier = PDE->getQualifier();
+    QualType ScopeType;
+    if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
+      if (Qualifier) {
+        mangleUnresolvedPrefix(Qualifier,
+                               /*Recursive=*/true);
+        mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
+        Out << 'E';
+      } else {
+        Out << "sr";
+        if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
+          Out << 'E';
+      }
+    } else if (Qualifier) {
+      mangleUnresolvedPrefix(Qualifier);
+    }
+    // <base-unresolved-name> ::= dn <destructor-name>
+    Out << "dn";
+    QualType DestroyedType = PDE->getDestroyedType();
+    mangleUnresolvedTypeOrSimpleId(DestroyedType);
+    break;
+  }
+
   case Expr::MemberExprClass: {
     const MemberExpr *ME = cast<MemberExpr>(E);
     mangleMemberExpr(ME->getBase(), ME->isArrow(),
@@ -2837,7 +2903,7 @@
 
   case Expr::UnresolvedLookupExprClass: {
     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
-    mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity);
+    mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
 
     // All the <unresolved-name> productions end in a
     // base-unresolved-name, where <template-args> are just tacked
@@ -2859,26 +2925,55 @@
     break;
   }
 
-  case Expr::CXXTemporaryObjectExprClass:
   case Expr::CXXConstructExprClass: {
-    const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
-    unsigned N = CE->getNumArgs();
+    const auto *CE = cast<CXXConstructExpr>(E);
+    if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
+      assert(
+          CE->getNumArgs() >= 1 &&
+          (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
+          "implicit CXXConstructExpr must have one argument");
+      return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
+    }
+    Out << "il";
+    for (auto *E : CE->arguments())
+      mangleExpression(E);
+    Out << "E";
+    break;
+  }
 
-    if (CE->isListInitialization())
+  case Expr::CXXTemporaryObjectExprClass: {
+    const auto *CE = cast<CXXTemporaryObjectExpr>(E);
+    unsigned N = CE->getNumArgs();
+    bool List = CE->isListInitialization();
+
+    if (List)
       Out << "tl";
     else
       Out << "cv";
     mangleType(CE->getType());
-    if (N != 1) Out << '_';
-    for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
-    if (N != 1) Out << 'E';
+    if (!List && N != 1)
+      Out << '_';
+    if (CE->isStdInitListInitialization()) {
+      // We implicitly created a std::initializer_list<T> for the first argument
+      // of a constructor of type U in an expression of the form U{a, b, c}.
+      // Strip all the semantic gunk off the initializer list.
+      auto *SILE =
+          cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
+      auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
+      mangleInitListElements(ILE);
+    } else {
+      for (auto *E : CE->arguments())
+        mangleExpression(E);
+    }
+    if (List || N != 1)
+      Out << 'E';
     break;
   }
 
   case Expr::CXXScalarValueInitExprClass:
-    Out <<"cv";
+    Out << "cv";
     mangleType(E->getType());
-    Out <<"_E";
+    Out << "_E";
     break;
 
   case Expr::CXXNoexceptExprClass:
@@ -3023,10 +3118,28 @@
   // Fall through to mangle the cast itself.
       
   case Expr::CStyleCastExprClass:
-  case Expr::CXXFunctionalCastExprClass:
     mangleCastExpression(E, "cv");
     break;
 
+  case Expr::CXXFunctionalCastExprClass: {
+    auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
+    // FIXME: Add isImplicit to CXXConstructExpr.
+    if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
+      if (CCE->getParenOrBraceRange().isInvalid())
+        Sub = CCE->getArg(0)->IgnoreImplicit();
+    if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
+      Sub = StdInitList->getSubExpr()->IgnoreImplicit();
+    if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
+      Out << "tl";
+      mangleType(E->getType());
+      mangleInitListElements(IL);
+      Out << "E";
+    } else {
+      mangleCastExpression(E, "cv");
+    }
+    break;
+  }
+
   case Expr::CXXStaticCastExprClass:
     mangleCastExpression(E, "sc");
     break;
@@ -3061,7 +3174,7 @@
     default:
       //  <expr-primary> ::= L <mangled-name> E # external name
       Out << 'L';
-      mangle(D, "_Z");
+      mangle(D);
       Out << 'E';
       break;
 
@@ -3104,8 +3217,7 @@
 
   case Expr::DependentScopeDeclRefExprClass: {
     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
-    mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(),
-                         Arity);
+    mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
 
     // All the <unresolved-name> productions end in a
     // base-unresolved-name, where <template-args> are just tacked
@@ -3413,8 +3525,8 @@
     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
       const ValueDecl *D = DRE->getDecl();
       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
-        Out << "L";
-        mangle(D, "_Z");
+        Out << 'L';
+        mangle(D);
         Out << 'E';
         break;
       }
@@ -3443,13 +3555,7 @@
     Out << 'L';
     // References to external entities use the mangled name; if the name would
     // not normally be manged then mangle it as unqualified.
-    //
-    // FIXME: The ABI specifies that external names here should have _Z, but
-    // gcc leaves this off.
-    if (compensateMangling)
-      mangle(D, "_Z");
-    else
-      mangle(D, "Z");
+    mangle(D);
     Out << 'E';
 
     if (compensateMangling)
@@ -3745,7 +3851,7 @@
                                  "Mangling declaration");
 
   CXXNameMangler Mangler(*this, Out, D);
-  return Mangler.mangle(D);
+  Mangler.mangle(D);
 }
 
 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
@@ -3848,6 +3954,16 @@
     Mangler.getStream() << D->getName();
 }
 
+void ItaniumMangleContextImpl::mangleSEHFilterExpression(
+    const NamedDecl *EnclosingDecl, raw_ostream &Out) {
+  CXXNameMangler Mangler(*this, Out);
+  Mangler.getStream() << "__filt_";
+  if (shouldMangleDeclName(EnclosingDecl))
+    Mangler.mangle(EnclosingDecl);
+  else
+    Mangler.getStream() << EnclosingDecl->getName();
+}
+
 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
                                                             raw_ostream &Out) {
   //  <special-name> ::= TH <object name>
@@ -3926,6 +4042,22 @@
   mangleCXXRTTIName(Ty, Out);
 }
 
+void ItaniumMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
+                                                     raw_ostream &Out) {
+  Linkage L = RD->getLinkageInternal();
+  if (L == InternalLinkage || L == UniqueExternalLinkage) {
+    // This part of the identifier needs to be unique across all translation
+    // units in the linked program. The scheme fails if multiple translation
+    // units are compiled using the same relative source file path, or if
+    // multiple translation units are built from the same source file.
+    SourceManager &SM = getASTContext().getSourceManager();
+    Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
+  }
+
+  CXXNameMangler Mangler(*this, Out);
+  Mangler.mangleType(QualType(RD->getTypeForDecl(), 0));
+}
+
 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
   llvm_unreachable("Can't mangle string literals");
 }
@@ -3934,3 +4066,4 @@
 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
   return new ItaniumMangleContextImpl(Context, Diags);
 }
+
diff --git a/lib/AST/Mangle.cpp b/lib/AST/Mangle.cpp
index 53ee442..1a061c4 100644
--- a/lib/AST/Mangle.cpp
+++ b/lib/AST/Mangle.cpp
@@ -236,7 +236,11 @@
         (void) getBlockId(cast<BlockDecl>(DC), true);
     assert((isa<TranslationUnitDecl>(DC) || isa<NamedDecl>(DC)) &&
            "expected a TranslationUnitDecl or a NamedDecl");
-    if (auto ND = dyn_cast<NamedDecl>(DC)) {
+    if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
+      mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
+    else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
+      mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
+    else if (auto ND = dyn_cast<NamedDecl>(DC)) {
       if (!shouldMangleDeclName(ND) && ND->getIdentifier())
         Stream << ND->getIdentifier()->getName();
       else {
diff --git a/lib/AST/MicrosoftMangle.cpp b/lib/AST/MicrosoftMangle.cpp
index 9fedcf5..9dbbe5b 100644
--- a/lib/AST/MicrosoftMangle.cpp
+++ b/lib/AST/MicrosoftMangle.cpp
@@ -89,6 +89,7 @@
   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
   llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
   llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
+  llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
 
 public:
   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
@@ -134,7 +135,11 @@
   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
   void mangleDynamicAtExitDestructor(const VarDecl *D,
                                      raw_ostream &Out) override;
+  void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
+                                 raw_ostream &Out) override;
   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
+  void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
+                             raw_ostream &Out) override;
   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
     // Lambda closure types are already numbered.
     if (isLambda(ND))
@@ -338,9 +343,7 @@
 
 bool
 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
-  return SL->isAscii() || SL->isWide();
-  // TODO: This needs to be updated when MSVC gains support for Unicode
-  // literals.
+  return true;
 }
 
 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
@@ -1042,8 +1045,10 @@
   // Make sure booleans are encoded as 0/1.
   if (IsBoolean && Value.getBoolValue())
     mangleNumber(1);
-  else
+  else if (Value.isSigned())
     mangleNumber(Value.getSExtValue());
+  else
+    mangleNumber(Value.getZExtValue());
 }
 
 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
@@ -1485,6 +1490,8 @@
   case BuiltinType::Int128: Out << "_L"; break;
   case BuiltinType::UInt128: Out << "_M"; break;
   case BuiltinType::Bool: Out << "_N"; break;
+  case BuiltinType::Char16: Out << "_S"; break;
+  case BuiltinType::Char32: Out << "_U"; break;
   case BuiltinType::WChar_S:
   case BuiltinType::WChar_U: Out << "_W"; break;
 
@@ -1510,8 +1517,6 @@
 
   case BuiltinType::NullPtr: Out << "$$T"; break;
 
-  case BuiltinType::Char16:
-  case BuiltinType::Char32:
   case BuiltinType::Half: {
     DiagnosticsEngine &Diags = Context.getDiags();
     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
@@ -2318,6 +2323,17 @@
   Mangler.getStream() << '@';
 }
 
+void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
+    const NamedDecl *EnclosingDecl, raw_ostream &Out) {
+  MicrosoftCXXNameMangler Mangler(*this, Out);
+  // The function body is in the same comdat as the function with the handler,
+  // so the numbering here doesn't have to be the same across TUs.
+  //
+  // <mangled-name> ::= ?filt$ <filter-number> @0
+  Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
+  Mangler.mangleName(EnclosingDecl);
+}
+
 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
   // This is just a made up unique string for the purposes of tbaa.  undname
   // does *not* know how to demangle it.
@@ -2439,14 +2455,10 @@
   Mangler.getStream() << "\01??_C@_";
 
   // <char-type>: The "kind" of string literal is encoded into the mangled name.
-  // TODO: This needs to be updated when MSVC gains support for unicode
-  // literals.
-  if (SL->isAscii())
-    Mangler.getStream() << '0';
-  else if (SL->isWide())
+  if (SL->isWide())
     Mangler.getStream() << '1';
   else
-    llvm_unreachable("unexpected string literal kind!");
+    Mangler.getStream() << '0';
 
   // <literal-length>: The next part of the mangled name consists of the length
   // of the string.
@@ -2525,42 +2537,16 @@
     } else if (isLetter(Byte & 0x7f)) {
       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
     } else {
-      switch (Byte) {
-        case ',':
-          Mangler.getStream() << "?0";
-          break;
-        case '/':
-          Mangler.getStream() << "?1";
-          break;
-        case '\\':
-          Mangler.getStream() << "?2";
-          break;
-        case ':':
-          Mangler.getStream() << "?3";
-          break;
-        case '.':
-          Mangler.getStream() << "?4";
-          break;
-        case ' ':
-          Mangler.getStream() << "?5";
-          break;
-        case '\n':
-          Mangler.getStream() << "?6";
-          break;
-        case '\t':
-          Mangler.getStream() << "?7";
-          break;
-        case '\'':
-          Mangler.getStream() << "?8";
-          break;
-        case '-':
-          Mangler.getStream() << "?9";
-          break;
-        default:
-          Mangler.getStream() << "?$";
-          Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
-          Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
-          break;
+      const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
+                                   ' ', '\n', '\t', '\'', '-'};
+      const char *Pos =
+          std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
+      if (Pos != std::end(SpecialChars)) {
+        Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
+      } else {
+        Mangler.getStream() << "?$";
+        Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
+        Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
       }
     }
   };
@@ -2569,7 +2555,10 @@
   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
        ++I)
-    MangleByte(GetBigEndianByte(I));
+    if (SL->isWide())
+      MangleByte(GetBigEndianByte(I));
+    else
+      MangleByte(GetLittleEndianByte(I));
 
   // Encode the NUL terminator if there is room.
   if (NumCharsToMangle < 32)
@@ -2580,6 +2569,11 @@
   Mangler.getStream() << '@';
 }
 
+void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
+                                                       raw_ostream &Out) {
+  llvm::report_fatal_error("Cannot mangle bitsets yet");
+}
+
 MicrosoftMangleContext *
 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
   return new MicrosoftMangleContextImpl(Context, Diags);
diff --git a/lib/AST/RecordLayoutBuilder.cpp b/lib/AST/RecordLayoutBuilder.cpp
index 0d070a4..3753d27 100644
--- a/lib/AST/RecordLayoutBuilder.cpp
+++ b/lib/AST/RecordLayoutBuilder.cpp
@@ -55,6 +55,52 @@
   const BaseSubobjectInfo *Derived;
 };
 
+/// \brief Externally provided layout. Typically used when the AST source, such
+/// as DWARF, lacks all the information that was available at compile time, such
+/// as alignment attributes on fields and pragmas in effect.
+struct ExternalLayout {
+  ExternalLayout() : Size(0), Align(0) {}
+
+  /// \brief Overall record size in bits.
+  uint64_t Size;
+
+  /// \brief Overall record alignment in bits.
+  uint64_t Align;
+
+  /// \brief Record field offsets in bits.
+  llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
+
+  /// \brief Direct, non-virtual base offsets.
+  llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
+
+  /// \brief Virtual base offsets.
+  llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
+
+  /// Get the offset of the given field. The external source must provide
+  /// entries for all fields in the record.
+  uint64_t getExternalFieldOffset(const FieldDecl *FD) {
+    assert(FieldOffsets.count(FD) &&
+           "Field does not have an external offset");
+    return FieldOffsets[FD];
+  }
+
+  bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
+    auto Known = BaseOffsets.find(RD);
+    if (Known == BaseOffsets.end())
+      return false;
+    BaseOffset = Known->second;
+    return true;
+  }
+
+  bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
+    auto Known = VirtualBaseOffsets.find(RD);
+    if (Known == VirtualBaseOffsets.end())
+      return false;
+    BaseOffset = Known->second;
+    return true;
+  }
+};
+
 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
 /// offsets while laying out a C++ class.
 class EmptySubobjectMap {
@@ -541,7 +587,7 @@
 
   /// \brief Whether the external AST source has provided a layout for this
   /// record.
-  unsigned ExternalLayout : 1;
+  unsigned UseExternalLayout : 1;
 
   /// \brief Whether we need to infer alignment, even when we have an 
   /// externally-provided layout.
@@ -607,26 +653,14 @@
   /// avoid visiting virtual bases more than once.
   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
 
-  /// \brief Externally-provided size.
-  uint64_t ExternalSize;
-  
-  /// \brief Externally-provided alignment.
-  uint64_t ExternalAlign;
-  
-  /// \brief Externally-provided field offsets.
-  llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
-
-  /// \brief Externally-provided direct, non-virtual base offsets.
-  llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
-
-  /// \brief Externally-provided virtual base offsets.
-  llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
+  /// Valid if UseExternalLayout is true.
+  ExternalLayout External;
 
   RecordLayoutBuilder(const ASTContext &Context,
                       EmptySubobjectMap *EmptySubobjects)
     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), 
       Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
-      ExternalLayout(false), InferAlignment(false), 
+      UseExternalLayout(false), InferAlignment(false),
       Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
       UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
       MaxFieldAlignment(CharUnits::Zero()), 
@@ -748,8 +782,8 @@
   void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
   void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
 
-  RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
-  void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
+  RecordLayoutBuilder(const RecordLayoutBuilder &) = delete;
+  void operator=(const RecordLayoutBuilder &) = delete;
 };
 } // end anonymous namespace
 
@@ -1134,21 +1168,12 @@
   
   // Query the external layout to see if it provides an offset.
   bool HasExternalLayout = false;
-  if (ExternalLayout) {
+  if (UseExternalLayout) {
     llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
-    if (Base->IsVirtual) {
-      Known = ExternalVirtualBaseOffsets.find(Base->Class);
-      if (Known != ExternalVirtualBaseOffsets.end()) {
-        Offset = Known->second;
-        HasExternalLayout = true;
-      }
-    } else {
-      Known = ExternalBaseOffsets.find(Base->Class);
-      if (Known != ExternalBaseOffsets.end()) {
-        Offset = Known->second;
-        HasExternalLayout = true;
-      }
-    }
+    if (Base->IsVirtual)
+      HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
+    else
+      HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
   }
   
   CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
@@ -1235,18 +1260,15 @@
   
   // If there is an external AST source, ask it for the various offsets.
   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
-    if (ExternalASTSource *External = Context.getExternalSource()) {
-      ExternalLayout = External->layoutRecordType(RD, 
-                                                  ExternalSize,
-                                                  ExternalAlign,
-                                                  ExternalFieldOffsets,
-                                                  ExternalBaseOffsets,
-                                                  ExternalVirtualBaseOffsets);
-      
+    if (ExternalASTSource *Source = Context.getExternalSource()) {
+      UseExternalLayout = Source->layoutRecordType(
+          RD, External.Size, External.Align, External.FieldOffsets,
+          External.BaseOffsets, External.VirtualBaseOffsets);
+
       // Update based on external alignment.
-      if (ExternalLayout) {
-        if (ExternalAlign > 0) {
-          Alignment = Context.toCharUnitsFromBits(ExternalAlign);
+      if (UseExternalLayout) {
+        if (External.Align > 0) {
+          Alignment = Context.toCharUnitsFromBits(External.Align);
         } else {
           // The external source didn't have alignment information; infer it.
           InferAlignment = true;
@@ -1588,7 +1610,7 @@
 
   // If we're using external layout, give the external layout a chance
   // to override this information.
-  if (ExternalLayout)
+  if (UseExternalLayout)
     FieldOffset = updateExternalFieldOffset(D, FieldOffset);
 
   // Okay, place the bitfield at the calculated offset.
@@ -1604,7 +1626,7 @@
     FieldAlign = UnpackedFieldAlign = 1;
 
   // Diagnose differences in layout due to padding or packing.
-  if (!ExternalLayout)
+  if (!UseExternalLayout)
     CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
                       UnpackedFieldAlign, FieldPacked, D);
 
@@ -1727,7 +1749,7 @@
   UnpackedFieldOffset = 
     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
 
-  if (ExternalLayout) {
+  if (UseExternalLayout) {
     FieldOffset = Context.toCharUnitsFromBits(
                     updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
     
@@ -1750,7 +1772,7 @@
   // Place this field at the current location.
   FieldOffsets.push_back(Context.toBits(FieldOffset));
 
-  if (!ExternalLayout)
+  if (!UseExternalLayout)
     CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, 
                       Context.toBits(UnpackedFieldOffset),
                       Context.toBits(UnpackedFieldAlign), FieldPacked, D);
@@ -1802,15 +1824,15 @@
   uint64_t RoundedSize
     = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
 
-  if (ExternalLayout) {
+  if (UseExternalLayout) {
     // If we're inferring alignment, and the external size is smaller than
     // our size after we've rounded up to alignment, conservatively set the
     // alignment to 1.
-    if (InferAlignment && ExternalSize < RoundedSize) {
+    if (InferAlignment && External.Size < RoundedSize) {
       Alignment = CharUnits::One();
       InferAlignment = false;
     }
-    setSize(ExternalSize);
+    setSize(External.Size);
     return;
   }
 
@@ -1846,7 +1868,7 @@
                                           CharUnits UnpackedNewAlignment) {
   // The alignment is not modified when using 'mac68k' alignment or when
   // we have an externally-supplied layout that also provides overall alignment.
-  if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
+  if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
     return;
 
   if (NewAlignment > Alignment) {
@@ -1865,11 +1887,8 @@
 uint64_t
 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, 
                                                uint64_t ComputedOffset) {
-  assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
-         "Field does not have an external offset");
-  
-  uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
-  
+  uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
+
   if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
     // The externally-supplied field offset is before the field offset we
     // computed. Assume that the structure is packed.
@@ -2152,9 +2171,8 @@
   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
   MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
 private:
-  MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
-  LLVM_DELETED_FUNCTION;
-  void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
+  MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
+  void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
 public:
   void layout(const RecordDecl *RD);
   void cxxLayout(const CXXRecordDecl *RD);
@@ -2252,6 +2270,13 @@
   /// \brief True if this class is zero sized or first base is zero sized or
   /// has this property.  Only used for MS-ABI.
   bool LeadsWithZeroSizedBase : 1;
+
+  /// \brief True if the external AST source provided a layout for this record.
+  bool UseExternalLayout : 1;
+
+  /// \brief The layout provided by the external AST source. Only active if
+  /// UseExternalLayout is true.
+  ExternalLayout External;
 };
 } // namespace
 
@@ -2371,6 +2396,13 @@
   // Packed attribute forces max field alignment to be 1.
   if (RD->hasAttr<PackedAttr>())
     MaxFieldAlignment = CharUnits::One();
+
+  // Try to respect the external layout if present.
+  UseExternalLayout = false;
+  if (ExternalASTSource *Source = Context.getExternalSource())
+    UseExternalLayout = Source->layoutRecordType(
+        RD, External.Size, External.Align, External.FieldOffsets,
+        External.BaseOffsets, External.VirtualBaseOffsets);
 }
 
 void
@@ -2475,7 +2507,18 @@
       BaseLayout.leadsWithZeroSizedBase())
     Size++;
   ElementInfo Info = getAdjustedElementInfo(BaseLayout);
-  CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
+  CharUnits BaseOffset;
+
+  // Respect the external AST source base offset, if present.
+  bool FoundBase = false;
+  if (UseExternalLayout) {
+    FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
+    if (FoundBase)
+      assert(BaseOffset >= Size && "base offset already allocated");
+  }
+
+  if (!FoundBase)
+    BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
   Bases.insert(std::make_pair(BaseDecl, BaseOffset));
   Size = BaseOffset + BaseLayout.getNonVirtualSize();
   PreviousBaseLayout = &BaseLayout;
@@ -2499,7 +2542,14 @@
     placeFieldAtOffset(CharUnits::Zero());
     Size = std::max(Size, Info.Size);
   } else {
-    CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
+    CharUnits FieldOffset;
+    if (UseExternalLayout) {
+      FieldOffset =
+          Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
+      assert(FieldOffset >= Size && "field offset already allocated");
+    } else {
+      FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
+    }
     placeFieldAtOffset(FieldOffset);
     Size = FieldOffset + Info.Size;
   }
@@ -2573,14 +2623,16 @@
   CharUnits InjectionSite = VBPtrOffset;
   // But before we do, make sure it's properly aligned.
   VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
+  // Shift everything after the vbptr down, unless we're using an external
+  // layout.
+  if (UseExternalLayout)
+    return;
   // Determine where the first field should be laid out after the vbptr.
   CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
   // Make sure that the amount we push the fields back by is a multiple of the
   // alignment.
   CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
       std::max(RequiredAlignment, Alignment));
-  // Increase the size of the object and push back all fields by the offset
-  // amount.
   Size += Offset;
   for (uint64_t &FieldOffset : FieldOffsets)
     FieldOffset += Context.toBits(Offset);
@@ -2647,7 +2699,18 @@
     }
     // Insert the virtual base.
     ElementInfo Info = getAdjustedElementInfo(BaseLayout);
-    CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
+    CharUnits BaseOffset;
+
+    // Respect the external AST source base offset, if present.
+    bool FoundBase = false;
+    if (UseExternalLayout) {
+      FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
+      if (FoundBase)
+        assert(BaseOffset >= Size && "base offset already allocated");
+    }
+    if (!FoundBase)
+      BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
+
     VBases.insert(std::make_pair(BaseDecl,
         ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
     Size = BaseOffset + BaseLayout.getNonVirtualSize();
@@ -2677,6 +2740,12 @@
     else
       Size = MinEmptyStructSize;
   }
+
+  if (UseExternalLayout) {
+    Size = Context.toCharUnitsFromBits(External.Size);
+    if (External.Align)
+      Alignment = Context.toCharUnitsFromBits(External.Align);
+  }
 }
 
 // Recursively walks the non-virtual bases of a class and determines if any of
@@ -2815,7 +2884,7 @@
 
   const ASTRecordLayout *NewEntry = nullptr;
 
-  if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
+  if (isMsLayout(D)) {
     NewEntry = BuildMicrosoftASTRecordLayout(D);
   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
     EmptySubobjectMap EmptySubobjects(*this, RD);
diff --git a/lib/AST/Stmt.cpp b/lib/AST/Stmt.cpp
index 371a7a1..64b1897 100644
--- a/lib/AST/Stmt.cpp
+++ b/lib/AST/Stmt.cpp
@@ -95,10 +95,16 @@
 Stmt *Stmt::IgnoreImplicit() {
   Stmt *s = this;
 
-  if (ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(s))
+  if (auto *ewc = dyn_cast<ExprWithCleanups>(s))
     s = ewc->getSubExpr();
 
-  while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(s))
+  if (auto *mte = dyn_cast<MaterializeTemporaryExpr>(s))
+    s = mte->GetTemporaryExpr();
+
+  if (auto *bte = dyn_cast<CXXBindTemporaryExpr>(s))
+    s = bte->getSubExpr();
+
+  while (auto *ice = dyn_cast<ImplicitCastExpr>(s))
     s = ice->getSubExpr();
 
   return s;
@@ -1487,28 +1493,26 @@
 OMPSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc,
                          SourceLocation EndLoc, unsigned CollapsedNum,
                          ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
-                         Expr *IV, Expr *LastIteration, Expr *CalcLastIteration,
-                         Expr *PreCond, Expr *Cond, Expr *SeparatedCond,
-                         Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-                         ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals) {
+                         const HelperExprs &Exprs) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPSimdDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem =
+      C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
+                 sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_simd));
   OMPSimdDirective *Dir = new (Mem)
       OMPSimdDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size());
   Dir->setClauses(Clauses);
   Dir->setAssociatedStmt(AssociatedStmt);
-  Dir->setIterationVariable(IV);
-  Dir->setLastIteration(LastIteration);
-  Dir->setCalcLastIteration(CalcLastIteration);
-  Dir->setPreCond(PreCond);
-  Dir->setCond(Cond, SeparatedCond);
-  Dir->setInit(Init);
-  Dir->setInc(Inc);
-  Dir->setCounters(Counters);
-  Dir->setUpdates(Updates);
-  Dir->setFinals(Finals);
+  Dir->setIterationVariable(Exprs.IterationVarRef);
+  Dir->setLastIteration(Exprs.LastIteration);
+  Dir->setCalcLastIteration(Exprs.CalcLastIteration);
+  Dir->setPreCond(Exprs.PreCond);
+  Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+  Dir->setInit(Exprs.Init);
+  Dir->setInc(Exprs.Inc);
+  Dir->setCounters(Exprs.Counters);
+  Dir->setUpdates(Exprs.Updates);
+  Dir->setFinals(Exprs.Finals);
   return Dir;
 }
 
@@ -1518,8 +1522,9 @@
                                                 EmptyShell) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPSimdDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem =
+      C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
+                 sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_simd));
   return new (Mem) OMPSimdDirective(CollapsedNum, NumClauses);
 }
 
@@ -1527,28 +1532,33 @@
 OMPForDirective::Create(const ASTContext &C, SourceLocation StartLoc,
                         SourceLocation EndLoc, unsigned CollapsedNum,
                         ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
-                        Expr *IV, Expr *LastIteration, Expr *CalcLastIteration,
-                        Expr *PreCond, Expr *Cond, Expr *SeparatedCond,
-                        Expr *Init, Expr *Inc, ArrayRef<Expr *> Counters,
-                        ArrayRef<Expr *> Updates, ArrayRef<Expr *> Finals) {
+                        const HelperExprs &Exprs) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPForDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem =
+      C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
+                 sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_for));
   OMPForDirective *Dir =
       new (Mem) OMPForDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size());
   Dir->setClauses(Clauses);
   Dir->setAssociatedStmt(AssociatedStmt);
-  Dir->setIterationVariable(IV);
-  Dir->setLastIteration(LastIteration);
-  Dir->setCalcLastIteration(CalcLastIteration);
-  Dir->setPreCond(PreCond);
-  Dir->setCond(Cond, SeparatedCond);
-  Dir->setInit(Init);
-  Dir->setInc(Inc);
-  Dir->setCounters(Counters);
-  Dir->setUpdates(Updates);
-  Dir->setFinals(Finals);
+  Dir->setIterationVariable(Exprs.IterationVarRef);
+  Dir->setLastIteration(Exprs.LastIteration);
+  Dir->setCalcLastIteration(Exprs.CalcLastIteration);
+  Dir->setPreCond(Exprs.PreCond);
+  Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+  Dir->setInit(Exprs.Init);
+  Dir->setInc(Exprs.Inc);
+  Dir->setIsLastIterVariable(Exprs.IL);
+  Dir->setLowerBoundVariable(Exprs.LB);
+  Dir->setUpperBoundVariable(Exprs.UB);
+  Dir->setStrideVariable(Exprs.ST);
+  Dir->setEnsureUpperBound(Exprs.EUB);
+  Dir->setNextLowerBound(Exprs.NLB);
+  Dir->setNextUpperBound(Exprs.NUB);
+  Dir->setCounters(Exprs.Counters);
+  Dir->setUpdates(Exprs.Updates);
+  Dir->setFinals(Exprs.Finals);
   return Dir;
 }
 
@@ -1558,36 +1568,43 @@
                                               EmptyShell) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPForDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem =
+      C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
+                 sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_for));
   return new (Mem) OMPForDirective(CollapsedNum, NumClauses);
 }
 
-OMPForSimdDirective *OMPForSimdDirective::Create(
-    const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
-    unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
-    Expr *IV, Expr *LastIteration, Expr *CalcLastIteration, Expr *PreCond,
-    Expr *Cond, Expr *SeparatedCond, Expr *Init, Expr *Inc,
-    ArrayRef<Expr *> Counters, ArrayRef<Expr *> Updates,
-    ArrayRef<Expr *> Finals) {
+OMPForSimdDirective *
+OMPForSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc,
+                            SourceLocation EndLoc, unsigned CollapsedNum,
+                            ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
+                            const HelperExprs &Exprs) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPForSimdDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem =
+      C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
+                 sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_for_simd));
   OMPForSimdDirective *Dir = new (Mem)
       OMPForSimdDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size());
   Dir->setClauses(Clauses);
   Dir->setAssociatedStmt(AssociatedStmt);
-  Dir->setIterationVariable(IV);
-  Dir->setLastIteration(LastIteration);
-  Dir->setCalcLastIteration(CalcLastIteration);
-  Dir->setPreCond(PreCond);
-  Dir->setCond(Cond, SeparatedCond);
-  Dir->setInit(Init);
-  Dir->setInc(Inc);
-  Dir->setCounters(Counters);
-  Dir->setUpdates(Updates);
-  Dir->setFinals(Finals);
+  Dir->setIterationVariable(Exprs.IterationVarRef);
+  Dir->setLastIteration(Exprs.LastIteration);
+  Dir->setCalcLastIteration(Exprs.CalcLastIteration);
+  Dir->setPreCond(Exprs.PreCond);
+  Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+  Dir->setInit(Exprs.Init);
+  Dir->setInc(Exprs.Inc);
+  Dir->setIsLastIterVariable(Exprs.IL);
+  Dir->setLowerBoundVariable(Exprs.LB);
+  Dir->setUpperBoundVariable(Exprs.UB);
+  Dir->setStrideVariable(Exprs.ST);
+  Dir->setEnsureUpperBound(Exprs.EUB);
+  Dir->setNextLowerBound(Exprs.NLB);
+  Dir->setNextUpperBound(Exprs.NUB);
+  Dir->setCounters(Exprs.Counters);
+  Dir->setUpdates(Exprs.Updates);
+  Dir->setFinals(Exprs.Finals);
   return Dir;
 }
 
@@ -1597,8 +1614,9 @@
                                                       EmptyShell) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPForSimdDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem =
+      C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
+                 sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_for_simd));
   return new (Mem) OMPForSimdDirective(CollapsedNum, NumClauses);
 }
 
@@ -1715,28 +1733,33 @@
 OMPParallelForDirective *OMPParallelForDirective::Create(
     const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
     unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
-    Expr *IV, Expr *LastIteration, Expr *CalcLastIteration, Expr *PreCond,
-    Expr *Cond, Expr *SeparatedCond, Expr *Init, Expr *Inc,
-    ArrayRef<Expr *> Counters, ArrayRef<Expr *> Updates,
-    ArrayRef<Expr *> Finals) {
+    const HelperExprs &Exprs) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPParallelForDirective),
                                            llvm::alignOf<OMPClause *>());
   void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+                         sizeof(Stmt *) *
+                             numLoopChildren(CollapsedNum, OMPD_parallel_for));
   OMPParallelForDirective *Dir = new (Mem)
       OMPParallelForDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size());
   Dir->setClauses(Clauses);
   Dir->setAssociatedStmt(AssociatedStmt);
-  Dir->setIterationVariable(IV);
-  Dir->setLastIteration(LastIteration);
-  Dir->setCalcLastIteration(CalcLastIteration);
-  Dir->setPreCond(PreCond);
-  Dir->setCond(Cond, SeparatedCond);
-  Dir->setInit(Init);
-  Dir->setInc(Inc);
-  Dir->setCounters(Counters);
-  Dir->setUpdates(Updates);
-  Dir->setFinals(Finals);
+  Dir->setIterationVariable(Exprs.IterationVarRef);
+  Dir->setLastIteration(Exprs.LastIteration);
+  Dir->setCalcLastIteration(Exprs.CalcLastIteration);
+  Dir->setPreCond(Exprs.PreCond);
+  Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+  Dir->setInit(Exprs.Init);
+  Dir->setInc(Exprs.Inc);
+  Dir->setIsLastIterVariable(Exprs.IL);
+  Dir->setLowerBoundVariable(Exprs.LB);
+  Dir->setUpperBoundVariable(Exprs.UB);
+  Dir->setStrideVariable(Exprs.ST);
+  Dir->setEnsureUpperBound(Exprs.EUB);
+  Dir->setNextLowerBound(Exprs.NLB);
+  Dir->setNextUpperBound(Exprs.NUB);
+  Dir->setCounters(Exprs.Counters);
+  Dir->setUpdates(Exprs.Updates);
+  Dir->setFinals(Exprs.Finals);
   return Dir;
 }
 
@@ -1746,35 +1769,41 @@
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPParallelForDirective),
                                            llvm::alignOf<OMPClause *>());
   void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+                         sizeof(Stmt *) *
+                             numLoopChildren(CollapsedNum, OMPD_parallel_for));
   return new (Mem) OMPParallelForDirective(CollapsedNum, NumClauses);
 }
 
 OMPParallelForSimdDirective *OMPParallelForSimdDirective::Create(
     const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
     unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
-    Expr *IV, Expr *LastIteration, Expr *CalcLastIteration, Expr *PreCond,
-    Expr *Cond, Expr *SeparatedCond, Expr *Init, Expr *Inc,
-    ArrayRef<Expr *> Counters, ArrayRef<Expr *> Updates,
-    ArrayRef<Expr *> Finals) {
+    const HelperExprs &Exprs) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPParallelForSimdDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem = C.Allocate(
+      Size + sizeof(OMPClause *) * Clauses.size() +
+      sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_parallel_for_simd));
   OMPParallelForSimdDirective *Dir = new (Mem) OMPParallelForSimdDirective(
       StartLoc, EndLoc, CollapsedNum, Clauses.size());
   Dir->setClauses(Clauses);
   Dir->setAssociatedStmt(AssociatedStmt);
-  Dir->setIterationVariable(IV);
-  Dir->setLastIteration(LastIteration);
-  Dir->setCalcLastIteration(CalcLastIteration);
-  Dir->setPreCond(PreCond);
-  Dir->setCond(Cond, SeparatedCond);
-  Dir->setInit(Init);
-  Dir->setInc(Inc);
-  Dir->setCounters(Counters);
-  Dir->setUpdates(Updates);
-  Dir->setFinals(Finals);
+  Dir->setIterationVariable(Exprs.IterationVarRef);
+  Dir->setLastIteration(Exprs.LastIteration);
+  Dir->setCalcLastIteration(Exprs.CalcLastIteration);
+  Dir->setPreCond(Exprs.PreCond);
+  Dir->setCond(Exprs.Cond, Exprs.SeparatedCond);
+  Dir->setInit(Exprs.Init);
+  Dir->setInc(Exprs.Inc);
+  Dir->setIsLastIterVariable(Exprs.IL);
+  Dir->setLowerBoundVariable(Exprs.LB);
+  Dir->setUpperBoundVariable(Exprs.UB);
+  Dir->setStrideVariable(Exprs.ST);
+  Dir->setEnsureUpperBound(Exprs.EUB);
+  Dir->setNextLowerBound(Exprs.NLB);
+  Dir->setNextUpperBound(Exprs.NUB);
+  Dir->setCounters(Exprs.Counters);
+  Dir->setUpdates(Exprs.Updates);
+  Dir->setFinals(Exprs.Finals);
   return Dir;
 }
 
@@ -1784,8 +1813,9 @@
                                          unsigned CollapsedNum, EmptyShell) {
   unsigned Size = llvm::RoundUpToAlignment(sizeof(OMPParallelForSimdDirective),
                                            llvm::alignOf<OMPClause *>());
-  void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses +
-                         sizeof(Stmt *) * numLoopChildren(CollapsedNum));
+  void *Mem = C.Allocate(
+      Size + sizeof(OMPClause *) * NumClauses +
+      sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_parallel_for_simd));
   return new (Mem) OMPParallelForSimdDirective(CollapsedNum, NumClauses);
 }
 
diff --git a/lib/AST/StmtPrinter.cpp b/lib/AST/StmtPrinter.cpp
index 927a679..d6e0deb 100644
--- a/lib/AST/StmtPrinter.cpp
+++ b/lib/AST/StmtPrinter.cpp
@@ -1373,24 +1373,24 @@
     return;
   }
 
-  OS << "{ ";
+  OS << "{";
   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
     if (i) OS << ", ";
     if (Node->getInit(i))
       PrintExpr(Node->getInit(i));
     else
-      OS << "0";
+      OS << "{}";
   }
-  OS << " }";
+  OS << "}";
 }
 
 void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
-  OS << "( ";
+  OS << "(";
   for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
     if (i) OS << ", ";
     PrintExpr(Node->getExpr(i));
   }
-  OS << " )";
+  OS << ")";
 }
 
 void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
@@ -1679,9 +1679,13 @@
 
 void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
   Node->getType().print(OS, Policy);
-  OS << "(";
+  // If there are no parens, this is list-initialization, and the braces are
+  // part of the syntax of the inner construct.
+  if (Node->getLParenLoc().isValid())
+    OS << "(";
   PrintExpr(Node->getSubExpr());
-  OS << ")";
+  if (Node->getLParenLoc().isValid())
+    OS << ")";
 }
 
 void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
@@ -1690,7 +1694,12 @@
 
 void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
   Node->getType().print(OS, Policy);
-  OS << "(";
+  if (Node->isStdInitListInitialization())
+    /* Nothing to do; braces are part of creating the std::initializer_list. */;
+  else if (Node->isListInitialization())
+    OS << "{";
+  else
+    OS << "(";
   for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
                                          ArgEnd = Node->arg_end();
        Arg != ArgEnd; ++Arg) {
@@ -1700,7 +1709,12 @@
       OS << ", ";
     PrintExpr(*Arg);
   }
-  OS << ")";
+  if (Node->isStdInitListInitialization())
+    /* See above. */;
+  else if (Node->isListInitialization())
+    OS << "}";
+  else
+    OS << ")";
 }
 
 void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
@@ -1866,8 +1880,8 @@
 }
 
 void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
-  if (E->isListInitialization())
-    OS << "{ ";
+  if (E->isListInitialization() && !E->isStdInitListInitialization())
+    OS << "{";
 
   for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
     if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
@@ -1879,8 +1893,8 @@
     PrintExpr(E->getArg(i));
   }
 
-  if (E->isListInitialization())
-    OS << " }";
+  if (E->isListInitialization() && !E->isStdInitListInitialization())
+    OS << "}";
 }
 
 void StmtPrinter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
diff --git a/lib/AST/TemplateBase.cpp b/lib/AST/TemplateBase.cpp
index f07b18e..f8b73cb 100644
--- a/lib/AST/TemplateBase.cpp
+++ b/lib/AST/TemplateBase.cpp
@@ -33,11 +33,26 @@
 /// \param TemplArg the TemplateArgument instance to print.
 ///
 /// \param Out the raw_ostream instance to use for printing.
+///
+/// \param Policy the printing policy for EnumConstantDecl printing.
 static void printIntegral(const TemplateArgument &TemplArg,
-                          raw_ostream &Out) {
+                          raw_ostream &Out, const PrintingPolicy& Policy) {
   const ::clang::Type *T = TemplArg.getIntegralType().getTypePtr();
   const llvm::APSInt &Val = TemplArg.getAsIntegral();
 
+  if (const EnumType *ET = T->getAs<EnumType>()) {
+    for (const EnumConstantDecl* ECD : ET->getDecl()->enumerators()) {
+      // In Sema::CheckTemplateArugment, enum template arguments value are
+      // extended to the size of the integer underlying the enum type.  This
+      // may create a size difference between the enum value and template
+      // argument value, requiring isSameValue here instead of operator==.
+      if (llvm::APSInt::isSameValue(ECD->getInitVal(), Val)) {
+        ECD->printQualifiedName(Out, Policy);
+        return;
+      }
+    }
+  }
+
   if (T->isBooleanType()) {
     Out << (Val.getBoolValue() ? "true" : "false");
   } else if (T->isCharType()) {
@@ -378,7 +393,7 @@
     break;
       
   case Integral: {
-    printIntegral(*this, Out);
+    printIntegral(*this, Out, Policy);
     break;
   }
     
diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp
index abceb8a..ace5fc3 100644
--- a/lib/AST/Type.cpp
+++ b/lib/AST/Type.cpp
@@ -541,10 +541,13 @@
 }
 
 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
-  if (const RecordType *RT = getAs<RecordType>())
-    return dyn_cast<CXXRecordDecl>(RT->getDecl());
-  else if (const InjectedClassNameType *Injected
-                                  = getAs<InjectedClassNameType>())
+  return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
+}
+
+TagDecl *Type::getAsTagDecl() const {
+  if (const auto *TT = getAs<TagType>())
+    return cast<TagDecl>(TT->getDecl());
+  if (const auto *Injected = getAs<InjectedClassNameType>())
     return Injected->getDecl();
 
   return nullptr;
@@ -1086,7 +1089,7 @@
 
 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
   if ((*this)->isArrayType())
-    return Context.getBaseElementType(*this).isTrivialType(Context);
+    return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
 
   if (Context.getLangOpts().ObjCAutoRefCount) {
     switch (getObjCLifetime()) {
@@ -1583,8 +1586,9 @@
   case CC_X86_64SysV: return "sysv_abi";
   case CC_AAPCS: return "aapcs";
   case CC_AAPCS_VFP: return "aapcs-vfp";
-  case CC_PnaclCall: return "pnaclcall";
   case CC_IntelOclBicc: return "intel_ocl_bicc";
+  case CC_SpirFunction: return "spir_function";
+  case CC_SpirKernel: return "spir_kernel";
   }
 
   llvm_unreachable("Invalid calling convention.");
@@ -1933,7 +1937,6 @@
   case attr_pascal:
   case attr_ms_abi:
   case attr_sysv_abi:
-  case attr_pnaclcall:
   case attr_inteloclbicc:
     return true;
   }
diff --git a/lib/AST/TypePrinter.cpp b/lib/AST/TypePrinter.cpp
index f36e799..0f6a2a8 100644
--- a/lib/AST/TypePrinter.cpp
+++ b/lib/AST/TypePrinter.cpp
@@ -685,9 +685,6 @@
     case CC_AAPCS_VFP:
       OS << " __attribute__((pcs(\"aapcs-vfp\")))";
       break;
-    case CC_PnaclCall:
-      OS << " __attribute__((pnaclcall))";
-      break;
     case CC_IntelOclBicc:
       OS << " __attribute__((intel_ocl_bicc))";
       break;
@@ -697,6 +694,10 @@
     case CC_X86_64SysV:
       OS << " __attribute__((sysv_abi))";
       break;
+    case CC_SpirFunction:
+    case CC_SpirKernel:
+      // Do nothing. These CCs are not available as attributes.
+      break;
     }
   }
 
@@ -1253,7 +1254,6 @@
    OS << ')';
    break;
   }
-  case AttributedType::attr_pnaclcall: OS << "pnaclcall"; break;
   case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
   }
   OS << "))";
@@ -1490,6 +1490,9 @@
       case LangAS::opencl_constant:
         OS << "__constant";
         break;
+      case LangAS::opencl_generic:
+        OS << "__generic";
+        break;
       default:
         OS << "__attribute__((address_space(";
         OS << addrspace;
diff --git a/lib/AST/VTableBuilder.cpp b/lib/AST/VTableBuilder.cpp
index d8723b3..4e7715d 100644
--- a/lib/AST/VTableBuilder.cpp
+++ b/lib/AST/VTableBuilder.cpp
@@ -411,7 +411,8 @@
   for (const auto *MD : RD->methods()) {
     if (!MD->isVirtual())
       continue;
-  
+    MD = MD->getCanonicalDecl();
+
     OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
 
     Out << "  ";
@@ -695,6 +696,7 @@
   for (const auto *MD : RD->methods()) {
     if (!MD->isVirtual())
       continue;
+    MD = MD->getCanonicalDecl();
 
     CharUnits OffsetOffset = getCurrentOffsetOffset();
     
@@ -1514,6 +1516,7 @@
   for (const auto *MD : RD->methods()) {
     if (!MD->isVirtual())
       continue;
+    MD = MD->getCanonicalDecl();
 
     // Get the final overrider.
     FinalOverriders::OverriderInfo Overrider = 
@@ -2196,6 +2199,7 @@
     // We only want virtual member functions.
     if (!MD->isVirtual())
       continue;
+    MD = MD->getCanonicalDecl();
 
     std::string MethodName =
       PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
@@ -2676,7 +2680,7 @@
 // In this hierarchy, f() belongs to the vftable of A, so B::f() expects
 // "this" parameter to point at the A subobject, which is B+4.
 // In the B::f() prologue, it adjusts "this" back to B by subtracting 4,
-// peformed as a *static* adjustment.
+// performed as a *static* adjustment.
 //
 // Interesting thing happens when we alter the relative placement of A and B
 // subobjects in a class:
@@ -2930,6 +2934,7 @@
   typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
   VisitedGroupIndicesTy VisitedGroupIndices;
   for (const auto *MD : RD->methods()) {
+    MD = MD->getCanonicalDecl();
     VisitedGroupIndicesTy::iterator J;
     bool Inserted;
     std::tie(J, Inserted) = VisitedGroupIndices.insert(
diff --git a/lib/ASTMatchers/ASTMatchFinder.cpp b/lib/ASTMatchers/ASTMatchFinder.cpp
index 27c02bb..fa7968a 100644
--- a/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/Timer.h"
 #include <deque>
@@ -523,7 +524,7 @@
   ///
   /// Used by \c matchDispatch() below.
   template <typename T, typename MC>
-  void matchImpl(const T &Node, const MC &Matchers) {
+  void matchWithoutFilter(const T &Node, const MC &Matchers) {
     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
     TimeBucketRegion Timer;
     for (const auto &MP : Matchers) {
@@ -537,22 +538,66 @@
     }
   }
 
+  void matchWithFilter(const ast_type_traits::DynTypedNode &DynNode) {
+    auto Kind = DynNode.getNodeKind();
+    auto it = MatcherFiltersMap.find(Kind);
+    const auto &Filter =
+        it != MatcherFiltersMap.end() ? it->second : getFilterForKind(Kind);
+
+    if (Filter.empty())
+      return;
+
+    const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
+    TimeBucketRegion Timer;
+    auto &Matchers = this->Matchers->DeclOrStmt;
+    for (unsigned short I : Filter) {
+      auto &MP = Matchers[I];
+      if (EnableCheckProfiling)
+        Timer.setBucket(&TimeByBucket[MP.second->getID()]);
+      BoundNodesTreeBuilder Builder;
+      if (MP.first.matchesNoKindCheck(DynNode, this, &Builder)) {
+        MatchVisitor Visitor(ActiveASTContext, MP.second);
+        Builder.visitMatches(&Visitor);
+      }
+    }
+  }
+
+  const std::vector<unsigned short> &
+  getFilterForKind(ast_type_traits::ASTNodeKind Kind) {
+    auto &Filter = MatcherFiltersMap[Kind];
+    auto &Matchers = this->Matchers->DeclOrStmt;
+    assert((Matchers.size() < USHRT_MAX) && "Too many matchers.");
+    for (unsigned I = 0, E = Matchers.size(); I != E; ++I) {
+      if (Matchers[I].first.canMatchNodesOfKind(Kind)) {
+        Filter.push_back(I);
+      }
+    }
+    return Filter;
+  }
+
   /// @{
   /// \brief Overloads to pair the different node types to their matchers.
-  void matchDispatch(const Decl *Node) { matchImpl(*Node, Matchers->Decl); }
-  void matchDispatch(const Stmt *Node) { matchImpl(*Node, Matchers->Stmt); }
+  void matchDispatch(const Decl *Node) {
+    return matchWithFilter(ast_type_traits::DynTypedNode::create(*Node));
+  }
+  void matchDispatch(const Stmt *Node) {
+    return matchWithFilter(ast_type_traits::DynTypedNode::create(*Node));
+  }
+
   void matchDispatch(const Type *Node) {
-    matchImpl(QualType(Node, 0), Matchers->Type);
+    matchWithoutFilter(QualType(Node, 0), Matchers->Type);
   }
   void matchDispatch(const TypeLoc *Node) {
-    matchImpl(*Node, Matchers->TypeLoc);
+    matchWithoutFilter(*Node, Matchers->TypeLoc);
   }
-  void matchDispatch(const QualType *Node) { matchImpl(*Node, Matchers->Type); }
+  void matchDispatch(const QualType *Node) {
+    matchWithoutFilter(*Node, Matchers->Type);
+  }
   void matchDispatch(const NestedNameSpecifier *Node) {
-    matchImpl(*Node, Matchers->NestedNameSpecifier);
+    matchWithoutFilter(*Node, Matchers->NestedNameSpecifier);
   }
   void matchDispatch(const NestedNameSpecifierLoc *Node) {
-    matchImpl(*Node, Matchers->NestedNameSpecifierLoc);
+    matchWithoutFilter(*Node, Matchers->NestedNameSpecifierLoc);
   }
   void matchDispatch(const void *) { /* Do nothing. */ }
   /// @}
@@ -685,6 +730,18 @@
   llvm::StringMap<llvm::TimeRecord> TimeByBucket;
 
   const MatchFinder::MatchersByType *Matchers;
+
+  /// \brief Filtered list of matcher indices for each matcher kind.
+  ///
+  /// \c Decl and \c Stmt toplevel matchers usually apply to a specific node
+  /// kind (and derived kinds) so it is a waste to try every matcher on every
+  /// node.
+  /// We precalculate a list of matchers that pass the toplevel restrict check.
+  /// This also allows us to skip the restrict check at matching time. See
+  /// use \c matchesNoKindCheck() above.
+  llvm::DenseMap<ast_type_traits::ASTNodeKind, std::vector<unsigned short>>
+      MatcherFiltersMap;
+
   const MatchFinder::MatchFinderOptions &Options;
   ASTContext *ActiveASTContext;
 
@@ -855,7 +912,7 @@
 
 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
                              MatchCallback *Action) {
-  Matchers.Decl.push_back(std::make_pair(NodeMatch, Action));
+  Matchers.DeclOrStmt.push_back(std::make_pair(NodeMatch, Action));
   Matchers.AllCallbacks.push_back(Action);
 }
 
@@ -867,7 +924,7 @@
 
 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
                              MatchCallback *Action) {
-  Matchers.Stmt.push_back(std::make_pair(NodeMatch, Action));
+  Matchers.DeclOrStmt.push_back(std::make_pair(NodeMatch, Action));
   Matchers.AllCallbacks.push_back(Action);
 }
 
diff --git a/lib/ASTMatchers/ASTMatchersInternal.cpp b/lib/ASTMatchers/ASTMatchersInternal.cpp
index c7d98b8..2c482e3 100644
--- a/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -50,15 +50,15 @@
 
 namespace {
 
+typedef bool (*VariadicOperatorFunction)(
+    const ast_type_traits::DynTypedNode DynNode, ASTMatchFinder *Finder,
+    BoundNodesTreeBuilder *Builder, ArrayRef<DynTypedMatcher> InnerMatchers);
+
+template <VariadicOperatorFunction Func>
 class VariadicMatcher : public DynMatcherInterface {
 public:
-  typedef bool (*VariadicOperatorFunction)(
-      const ast_type_traits::DynTypedNode DynNode, ASTMatchFinder *Finder,
-      BoundNodesTreeBuilder *Builder, ArrayRef<DynTypedMatcher> InnerMatchers);
-
-  VariadicMatcher(VariadicOperatorFunction Func,
-                  std::vector<DynTypedMatcher> InnerMatchers)
-      : Func(Func), InnerMatchers(std::move(InnerMatchers)) {}
+  VariadicMatcher(std::vector<DynTypedMatcher> InnerMatchers)
+      : InnerMatchers(std::move(InnerMatchers)) {}
 
   bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
                   ASTMatchFinder *Finder,
@@ -67,7 +67,6 @@
   }
 
 private:
-  VariadicOperatorFunction Func;
   std::vector<DynTypedMatcher> InnerMatchers;
 };
 
@@ -119,29 +118,45 @@
          }) &&
          "SupportedKind must match!");
 
+  auto SupportedKind = InnerMatchers[0].SupportedKind;
   // We must relax the restrict kind here.
   // The different operators might deal differently with a mismatch.
   // Make it the same as SupportedKind, since that is the broadest type we are
   // allowed to accept.
-  auto SupportedKind = InnerMatchers[0].SupportedKind;
-  VariadicMatcher::VariadicOperatorFunction Func;
+  auto RestrictKind = SupportedKind;
+
   switch (Op) {
   case VO_AllOf:
-    Func = AllOfVariadicOperator;
-    break;
-  case VO_AnyOf:
-    Func = AnyOfVariadicOperator;
-    break;
-  case VO_EachOf:
-    Func = EachOfVariadicOperator;
-    break;
-  case VO_UnaryNot:
-    Func = NotUnaryOperator;
-    break;
-  }
+    // In the case of allOf() we must pass all the checks, so making
+    // RestrictKind the most restrictive can save us time. This way we reject
+    // invalid types earlier and we can elide the kind checks inside the
+    // matcher.
+    for (auto &IM : InnerMatchers) {
+      RestrictKind = ast_type_traits::ASTNodeKind::getMostDerivedType(
+          RestrictKind, IM.RestrictKind);
+    }
+    return DynTypedMatcher(
+        SupportedKind, RestrictKind,
+        new VariadicMatcher<AllOfVariadicOperator>(std::move(InnerMatchers)));
 
-  return DynTypedMatcher(SupportedKind, SupportedKind,
-                         new VariadicMatcher(Func, std::move(InnerMatchers)));
+  case VO_AnyOf:
+    return DynTypedMatcher(
+        SupportedKind, RestrictKind,
+        new VariadicMatcher<AnyOfVariadicOperator>(std::move(InnerMatchers)));
+
+  case VO_EachOf:
+    return DynTypedMatcher(
+        SupportedKind, RestrictKind,
+        new VariadicMatcher<EachOfVariadicOperator>(std::move(InnerMatchers)));
+
+  case VO_UnaryNot:
+    // FIXME: Implement the Not operator to take a single matcher instead of a
+    // vector.
+    return DynTypedMatcher(
+        SupportedKind, RestrictKind,
+        new VariadicMatcher<NotUnaryOperator>(std::move(InnerMatchers)));
+  }
+  llvm_unreachable("Invalid Op value.");
 }
 
 DynTypedMatcher DynTypedMatcher::trueMatcher(
@@ -149,6 +164,11 @@
   return DynTypedMatcher(NodeKind, NodeKind, &*TrueMatcherInstance);
 }
 
+bool DynTypedMatcher::canMatchNodesOfKind(
+    ast_type_traits::ASTNodeKind Kind) const {
+  return RestrictKind.isBaseOf(Kind);
+}
+
 DynTypedMatcher DynTypedMatcher::dynCastTo(
     const ast_type_traits::ASTNodeKind Kind) const {
   auto Copy = *this;
@@ -172,6 +192,20 @@
   return false;
 }
 
+bool DynTypedMatcher::matchesNoKindCheck(
+    const ast_type_traits::DynTypedNode &DynNode, ASTMatchFinder *Finder,
+    BoundNodesTreeBuilder *Builder) const {
+  assert(RestrictKind.isBaseOf(DynNode.getNodeKind()));
+  if (Implementation->dynMatches(DynNode, Finder, Builder)) {
+    return true;
+  }
+  // Delete all bindings when a matcher does not match.
+  // This prevents unexpected exposure of bound nodes in unmatches
+  // branches of the match tree.
+  Builder->removeBindings([](const BoundNodesMap &) { return true; });
+  return false;
+}
+
 llvm::Optional<DynTypedMatcher> DynTypedMatcher::tryBind(StringRef ID) const {
   if (!AllowBind) return llvm::None;
   auto Result = *this;
@@ -222,7 +256,7 @@
   // matcher combined with each alternative in the second matcher.
   // Thus, we can reuse the same Builder.
   for (const DynTypedMatcher &InnerMatcher : InnerMatchers) {
-    if (!InnerMatcher.matches(DynNode, Finder, Builder))
+    if (!InnerMatcher.matchesNoKindCheck(DynNode, Finder, Builder))
       return false;
   }
   return true;
diff --git a/lib/ASTMatchers/Dynamic/Registry.cpp b/lib/ASTMatchers/Dynamic/Registry.cpp
index dab4187..c074279 100644
--- a/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -242,7 +242,10 @@
   REGISTER_MATCHER(isExpr);
   REGISTER_MATCHER(isExternC);
   REGISTER_MATCHER(isImplicit);
+  REGISTER_MATCHER(isExpansionInFileMatching);
+  REGISTER_MATCHER(isExpansionInMainFile);
   REGISTER_MATCHER(isInstantiated);
+  REGISTER_MATCHER(isExpansionInSystemHeader);
   REGISTER_MATCHER(isInteger);
   REGISTER_MATCHER(isIntegral);
   REGISTER_MATCHER(isInTemplateInstantiation);
@@ -312,8 +315,10 @@
   REGISTER_MATCHER(throughUsingDecl);
   REGISTER_MATCHER(throwExpr);
   REGISTER_MATCHER(to);
+  REGISTER_MATCHER(translationUnitDecl);
   REGISTER_MATCHER(tryStmt);
   REGISTER_MATCHER(type);
+  REGISTER_MATCHER(typedefDecl);
   REGISTER_MATCHER(typedefType);
   REGISTER_MATCHER(typeLoc);
   REGISTER_MATCHER(unaryExprOrTypeTraitExpr);
@@ -328,6 +333,7 @@
   REGISTER_MATCHER(valueDecl);
   REGISTER_MATCHER(varDecl);
   REGISTER_MATCHER(variableArrayType);
+  REGISTER_MATCHER(voidType);
   REGISTER_MATCHER(whileStmt);
   REGISTER_MATCHER(withInitializer);
 }
diff --git a/lib/Analysis/AnalysisDeclContext.cpp b/lib/Analysis/AnalysisDeclContext.cpp
index be66f32..4e623c8 100644
--- a/lib/Analysis/AnalysisDeclContext.cpp
+++ b/lib/Analysis/AnalysisDeclContext.cpp
@@ -530,14 +530,14 @@
   return BV;
 }
 
-std::pair<AnalysisDeclContext::referenced_decls_iterator,
-          AnalysisDeclContext::referenced_decls_iterator>
+llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
   if (!ReferencedBlockVars)
     ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
 
-  DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
-  return std::make_pair(V->begin(), V->end());
+  const DeclVec *V =
+      LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
+  return llvm::make_range(V->begin(), V->end());
 }
 
 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
diff --git a/lib/Analysis/BodyFarm.cpp b/lib/Analysis/BodyFarm.cpp
index 23286b2..7d1b235 100644
--- a/lib/Analysis/BodyFarm.cpp
+++ b/lib/Analysis/BodyFarm.cpp
@@ -13,11 +13,11 @@
 //===----------------------------------------------------------------------===//
 
 #include "BodyFarm.h"
-#include "clang/Analysis/CodeInjector.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/Analysis/CodeInjector.h"
 #include "llvm/ADT/StringSwitch.h"
 
 using namespace clang;
@@ -115,7 +115,7 @@
                         /* QualifierLoc = */ NestedNameSpecifierLoc(),
                         /* TemplateKWLoc = */ SourceLocation(),
                         /* D = */ const_cast<VarDecl*>(D),
-                        /* isEnclosingLocal = */ false,
+                        /* RefersToEnclosingVariableOrCapture = */ false,
                         /* NameLoc = */ SourceLocation(),
                         /* T = */ D->getType(),
                         /* VK = */ VK_LValue);
diff --git a/lib/Analysis/CFG.cpp b/lib/Analysis/CFG.cpp
index d9073aa..5d06634 100644
--- a/lib/Analysis/CFG.cpp
+++ b/lib/Analysis/CFG.cpp
@@ -156,7 +156,7 @@
       return !(*this == rhs);
     }
 
-    LLVM_EXPLICIT operator bool() const {
+    explicit operator bool() const {
       return *this != const_iterator();
     }
 
diff --git a/lib/Analysis/CallGraph.cpp b/lib/Analysis/CallGraph.cpp
index f41a96d..91a8492 100644
--- a/lib/Analysis/CallGraph.cpp
+++ b/lib/Analysis/CallGraph.cpp
@@ -110,14 +110,13 @@
 
 bool CallGraph::includeInGraph(const Decl *D) {
   assert(D);
-  if (!D->getBody())
+  if (!D->hasBody())
     return false;
 
   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
     // We skip function template definitions, as their semantics is
     // only determined when they are instantiated.
-    if (!FD->isThisDeclarationADefinition() ||
-        FD->isDependentContext())
+    if (FD->isDependentContext())
       return false;
 
     IdentifierInfo *II = FD->getIdentifier();
@@ -125,11 +124,6 @@
       return false;
   }
 
-  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
-    if (!ID->isThisDeclarationADefinition())
-      return false;
-  }
-
   return true;
 }
 
@@ -152,6 +146,9 @@
 }
 
 CallGraphNode *CallGraph::getOrInsertNode(Decl *F) {
+  if (F && !isa<ObjCMethodDecl>(F))
+    F = F->getCanonicalDecl();
+
   CallGraphNode *&Node = FunctionMap[F];
   if (Node)
     return Node;
diff --git a/lib/Analysis/FormatString.cpp b/lib/Analysis/FormatString.cpp
index 8c663d8..662166c 100644
--- a/lib/Analysis/FormatString.cpp
+++ b/lib/Analysis/FormatString.cpp
@@ -552,6 +552,12 @@
   // Objective-C specific specifiers.
   case ObjCObjArg: return "@";
 
+  // FreeBSD kernel specific specifiers.
+  case FreeBSDbArg: return "b";
+  case FreeBSDDArg: return "D";
+  case FreeBSDrArg: return "r";
+  case FreeBSDyArg: return "y";
+
   // GlibC specific specifiers.
   case PrintErrno: return "m";
 
@@ -647,6 +653,9 @@
         case ConversionSpecifier::XArg:
         case ConversionSpecifier::nArg:
           return true;
+        case ConversionSpecifier::FreeBSDrArg:
+        case ConversionSpecifier::FreeBSDyArg:
+          return Target.getTriple().isOSFreeBSD();
         default:
           return false;
       }
@@ -677,6 +686,9 @@
         case ConversionSpecifier::ScanListArg:
         case ConversionSpecifier::ZArg:
           return true;
+        case ConversionSpecifier::FreeBSDrArg:
+        case ConversionSpecifier::FreeBSDyArg:
+          return Target.getTriple().isOSFreeBSD();
         default:
           return false;
       }
@@ -807,6 +819,10 @@
     case ConversionSpecifier::SArg:
       return LangOpt.ObjC1 || LangOpt.ObjC2;
     case ConversionSpecifier::InvalidSpecifier:
+    case ConversionSpecifier::FreeBSDbArg:
+    case ConversionSpecifier::FreeBSDDArg:
+    case ConversionSpecifier::FreeBSDrArg:
+    case ConversionSpecifier::FreeBSDyArg:
     case ConversionSpecifier::PrintErrno:
     case ConversionSpecifier::DArg:
     case ConversionSpecifier::OArg:
diff --git a/lib/Analysis/LiveVariables.cpp b/lib/Analysis/LiveVariables.cpp
index 86b679c..0ab1580 100644
--- a/lib/Analysis/LiveVariables.cpp
+++ b/lib/Analysis/LiveVariables.cpp
@@ -356,11 +356,8 @@
 }
 
 void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
-  AnalysisDeclContext::referenced_decls_iterator I, E;
-  std::tie(I, E) =
-    LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
-  for ( ; I != E ; ++I) {
-    const VarDecl *VD = *I;
+  for (const VarDecl *VD :
+       LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
     if (isAlwaysAlive(VD))
       continue;
     val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
diff --git a/lib/Analysis/PrintfFormatString.cpp b/lib/Analysis/PrintfFormatString.cpp
index 146635b..b8d3ec1 100644
--- a/lib/Analysis/PrintfFormatString.cpp
+++ b/lib/Analysis/PrintfFormatString.cpp
@@ -55,7 +55,8 @@
                                                   unsigned &argIndex,
                                                   const LangOptions &LO,
                                                   const TargetInfo &Target,
-                                                  bool Warn) {
+                                                  bool Warn,
+                                                  bool isFreeBSDKPrintf) {
 
   using namespace clang::analyze_format_string;
   using namespace clang::analyze_printf;
@@ -206,9 +207,24 @@
     case '@': k = ConversionSpecifier::ObjCObjArg; break;
     // Glibc specific.
     case 'm': k = ConversionSpecifier::PrintErrno; break;
+    // FreeBSD kernel specific.
+    case 'b':
+      if (isFreeBSDKPrintf)
+        k = ConversionSpecifier::FreeBSDbArg; // int followed by char *
+      break;
+    case 'r':
+      if (isFreeBSDKPrintf)
+        k = ConversionSpecifier::FreeBSDrArg; // int
+      break;
+    case 'y':
+      if (isFreeBSDKPrintf)
+        k = ConversionSpecifier::FreeBSDyArg; // int
+      break;
     // Apple-specific.
     case 'D':
-      if (Target.getTriple().isOSDarwin())
+      if (isFreeBSDKPrintf)
+        k = ConversionSpecifier::FreeBSDDArg; // void * followed by char *
+      else if (Target.getTriple().isOSDarwin())
         k = ConversionSpecifier::DArg;
       break;
     case 'O':
@@ -228,6 +244,10 @@
   FS.setConversionSpecifier(CS);
   if (CS.consumesDataArgument() && !FS.usesPositionalArg())
     FS.setArgIndex(argIndex++);
+  // FreeBSD kernel specific.
+  if (k == ConversionSpecifier::FreeBSDbArg ||
+      k == ConversionSpecifier::FreeBSDDArg)
+    argIndex++;
 
   if (k == ConversionSpecifier::InvalidSpecifier) {
     // Assume the conversion takes one argument.
@@ -240,14 +260,16 @@
                                                      const char *I,
                                                      const char *E,
                                                      const LangOptions &LO,
-                                                     const TargetInfo &Target) {
+                                                     const TargetInfo &Target,
+                                                     bool isFreeBSDKPrintf) {
 
   unsigned argIndex = 0;
 
   // Keep looking for a format specifier until we have exhausted the string.
   while (I != E) {
     const PrintfSpecifierResult &FSR = ParsePrintfSpecifier(H, I, E, argIndex,
-                                                            LO, Target, true);
+                                                            LO, Target, true,
+                                                            isFreeBSDKPrintf);
     // Did a fail-stop error of any kind occur when parsing the specifier?
     // If so, don't do any more processing.
     if (FSR.shouldStop())
@@ -276,7 +298,8 @@
   FormatStringHandler H;
   while (I != E) {
     const PrintfSpecifierResult &FSR = ParsePrintfSpecifier(H, I, E, argIndex,
-                                                            LO, Target, false);
+                                                            LO, Target, false,
+                                                            false);
     // Did a fail-stop error of any kind occur when parsing the specifier?
     // If so, don't do any more processing.
     if (FSR.shouldStop())
@@ -674,6 +697,8 @@
   case ConversionSpecifier::GArg:
   case ConversionSpecifier::aArg:
   case ConversionSpecifier::AArg:
+  case ConversionSpecifier::FreeBSDrArg:
+  case ConversionSpecifier::FreeBSDyArg:
     return true;
 
   default:
@@ -699,6 +724,8 @@
   case ConversionSpecifier::FArg:
   case ConversionSpecifier::gArg:
   case ConversionSpecifier::GArg:
+  case ConversionSpecifier::FreeBSDrArg:
+  case ConversionSpecifier::FreeBSDyArg:
     return true;
 
   default:
@@ -729,6 +756,8 @@
   case ConversionSpecifier::FArg:
   case ConversionSpecifier::gArg:
   case ConversionSpecifier::GArg:
+  case ConversionSpecifier::FreeBSDrArg:
+  case ConversionSpecifier::FreeBSDyArg:
     return true;
 
   default:
@@ -753,6 +782,8 @@
   case ConversionSpecifier::GArg:
   case ConversionSpecifier::aArg:
   case ConversionSpecifier::AArg:
+  case ConversionSpecifier::FreeBSDrArg:
+  case ConversionSpecifier::FreeBSDyArg:
     return true;
 
   default:
@@ -818,6 +849,8 @@
   case ConversionSpecifier::gArg:
   case ConversionSpecifier::GArg:
   case ConversionSpecifier::sArg:
+  case ConversionSpecifier::FreeBSDrArg:
+  case ConversionSpecifier::FreeBSDyArg:
     return true;
 
   default:
diff --git a/lib/Analysis/ReachableCode.cpp b/lib/Analysis/ReachableCode.cpp
index b4a72a7..8165b09 100644
--- a/lib/Analysis/ReachableCode.cpp
+++ b/lib/Analysis/ReachableCode.cpp
@@ -13,15 +13,15 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Analysis/Analyses/ReachableCode.h"
-#include "clang/Lex/Preprocessor.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
-#include "clang/AST/StmtCXX.h"
 #include "clang/AST/ParentMap.h"
+#include "clang/AST/StmtCXX.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/SmallVector.h"
 
diff --git a/lib/Analysis/ThreadSafety.cpp b/lib/Analysis/ThreadSafety.cpp
index 4ddc21d..37819a7 100644
--- a/lib/Analysis/ThreadSafety.cpp
+++ b/lib/Analysis/ThreadSafety.cpp
@@ -22,10 +22,10 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
 #include "clang/Analysis/Analyses/ThreadSafety.h"
+#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
 #include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
-#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CFGStmtMap.h"
@@ -101,17 +101,22 @@
   LockKind          LKind;            ///<  exclusive or shared
   SourceLocation    AcquireLoc;       ///<  where it was acquired.
   bool              Asserted;         ///<  true if the lock was asserted
+  bool              Declared;         ///<  true if the lock was declared
 
 public:
   FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
-            bool Asrt)
-      : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt) {}
+            bool Asrt, bool Declrd = false)
+      : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
+        Declared(Declrd) {}
 
   virtual ~FactEntry() {}
 
-  LockKind          kind()       const { return LKind;    }
+  LockKind          kind()       const { return LKind;      }
   SourceLocation    loc()        const { return AcquireLoc; }
   bool              asserted()   const { return Asserted; }
+  bool              declared()   const { return Declared; }
+
+  void setDeclared(bool D) { Declared = D; }
 
   virtual void
   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
@@ -231,14 +236,59 @@
 
   FactEntry *findPartialMatch(FactManager &FM,
                               const CapabilityExpr &CapE) const {
-    auto I = std::find_if(begin(), end(), [&](FactID ID) {
+    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
       return FM[ID].partiallyMatches(CapE);
     });
     return I != end() ? &FM[*I] : nullptr;
   }
+
+  bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
+    auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
+      return FM[ID].valueDecl() == Vd;
+    });
+    return I != end();
+  }
 };
 
 
+class ThreadSafetyAnalyzer;
+
+
+class BeforeSet {
+private:
+  typedef SmallVector<const ValueDecl*, 4>  BeforeVect;
+
+  struct BeforeInfo {
+    BeforeInfo() : Vect(nullptr), Visited(false) { }
+    BeforeInfo(BeforeInfo &&O)
+        : Vect(std::move(O.Vect)), Visited(O.Visited)
+    {}
+
+    std::unique_ptr<BeforeVect> Vect;
+    int                         Visited;
+  };
+
+  typedef llvm::DenseMap<const ValueDecl*, BeforeInfo>  BeforeMap;
+  typedef llvm::DenseMap<const ValueDecl*, bool>        CycleMap;
+
+public:
+  BeforeSet() { }
+
+  BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
+                              ThreadSafetyAnalyzer& Analyzer);
+
+  void checkBeforeAfter(const ValueDecl* Vd,
+                        const FactSet& FSet,
+                        ThreadSafetyAnalyzer& Analyzer,
+                        SourceLocation Loc, StringRef CapKind);
+
+private:
+  BeforeMap BMap;
+  CycleMap  CycMap;
+};
+
+
+
 typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
 class LocalVariableMap;
 
@@ -853,6 +903,7 @@
 /// \brief Class which implements the core thread safety analysis routines.
 class ThreadSafetyAnalyzer {
   friend class BuildLockset;
+  friend class BeforeSet;
 
   llvm::BumpPtrAllocator Bpa;
   threadSafety::til::MemRegionRef Arena;
@@ -864,9 +915,11 @@
   FactManager               FactMan;
   std::vector<CFGBlockInfo> BlockInfo;
 
+  BeforeSet* GlobalBeforeSet;
+
 public:
-  ThreadSafetyAnalyzer(ThreadSafetyHandler &H)
-     : Arena(&Bpa), SxBuilder(Arena), Handler(H) {}
+  ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
+     : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
 
   bool inCurrentScope(const CapabilityExpr &CapE);
 
@@ -907,6 +960,135 @@
   void runAnalysis(AnalysisDeclContext &AC);
 };
 
+
+
+/// Process acquired_before and acquired_after attributes on Vd.
+BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
+    ThreadSafetyAnalyzer& Analyzer) {
+  // Create a new entry for Vd.
+  auto& Entry = BMap.FindAndConstruct(Vd);
+  BeforeInfo* Info = &Entry.second;
+  BeforeVect* Bv = nullptr;
+
+  for (Attr* At : Vd->attrs()) {
+    switch (At->getKind()) {
+      case attr::AcquiredBefore: {
+        auto *A = cast<AcquiredBeforeAttr>(At);
+
+        // Create a new BeforeVect for Vd if necessary.
+        if (!Bv) {
+          Bv = new BeforeVect;
+          Info->Vect.reset(Bv);
+        }
+        // Read exprs from the attribute, and add them to BeforeVect.
+        for (const auto *Arg : A->args()) {
+          CapabilityExpr Cp =
+            Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
+          if (const ValueDecl *Cpvd = Cp.valueDecl()) {
+            Bv->push_back(Cpvd);
+            auto It = BMap.find(Cpvd);
+            if (It == BMap.end())
+              insertAttrExprs(Cpvd, Analyzer);
+          }
+        }
+        break;
+      }
+      case attr::AcquiredAfter: {
+        auto *A = cast<AcquiredAfterAttr>(At);
+
+        // Read exprs from the attribute, and add them to BeforeVect.
+        for (const auto *Arg : A->args()) {
+          CapabilityExpr Cp =
+            Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
+          if (const ValueDecl *ArgVd = Cp.valueDecl()) {
+            // Get entry for mutex listed in attribute
+            BeforeInfo* ArgInfo;
+            auto It = BMap.find(ArgVd);
+            if (It == BMap.end())
+              ArgInfo = insertAttrExprs(ArgVd, Analyzer);
+            else
+              ArgInfo = &It->second;
+
+            // Create a new BeforeVect if necessary.
+            BeforeVect* ArgBv = ArgInfo->Vect.get();
+            if (!ArgBv) {
+              ArgBv = new BeforeVect;
+              ArgInfo->Vect.reset(ArgBv);
+            }
+            ArgBv->push_back(Vd);
+          }
+        }
+        break;
+      }
+      default:
+        break;
+    }
+  }
+
+  return Info;
+}
+
+
+/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
+void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
+                                 const FactSet& FSet,
+                                 ThreadSafetyAnalyzer& Analyzer,
+                                 SourceLocation Loc, StringRef CapKind) {
+  SmallVector<BeforeInfo*, 8> InfoVect;
+
+  // Do a depth-first traversal of Vd.
+  // Return true if there are cycles.
+  std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
+    if (!Vd)
+      return false;
+
+    BeforeSet::BeforeInfo* Info;
+    auto It = BMap.find(Vd);
+    if (It == BMap.end())
+      Info = insertAttrExprs(Vd, Analyzer);
+    else
+      Info = &It->second;
+
+    if (Info->Visited == 1)
+      return true;
+
+    if (Info->Visited == 2)
+      return false;
+
+    BeforeVect* Bv = Info->Vect.get();
+    if (!Bv)
+      return false;
+
+    InfoVect.push_back(Info);
+    Info->Visited = 1;
+    for (auto *Vdb : *Bv) {
+      // Exclude mutexes in our immediate before set.
+      if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
+        StringRef L1 = StartVd->getName();
+        StringRef L2 = Vdb->getName();
+        Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
+      }
+      // Transitively search other before sets, and warn on cycles.
+      if (traverse(Vdb)) {
+        if (CycMap.find(Vd) == CycMap.end()) {
+          CycMap.insert(std::make_pair(Vd, true));
+          StringRef L1 = Vd->getName();
+          Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
+        }
+      }
+    }
+    Info->Visited = 2;
+    return false;
+  };
+
+  traverse(StartVd);
+
+  for (auto* Info : InfoVect)
+    Info->Visited = 0;
+}
+
+
+
 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
 static const ValueDecl *getValueDecl(const Expr *Exp) {
   if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
@@ -1020,7 +1202,13 @@
     }
   }
 
-  // FIXME: deal with acquired before/after annotations.
+  // Check before/after constraints
+  if (Handler.issueBetaWarnings() &&
+      !Entry->asserted() && !Entry->declared()) {
+    GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
+                                      Entry->loc(), DiagKind);
+  }
+
   // FIXME: Don't always warn when we have support for reentrant locks.
   if (FSet.findLock(FactMan, *Entry)) {
     if (!Entry->asserted())
@@ -1230,7 +1418,7 @@
   CapExprSet SharedLocksToAdd;
 
   // If the condition is a call to a Trylock function, then grab the attributes
-  for (auto *Attr : FunDecl->getAttrs()) {
+  for (auto *Attr : FunDecl->attrs()) {
     switch (Attr->getKind()) {
       case attr::ExclusiveTrylockFunction: {
         ExclusiveTrylockFunctionAttr *A =
@@ -1500,13 +1688,23 @@
 ///
 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
   SourceLocation Loc = Exp->getExprLoc();
-  const AttrVec &ArgAttrs = D->getAttrs();
   CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
   CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
+  CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
   StringRef CapDiagKind = "mutex";
 
-  for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
-    Attr *At = const_cast<Attr*>(ArgAttrs[i]);
+  // Figure out if we're calling the constructor of scoped lockable class
+  bool isScopedVar = false;
+  if (VD) {
+    if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
+      const CXXRecordDecl* PD = CD->getParent();
+      if (PD && PD->hasAttr<ScopedLockableAttr>())
+        isScopedVar = true;
+    }
+  }
+
+  for(Attr *Atconst : D->attrs()) {
+    Attr* At = const_cast<Attr*>(Atconst);
     switch (At->getKind()) {
       // When we encounter a lock function, we need to add the lock to our
       // lockset.
@@ -1564,10 +1762,17 @@
 
       case attr::RequiresCapability: {
         RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
-        for (auto *Arg : A->args())
+        for (auto *Arg : A->args()) {
           warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
                              POK_FunctionCall, ClassifyDiagnostic(A),
                              Exp->getExprLoc());
+          // use for adopting a lock
+          if (isScopedVar) {
+            Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
+                                                : ScopedExclusiveReqs,
+                                  A, Exp, D, VD);
+          }
+        }
         break;
       }
 
@@ -1584,16 +1789,6 @@
     }
   }
 
-  // Figure out if we're calling the constructor of scoped lockable class
-  bool isScopedVar = false;
-  if (VD) {
-    if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
-      const CXXRecordDecl* PD = CD->getParent();
-      if (PD && PD->hasAttr<ScopedLockableAttr>())
-        isScopedVar = true;
-    }
-  }
-
   // Add locks.
   for (const auto &M : ExclusiveLocksToAdd)
     Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
@@ -1611,9 +1806,10 @@
     // FIXME: does this store a pointer to DRE?
     CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
 
-    CapExprSet UnderlyingMutexes(ExclusiveLocksToAdd);
-    std::copy(SharedLocksToAdd.begin(), SharedLocksToAdd.end(),
-              std::back_inserter(UnderlyingMutexes));
+    std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
+              std::back_inserter(ExclusiveLocksToAdd));
+    std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
+              std::back_inserter(SharedLocksToAdd));
     Analyzer->addLock(FSet,
                       llvm::make_unique<ScopedLockableFactEntry>(
                           Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
@@ -1940,14 +2136,13 @@
   if (!SortedGraph->empty() && D->hasAttrs()) {
     const CFGBlock *FirstBlock = *SortedGraph->begin();
     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
-    const AttrVec &ArgAttrs = D->getAttrs();
 
     CapExprSet ExclusiveLocksToAdd;
     CapExprSet SharedLocksToAdd;
     StringRef CapDiagKind = "mutex";
 
     SourceLocation Loc = D->getLocation();
-    for (const auto *Attr : ArgAttrs) {
+    for (const auto *Attr : D->attrs()) {
       Loc = Attr->getLocation();
       if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
@@ -1979,14 +2174,16 @@
     }
 
     // FIXME -- Loc can be wrong here.
-    for (const auto &Mu : ExclusiveLocksToAdd)
-      addLock(InitialLockset,
-              llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc),
-              CapDiagKind, true);
-    for (const auto &Mu : SharedLocksToAdd)
-      addLock(InitialLockset,
-              llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc),
-              CapDiagKind, true);
+    for (const auto &Mu : ExclusiveLocksToAdd) {
+      auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
+      Entry->setDeclared(true);
+      addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
+    }
+    for (const auto &Mu : SharedLocksToAdd) {
+      auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
+      Entry->setDeclared(true);
+      addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
+    }
   }
 
   for (const auto *CurrBlock : *SortedGraph) {
@@ -2180,11 +2377,20 @@
 /// at the end of each block, and issue warnings for thread safety violations.
 /// Each block in the CFG is traversed exactly once.
 void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
-                             ThreadSafetyHandler &Handler) {
-  ThreadSafetyAnalyzer Analyzer(Handler);
+                             ThreadSafetyHandler &Handler,
+                             BeforeSet **BSet) {
+  if (!*BSet)
+    *BSet = new BeforeSet;
+  ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
   Analyzer.runAnalysis(AC);
 }
 
+
+void threadSafetyCleanup(BeforeSet* Cache) {
+  delete Cache;
+}
+
+
 /// \brief Helper function that returns a LockKind required for the given level
 /// of access.
 LockKind getLockKindFromAccessKind(AccessKind AK) {
diff --git a/lib/Analysis/ThreadSafetyCommon.cpp b/lib/Analysis/ThreadSafetyCommon.cpp
index 88a1cbf..563e059 100644
--- a/lib/Analysis/ThreadSafetyCommon.cpp
+++ b/lib/Analysis/ThreadSafetyCommon.cpp
@@ -28,7 +28,6 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-
 #include <algorithm>
 #include <climits>
 #include <vector>
diff --git a/lib/Analysis/UninitializedValues.cpp b/lib/Analysis/UninitializedValues.cpp
index 94f59f1..61a2592 100644
--- a/lib/Analysis/UninitializedValues.cpp
+++ b/lib/Analysis/UninitializedValues.cpp
@@ -419,7 +419,8 @@
   // Classify arguments to std::move as used.
   if (CE->getNumArgs() == 1) {
     if (FunctionDecl *FD = CE->getDirectCallee()) {
-      if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
+      if (FD->isInStdNamespace() && FD->getIdentifier() &&
+          FD->getIdentifier()->isStr("move")) {
         classify(CE->getArg(0), Use);
         return;
       }
diff --git a/lib/Basic/Android.mk b/lib/Basic/Android.mk
index 79d7322..a5bd987 100644
--- a/lib/Basic/Android.mk
+++ b/lib/Basic/Android.mk
@@ -16,6 +16,7 @@
   DiagnosticParseKinds.inc \
   DiagnosticSemaKinds.inc \
   DiagnosticSerializationKinds.inc \
+  arm_neon.h \
   arm_neon.inc
 
 clang_basic_SRC_FILES := \
diff --git a/lib/Basic/CMakeLists.txt b/lib/Basic/CMakeLists.txt
index a7bd8de..50a06d9 100644
--- a/lib/Basic/CMakeLists.txt
+++ b/lib/Basic/CMakeLists.txt
@@ -25,28 +25,33 @@
 find_first_existing_vc_file(llvm_vc "${LLVM_MAIN_SRC_DIR}")
 find_first_existing_vc_file(clang_vc "${CLANG_SOURCE_DIR}")
 
+# The VC revision include that we want to generate.
+set(version_inc "${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc")
+
+set(get_svn_script "${LLVM_MAIN_SRC_DIR}/cmake/modules/GetSVN.cmake")
+
 if(DEFINED llvm_vc AND DEFINED clang_vc)
   # Create custom target to generate the VC revision include.
-  add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc"
-    DEPENDS "${llvm_vc}" "${clang_vc}"
+  add_custom_command(OUTPUT "${version_inc}"
+    DEPENDS "${llvm_vc}" "${clang_vc}" "${get_svn_script}"
     COMMAND
     ${CMAKE_COMMAND} "-DFIRST_SOURCE_DIR=${LLVM_MAIN_SRC_DIR}"
                      "-DFIRST_NAME=LLVM"
                      "-DSECOND_SOURCE_DIR=${CLANG_SOURCE_DIR}"
                      "-DSECOND_NAME=SVN"
-                     "-DHEADER_FILE=${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc"
-                     -P "${LLVM_MAIN_SRC_DIR}/cmake/modules/GetSVN.cmake")
+                     "-DHEADER_FILE=${version_inc}"
+                     -P "${get_svn_script}")
 
   # Mark the generated header as being generated.
-  set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc"
+  set_source_files_properties("${version_inc}"
     PROPERTIES GENERATED TRUE
                HEADER_FILE_ONLY TRUE)
 
   # Tell Version.cpp that it needs to build with -DHAVE_SVN_VERSION_INC.
   set_source_files_properties(Version.cpp
     PROPERTIES COMPILE_DEFINITIONS "HAVE_SVN_VERSION_INC")
-  set(version_inc "${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc")
 else()
+  # Not producing a VC revision include.
   set(version_inc)
 endif()
 
diff --git a/lib/Basic/Diagnostic.cpp b/lib/Basic/Diagnostic.cpp
index 5c066ef..631b978 100644
--- a/lib/Basic/Diagnostic.cpp
+++ b/lib/Basic/Diagnostic.cpp
@@ -19,6 +19,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/CrashRecoveryContext.h"
+#include "llvm/Support/Locale.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
@@ -61,6 +62,12 @@
   Reset();
 }
 
+DiagnosticsEngine::~DiagnosticsEngine() {
+  // If we own the diagnostic client, destroy it first so that it can access the
+  // engine from its destructor.
+  setClient(nullptr);
+}
+
 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
                                   bool ShouldOwnClient) {
   Owner.reset(ShouldOwnClient ? client : nullptr);
@@ -623,6 +630,21 @@
 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
                  SmallVectorImpl<char> &OutStr) const {
 
+  // When the diagnostic string is only "%0", the entire string is being given
+  // by an outside source.  Remove unprintable characters from this string
+  // and skip all the other string processing.
+  if (DiagEnd - DiagStr == 2 &&
+      StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
+      getArgKind(0) == DiagnosticsEngine::ak_std_string) {
+    const std::string &S = getArgStdStr(0);
+    for (char c : S) {
+      if (llvm::sys::locale::isPrint(c) || c == '\t') {
+        OutStr.push_back(c);
+      }
+    }
+    return;
+  }
+
   /// FormattedArgs - Keep track of all of the arguments formatted by
   /// ConvertArgToString and pass them into subsequent calls to
   /// ConvertArgToString, allowing the implementation to avoid redundancies in
@@ -927,14 +949,8 @@
   SmallString<64> Message;
   Info.FormatDiagnostic(Message);
   this->Message.assign(Message.begin(), Message.end());
-
-  Ranges.reserve(Info.getNumRanges());
-  for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
-    Ranges.push_back(Info.getRange(I));
-
-  FixIts.reserve(Info.getNumFixItHints());
-  for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
-    FixIts.push_back(Info.getFixItHint(I));
+  this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
+  this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
 }
 
 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
diff --git a/lib/Basic/DiagnosticIDs.cpp b/lib/Basic/DiagnosticIDs.cpp
index 282e75e..1c68375 100644
--- a/lib/Basic/DiagnosticIDs.cpp
+++ b/lib/Basic/DiagnosticIDs.cpp
@@ -606,9 +606,6 @@
 bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const {
   Diagnostic Info(&Diag);
 
-  if (Diag.SuppressAllDiagnostics)
-    return false;
-
   assert(Diag.getClient() && "DiagnosticClient not set!");
 
   // Figure out the diagnostic level of this message.
@@ -616,6 +613,17 @@
   DiagnosticIDs::Level DiagLevel
     = getDiagnosticLevel(DiagID, Info.getLocation(), Diag);
 
+  // Update counts for DiagnosticErrorTrap even if a fatal error occurred
+  // or diagnostics are suppressed.
+  if (DiagLevel >= DiagnosticIDs::Error) {
+    ++Diag.TrapNumErrorsOccurred;
+    if (isUnrecoverable(DiagID))
+      ++Diag.TrapNumUnrecoverableErrorsOccurred;
+  }
+
+  if (Diag.SuppressAllDiagnostics)
+    return false;
+
   if (DiagLevel != DiagnosticIDs::Note) {
     // Record that a fatal error occurred only when we see a second
     // non-note diagnostic. This allows notes to be attached to the
@@ -627,13 +635,6 @@
     Diag.LastDiagLevel = DiagLevel;
   }
 
-  // Update counts for DiagnosticErrorTrap even if a fatal error occurred.
-  if (DiagLevel >= DiagnosticIDs::Error) {
-    ++Diag.TrapNumErrorsOccurred;
-    if (isUnrecoverable(DiagID))
-      ++Diag.TrapNumUnrecoverableErrorsOccurred;
-  }
-
   // If a fatal error has already been emitted, silence all subsequent
   // diagnostics.
   if (Diag.FatalErrorOccurred) {
diff --git a/lib/Basic/FileManager.cpp b/lib/Basic/FileManager.cpp
index af6022f..214e0f3 100644
--- a/lib/Basic/FileManager.cpp
+++ b/lib/Basic/FileManager.cpp
@@ -513,15 +513,47 @@
   File->ModTime = ModificationTime;
 }
 
+/// Remove '.' path components from the given absolute path.
+/// \return \c true if any changes were made.
+// FIXME: Move this to llvm::sys::path.
+bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path) {
+  using namespace llvm::sys;
+
+  SmallVector<StringRef, 16> ComponentStack;
+  StringRef P(Path.data(), Path.size());
+
+  // Skip the root path, then look for traversal in the components.
+  StringRef Rel = path::relative_path(P);
+  bool AnyDots = false;
+  for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) {
+    if (C == ".") {
+      AnyDots = true;
+      continue;
+    }
+    ComponentStack.push_back(C);
+  }
+
+  if (!AnyDots)
+    return false;
+
+  SmallString<256> Buffer = path::root_path(P);
+  for (StringRef C : ComponentStack)
+    path::append(Buffer, C);
+
+  Path.swap(Buffer);
+  return true;
+}
+
 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
   // FIXME: use llvm::sys::fs::canonical() when it gets implemented
-#ifdef LLVM_ON_UNIX
   llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known
     = CanonicalDirNames.find(Dir);
   if (Known != CanonicalDirNames.end())
     return Known->second;
 
   StringRef CanonicalName(Dir->getName());
+
+#ifdef LLVM_ON_UNIX
   char CanonicalNameBuf[PATH_MAX];
   if (realpath(Dir->getName(), CanonicalNameBuf)) {
     unsigned Len = strlen(CanonicalNameBuf);
@@ -529,12 +561,15 @@
     memcpy(Mem, CanonicalNameBuf, Len);
     CanonicalName = StringRef(Mem, Len);
   }
+#else
+  SmallString<256> CanonicalNameBuf(CanonicalName);
+  llvm::sys::fs::make_absolute(CanonicalNameBuf);
+  llvm::sys::path::native(CanonicalNameBuf);
+  removeDotPaths(CanonicalNameBuf);
+#endif
 
   CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName));
   return CanonicalName;
-#else
-  return StringRef(Dir->getName());
-#endif
 }
 
 void FileManager::PrintStats() const {
diff --git a/lib/Basic/IdentifierTable.cpp b/lib/Basic/IdentifierTable.cpp
index dd09704..613b43f 100644
--- a/lib/Basic/IdentifierTable.cpp
+++ b/lib/Basic/IdentifierTable.cpp
@@ -122,7 +122,7 @@
 
 /// \brief Translates flags as specified in TokenKinds.def into keyword status
 /// in the given language standard.
-static KeywordStatus GetKeywordStatus(const LangOptions &LangOpts,
+static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
                                       unsigned Flags) {
   if (Flags == KEYALL) return KS_Enabled;
   if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
@@ -151,7 +151,7 @@
 static void AddKeyword(StringRef Keyword,
                        tok::TokenKind TokenCode, unsigned Flags,
                        const LangOptions &LangOpts, IdentifierTable &Table) {
-  KeywordStatus AddResult = GetKeywordStatus(LangOpts, Flags);
+  KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
 
   // Don't add this keyword under MSVCCompat.
   if (LangOpts.MSVCCompat && (Flags & KEYNOMS))
@@ -209,6 +209,31 @@
                LangOpts, *this);
 }
 
+/// \brief Checks if the specified token kind represents a keyword in the
+/// specified language.
+/// \returns Status of the keyword in the language.
+static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
+                                      tok::TokenKind K) {
+  switch (K) {
+#define KEYWORD(NAME, FLAGS) \
+  case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
+#include "clang/Basic/TokenKinds.def"
+  default: return KS_Disabled;
+  }
+}
+
+/// \brief Returns true if the identifier represents a keyword in the
+/// specified language.
+bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) {
+  switch (getTokenKwStatus(LangOpts, getTokenID())) {
+  case KS_Enabled:
+  case KS_Extension:
+    return true;
+  default:
+    return false;
+  }
+}
+
 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
   // We use a perfect hash function here involving the length of the keyword,
   // the first and third character.  For preprocessor ID's there are no
diff --git a/lib/Basic/LangOptions.cpp b/lib/Basic/LangOptions.cpp
index dcbd228..2c87845 100644
--- a/lib/Basic/LangOptions.cpp
+++ b/lib/Basic/LangOptions.cpp
@@ -30,7 +30,7 @@
   // FIXME: This should not be reset; modules can be different with different
   // sanitizer options (this affects __has_feature(address_sanitizer) etc).
   Sanitize.clear();
-  SanitizerBlacklistFile.clear();
+  SanitizerBlacklistFiles.clear();
 
   CurrentModule.clear();
   ImplementationOfModule.clear();
diff --git a/lib/Basic/Module.cpp b/lib/Basic/Module.cpp
index c0f5a6a..e7e37ce 100644
--- a/lib/Basic/Module.cpp
+++ b/lib/Basic/Module.cpp
@@ -26,7 +26,7 @@
 
 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
                bool IsFramework, bool IsExplicit)
-    : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
+    : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
       Umbrella(), ASTFile(nullptr), IsMissingRequirement(false),
       IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
       IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
@@ -58,21 +58,26 @@
 /// language options has the given feature.
 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
                        const TargetInfo &Target) {
-  return llvm::StringSwitch<bool>(Feature)
-           .Case("altivec", LangOpts.AltiVec)
-           .Case("blocks", LangOpts.Blocks)
-           .Case("cplusplus", LangOpts.CPlusPlus)
-           .Case("cplusplus11", LangOpts.CPlusPlus11)
-           .Case("objc", LangOpts.ObjC1)
-           .Case("objc_arc", LangOpts.ObjCAutoRefCount)
-           .Case("opencl", LangOpts.OpenCL)
-           .Case("tls", Target.isTLSSupported())
-           .Default(Target.hasFeature(Feature));
+  bool HasFeature = llvm::StringSwitch<bool>(Feature)
+                        .Case("altivec", LangOpts.AltiVec)
+                        .Case("blocks", LangOpts.Blocks)
+                        .Case("cplusplus", LangOpts.CPlusPlus)
+                        .Case("cplusplus11", LangOpts.CPlusPlus11)
+                        .Case("objc", LangOpts.ObjC1)
+                        .Case("objc_arc", LangOpts.ObjCAutoRefCount)
+                        .Case("opencl", LangOpts.OpenCL)
+                        .Case("tls", Target.isTLSSupported())
+                        .Default(Target.hasFeature(Feature));
+  if (!HasFeature)
+    HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
+                           LangOpts.ModuleFeatures.end(),
+                           Feature) != LangOpts.ModuleFeatures.end();
+  return HasFeature;
 }
 
-bool
-Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
-                    Requirement &Req, HeaderDirective &MissingHeader) const {
+bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
+                         Requirement &Req,
+                         UnresolvedHeaderDirective &MissingHeader) const {
   if (IsAvailable)
     return true;
 
@@ -293,9 +298,12 @@
     OS << "explicit ";
   OS << "module " << Name;
 
-  if (IsSystem) {
+  if (IsSystem || IsExternC) {
     OS.indent(Indent + 2);
-    OS << " [system]";
+    if (IsSystem)
+      OS << " [system]";
+    if (IsExternC)
+      OS << " [extern_c]";
   }
 
   OS << " {\n";
@@ -338,19 +346,20 @@
     OS << "\n";
   }
 
-  struct HeaderKind {
+  struct {
     StringRef Prefix;
-    const SmallVectorImpl<const FileEntry *> &Headers;
-  } Kinds[] = {{"", NormalHeaders},
-               {"exclude ", ExcludedHeaders},
-               {"textual ", TextualHeaders},
-               {"private ", PrivateHeaders}};
+    HeaderKind Kind;
+  } Kinds[] = {{"", HK_Normal},
+               {"textual ", HK_Textual},
+               {"private ", HK_Private},
+               {"private textual ", HK_PrivateTextual},
+               {"exclude ", HK_Excluded}};
 
   for (auto &K : Kinds) {
-    for (auto *H : K.Headers) {
+    for (auto &H : Headers[K.Kind]) {
       OS.indent(Indent + 2);
       OS << K.Prefix << "header \"";
-      OS.write_escaped(H->getName());
+      OS.write_escaped(H.NameAsWritten);
       OS << "\"\n";
     }
   }
diff --git a/lib/Basic/SanitizerBlacklist.cpp b/lib/Basic/SanitizerBlacklist.cpp
index ea5b8d0..095fcd6 100644
--- a/lib/Basic/SanitizerBlacklist.cpp
+++ b/lib/Basic/SanitizerBlacklist.cpp
@@ -15,9 +15,9 @@
 
 using namespace clang;
 
-SanitizerBlacklist::SanitizerBlacklist(StringRef BlacklistPath,
-                                       SourceManager &SM)
-    : SCL(llvm::SpecialCaseList::createOrDie(BlacklistPath)), SM(SM) {}
+SanitizerBlacklist::SanitizerBlacklist(
+    const std::vector<std::string> &BlacklistPaths, SourceManager &SM)
+    : SCL(llvm::SpecialCaseList::createOrDie(BlacklistPaths)), SM(SM) {}
 
 bool SanitizerBlacklist::isBlacklistedGlobal(StringRef GlobalName,
                                              StringRef Category) const {
diff --git a/lib/Basic/TargetInfo.cpp b/lib/Basic/TargetInfo.cpp
index a352980..871bbd5 100644
--- a/lib/Basic/TargetInfo.cpp
+++ b/lib/Basic/TargetInfo.cpp
@@ -459,7 +459,9 @@
         // Eventually, an unknown constraint should just be treated as 'g'.
         return false;
       }
+      break;
     case '&': // early clobber.
+      Info.setEarlyClobber();
       break;
     case '%': // commutative.
       // FIXME: Check that there is a another register after this one.
@@ -484,9 +486,12 @@
       if (Name[1] == '=' || Name[1] == '+')
         Name++;
       break;
+    case '#': // Ignore as constraint.
+      while (Name[1] && Name[1] != ',')
+        Name++;
+      break;
     case '?': // Disparage slightly code.
     case '!': // Disparage severely.
-    case '#': // Ignore as constraint.
     case '*': // Ignore for choosing register preferences.
       break;  // Pass them.
     }
@@ -494,6 +499,11 @@
     Name++;
   }
 
+  // Early clobber with a read-write constraint which doesn't permit registers
+  // is invalid.
+  if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister())
+    return false;
+
   // If a constraint allows neither memory nor register operands it contains
   // only modifiers. Reject it.
   return Info.allowsMemory() || Info.allowsRegister();
@@ -536,11 +546,17 @@
     default:
       // Check if we have a matching constraint
       if (*Name >= '0' && *Name <= '9') {
-        unsigned i = *Name - '0';
+        const char *DigitStart = Name;
+        while (Name[1] >= '0' && Name[1] <= '9')
+          Name++;
+        const char *DigitEnd = Name;
+        unsigned i;
+        if (StringRef(DigitStart, DigitEnd - DigitStart + 1)
+                .getAsInteger(10, i))
+          return false;
 
         // Check if matching constraint is out of bounds.
-        if (i >= NumOutputs)
-          return false;
+        if (i >= NumOutputs) return false;
 
         // A number must refer to an output only operand.
         if (OutputConstraints[i].isReadWrite())
@@ -571,6 +587,10 @@
       if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
         return false;
 
+      // A number must refer to an output only operand.
+      if (OutputConstraints[Index].isReadWrite())
+        return false;
+
       Info.setTiedOperand(Index, OutputConstraints[Index]);
       break;
     }
@@ -588,6 +608,8 @@
     case 'N':
     case 'O':
     case 'P':
+      if (!validateAsmConstraint(Name, Info))
+        return false;
       break;
     case 'r': // general register.
       Info.setAllowsRegister();
@@ -610,9 +632,12 @@
       break;
     case ',': // multiple alternative constraint.  Ignore comma.
       break;
+    case '#': // Ignore as constraint.
+      while (Name[1] && Name[1] != ',')
+        Name++;
+      break;
     case '?': // Disparage slightly code.
     case '!': // Disparage severely.
-    case '#': // Ignore as constraint.
     case '*': // Ignore for choosing register preferences.
       break;  // Pass them.
     }
@@ -630,6 +655,7 @@
     .Case("ios", iOS)
     .Case("itanium", GenericItanium)
     .Case("microsoft", Microsoft)
+    .Case("mips", GenericMIPS)
     .Default(unknown);
   if (kind == unknown) return false;
 
diff --git a/lib/Basic/Targets.cpp b/lib/Basic/Targets.cpp
index 0dbeb25..063a9be 100644
--- a/lib/Basic/Targets.cpp
+++ b/lib/Basic/Targets.cpp
@@ -25,7 +25,6 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
-#include "llvm/IR/Type.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <algorithm>
@@ -273,6 +272,12 @@
     // On FreeBSD, wchar_t contains the number of the code point as
     // used by the character set of the locale. These character sets are
     // not necessarily a superset of ASCII.
+    //
+    // FIXME: This is wrong; the macro refers to the numerical values
+    // of wchar_t *literals*, which are not locale-dependent. However,
+    // FreeBSD systems apparently depend on us getting this wrong, and
+    // setting this to 1 is conforming even if all the basic source
+    // character literals have the same encoding as char and wchar_t.
     Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
   }
 public:
@@ -519,6 +524,33 @@
   }
 };
 
+template <typename Target>
+class PS4OSTargetInfo : public OSTargetInfo<Target> {
+protected:
+  void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
+                    MacroBuilder &Builder) const override {
+    Builder.defineMacro("__FreeBSD__", "9");
+    Builder.defineMacro("__FreeBSD_cc_version", "900001");
+    Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
+    DefineStd(Builder, "unix", Opts);
+    Builder.defineMacro("__ELF__");
+    Builder.defineMacro("__PS4__");
+  }
+public:
+  PS4OSTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
+    this->WCharType = this->UnsignedShort;
+
+    this->UserLabelPrefix = "";
+
+    switch (Triple.getArch()) {
+    default:
+    case llvm::Triple::x86_64:
+      this->MCountName = ".mcount";
+      break;
+    }
+  }
+};
+
 // Solaris target
 template<typename Target>
 class SolarisTargetInfo : public OSTargetInfo<Target> {
@@ -567,7 +599,7 @@
       if (Opts.RTTIData)
         Builder.defineMacro("_CPPRTTI");
 
-      if (Opts.Exceptions)
+      if (Opts.CXXExceptions)
         Builder.defineMacro("_CPPUNWIND");
     }
 
@@ -653,11 +685,6 @@
       this->DescriptionString = "e-p:32:32-i64:64";
     }
   }
-  typename Target::CallingConvCheckResult checkCallingConvention(
-      CallingConv CC) const override {
-    return CC == CC_PnaclCall ? Target::CCCR_OK :
-        Target::checkCallingConvention(CC);
-  }
 };
 } // end anonymous namespace.
 
@@ -1133,9 +1160,6 @@
     .Default(false);
 
   Features["qpx"] = (CPU == "a2q");
-
-  if (!ABI.empty())
-    Features[ABI] = true;
 }
 
 bool PPCTargetInfo::hasFeature(StringRef Feature) const {
@@ -1368,6 +1392,8 @@
     1,    // opencl_global
     3,    // opencl_local
     4,    // opencl_constant
+    // FIXME: generic has to be added to the target
+    0,    // opencl_generic
     1,    // cuda_device
     4,    // cuda_constant
     3,    // cuda_shared
@@ -1375,6 +1401,16 @@
   class NVPTXTargetInfo : public TargetInfo {
     static const char * const GCCRegNames[];
     static const Builtin::Info BuiltinInfo[];
+
+  // The GPU profiles supported by the NVPTX backend
+  enum GPUKind {
+    GK_NONE,
+    GK_SM20,
+    GK_SM21,
+    GK_SM30,
+    GK_SM35,
+  } GPU;
+
   public:
     NVPTXTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
       BigEndian = false;
@@ -1385,11 +1421,34 @@
       // Define available target features
       // These must be defined in sorted order!
       NoAsmVariants = true;
+      // Set the default GPU to sm20
+      GPU = GK_SM20;
     }
     void getTargetDefines(const LangOptions &Opts,
                           MacroBuilder &Builder) const override {
       Builder.defineMacro("__PTX__");
       Builder.defineMacro("__NVPTX__");
+      if (Opts.CUDAIsDevice) {
+        // Set __CUDA_ARCH__ for the GPU specified.
+        std::string CUDAArchCode;
+        switch (GPU) {
+        case GK_SM20:
+          CUDAArchCode = "200";
+          break;
+        case GK_SM21:
+          CUDAArchCode = "210";
+          break;
+        case GK_SM30:
+          CUDAArchCode = "300";
+          break;
+        case GK_SM35:
+          CUDAArchCode = "350";
+          break;
+        default:
+          llvm_unreachable("Unhandled target CPU");
+        }
+        Builder.defineMacro("__CUDA_ARCH__", CUDAArchCode);
+      }
     }
     void getTargetBuiltins(const Builtin::Info *&Records,
                            unsigned &NumRecords) const override {
@@ -1432,14 +1491,14 @@
       return TargetInfo::CharPtrBuiltinVaList;
     }
     bool setCPU(const std::string &Name) override {
-      bool Valid = llvm::StringSwitch<bool>(Name)
-        .Case("sm_20", true)
-        .Case("sm_21", true)
-        .Case("sm_30", true)
-        .Case("sm_35", true)
-        .Default(false);
+      GPU = llvm::StringSwitch<GPUKind>(Name)
+                .Case("sm_20", GK_SM20)
+                .Case("sm_21", GK_SM21)
+                .Case("sm_30", GK_SM30)
+                .Case("sm_35", GK_SM35)
+                .Default(GK_NONE);
 
-      return Valid;
+      return GPU != GK_NONE;
     }
   };
 
@@ -1487,6 +1546,7 @@
   1,    // opencl_global
   3,    // opencl_local
   2,    // opencl_constant
+  4,    // opencl_generic
   1,    // cuda_device
   2,    // cuda_constant
   3     // cuda_shared
@@ -1528,8 +1588,15 @@
 
 public:
   R600TargetInfo(const llvm::Triple &Triple)
-      : TargetInfo(Triple), GPU(GK_R600) {
-    DescriptionString = DescriptionStringR600;
+      : TargetInfo(Triple) {
+
+    if (Triple.getArch() == llvm::Triple::amdgcn) {
+      DescriptionString = DescriptionStringSI;
+      GPU = GK_SOUTHERN_ISLANDS;
+    } else {
+      DescriptionString = DescriptionStringR600;
+      GPU = GK_R600;
+    }
     AddrSpaceMap = &R600AddrSpaceMap;
     UseAddrSpaceMapMangling = true;
   }
@@ -1799,28 +1866,42 @@
     /// \name Atom
     /// Atom processors
     //@{
-    CK_Atom,
+    CK_Bonnell,
     CK_Silvermont,
     //@}
 
     /// \name Nehalem
     /// Nehalem microarchitecture based processors.
-    //@{
-    CK_Corei7,
-    CK_Corei7AVX,
-    CK_CoreAVXi,
-    CK_CoreAVX2,
+    CK_Nehalem,
+
+    /// \name Westmere
+    /// Westmere microarchitecture based processors.
+    CK_Westmere,
+
+    /// \name Sandy Bridge
+    /// Sandy Bridge microarchitecture based processors.
+    CK_SandyBridge,
+
+    /// \name Ivy Bridge
+    /// Ivy Bridge microarchitecture based processors.
+    CK_IvyBridge,
+
+    /// \name Haswell
+    /// Haswell microarchitecture based processors.
+    CK_Haswell,
+
+    /// \name Broadwell
+    /// Broadwell microarchitecture based processors.
     CK_Broadwell,
-    //@}
+
+    /// \name Skylake
+    /// Skylake microarchitecture based processors.
+    CK_Skylake,
 
     /// \name Knights Landing
     /// Knights Landing processor.
     CK_KNL,
 
-    /// \name Skylake Server
-    /// Skylake server processor.
-    CK_SKX,
-
     /// \name K6
     /// K6 architecture processors.
     //@{
@@ -1990,15 +2071,23 @@
       .Case("nocona", CK_Nocona)
       .Case("core2", CK_Core2)
       .Case("penryn", CK_Penryn)
-      .Case("atom", CK_Atom)
-      .Case("slm", CK_Silvermont)
-      .Case("corei7", CK_Corei7)
-      .Case("corei7-avx", CK_Corei7AVX)
-      .Case("core-avx-i", CK_CoreAVXi)
-      .Case("core-avx2", CK_CoreAVX2)
+      .Case("bonnell", CK_Bonnell)
+      .Case("atom", CK_Bonnell) // Legacy name.
+      .Case("silvermont", CK_Silvermont)
+      .Case("slm", CK_Silvermont) // Legacy name.
+      .Case("nehalem", CK_Nehalem)
+      .Case("corei7", CK_Nehalem) // Legacy name.
+      .Case("westmere", CK_Westmere)
+      .Case("sandybridge", CK_SandyBridge)
+      .Case("corei7-avx", CK_SandyBridge) // Legacy name.
+      .Case("ivybridge", CK_IvyBridge)
+      .Case("core-avx-i", CK_IvyBridge) // Legacy name.
+      .Case("haswell", CK_Haswell)
+      .Case("core-avx2", CK_Haswell) // Legacy name.
       .Case("broadwell", CK_Broadwell)
+      .Case("skylake", CK_Skylake)
+      .Case("skx", CK_Skylake) // Legacy name.
       .Case("knl", CK_KNL)
-      .Case("skx", CK_SKX)
       .Case("k6", CK_K6)
       .Case("k6-2", CK_K6_2)
       .Case("k6-3", CK_K6_3)
@@ -2014,6 +2103,7 @@
       .Case("k8-sse3", CK_K8SSE3)
       .Case("opteron", CK_Opteron)
       .Case("opteron-sse3", CK_OpteronSSE3)
+      .Case("barcelona", CK_AMDFAM10)
       .Case("amdfam10", CK_AMDFAM10)
       .Case("btver1", CK_BTVER1)
       .Case("btver2", CK_BTVER2)
@@ -2070,15 +2160,16 @@
     case CK_Nocona:
     case CK_Core2:
     case CK_Penryn:
-    case CK_Atom:
+    case CK_Bonnell:
     case CK_Silvermont:
-    case CK_Corei7:
-    case CK_Corei7AVX:
-    case CK_CoreAVXi:
-    case CK_CoreAVX2:
+    case CK_Nehalem:
+    case CK_Westmere:
+    case CK_SandyBridge:
+    case CK_IvyBridge:
+    case CK_Haswell:
     case CK_Broadwell:
+    case CK_Skylake:
     case CK_KNL:
-    case CK_SKX:
     case CK_Athlon64:
     case CK_Athlon64SSE3:
     case CK_AthlonFX:
@@ -2169,7 +2260,7 @@
     setFeatureEnabledImpl(Features, "cx16", true);
     break;
   case CK_Core2:
-  case CK_Atom:
+  case CK_Bonnell:
     setFeatureEnabledImpl(Features, "ssse3", true);
     setFeatureEnabledImpl(Features, "cx16", true);
     break;
@@ -2177,7 +2268,7 @@
     setFeatureEnabledImpl(Features, "sse4.1", true);
     setFeatureEnabledImpl(Features, "cx16", true);
     break;
-  case CK_SKX:
+  case CK_Skylake:
     setFeatureEnabledImpl(Features, "avx512f", true);
     setFeatureEnabledImpl(Features, "avx512cd", true);
     setFeatureEnabledImpl(Features, "avx512dq", true);
@@ -2188,7 +2279,7 @@
     setFeatureEnabledImpl(Features, "rdseed", true);
     setFeatureEnabledImpl(Features, "adx", true);
     // FALLTHROUGH
-  case CK_CoreAVX2:
+  case CK_Haswell:
     setFeatureEnabledImpl(Features, "avx2", true);
     setFeatureEnabledImpl(Features, "lzcnt", true);
     setFeatureEnabledImpl(Features, "bmi", true);
@@ -2196,19 +2287,20 @@
     setFeatureEnabledImpl(Features, "rtm", true);
     setFeatureEnabledImpl(Features, "fma", true);
     // FALLTHROUGH
-  case CK_CoreAVXi:
+  case CK_IvyBridge:
     setFeatureEnabledImpl(Features, "rdrnd", true);
     setFeatureEnabledImpl(Features, "f16c", true);
     setFeatureEnabledImpl(Features, "fsgsbase", true);
     // FALLTHROUGH
-  case CK_Corei7AVX:
+  case CK_SandyBridge:
     setFeatureEnabledImpl(Features, "avx", true);
     // FALLTHROUGH
+  case CK_Westmere:
   case CK_Silvermont:
     setFeatureEnabledImpl(Features, "aes", true);
     setFeatureEnabledImpl(Features, "pclmul", true);
     // FALLTHROUGH
-  case CK_Corei7:
+  case CK_Nehalem:
     setFeatureEnabledImpl(Features, "sse4.2", true);
     setFeatureEnabledImpl(Features, "cx16", true);
     break;
@@ -2357,8 +2449,8 @@
     Features["avx2"] = false;
   case AVX512F:
     Features["avx512f"] = Features["avx512cd"] = Features["avx512er"] =
-        Features["avx512pf"] = Features["avx512dq"] = Features["avx512bw"] =
-            Features["avx512vl"] = false;
+      Features["avx512pf"] = Features["avx512dq"] = Features["avx512bw"] =
+      Features["avx512vl"] = false;
   }
 }
 
@@ -2751,25 +2843,33 @@
   case CK_Penryn:
     defineCPUMacros(Builder, "core2");
     break;
-  case CK_Atom:
+  case CK_Bonnell:
     defineCPUMacros(Builder, "atom");
     break;
   case CK_Silvermont:
     defineCPUMacros(Builder, "slm");
     break;
-  case CK_Corei7:
-  case CK_Corei7AVX:
-  case CK_CoreAVXi:
-  case CK_CoreAVX2:
+  case CK_Nehalem:
+  case CK_Westmere:
+  case CK_SandyBridge:
+  case CK_IvyBridge:
+  case CK_Haswell:
   case CK_Broadwell:
+    // FIXME: Historically, we defined this legacy name, it would be nice to
+    // remove it at some point. We've never exposed fine-grained names for
+    // recent primary x86 CPUs, and we should keep it that way.
     defineCPUMacros(Builder, "corei7");
     break;
+  case CK_Skylake:
+    // FIXME: Historically, we defined this legacy name, it would be nice to
+    // remove it at some point. This is the only fine-grained CPU macro in the
+    // main intel CPU line, and it would be better to not have these and force
+    // people to use ISA macros.
+    defineCPUMacros(Builder, "skx");
+    break;
   case CK_KNL:
     defineCPUMacros(Builder, "knl");
     break;
-  case CK_SKX:
-    defineCPUMacros(Builder, "skx");
-    break;
   case CK_K6_2:
     Builder.defineMacro("__k6_2__");
     Builder.defineMacro("__tune_k6_2__");
@@ -3033,6 +3133,28 @@
                                      TargetInfo::ConstraintInfo &Info) const {
   switch (*Name) {
   default: return false;
+  case 'I':
+    Info.setRequiresImmediate(0, 31);
+    return true;
+  case 'J':
+    Info.setRequiresImmediate(0, 63);
+    return true;
+  case 'K':
+    Info.setRequiresImmediate(-128, 127);
+    return true;
+  case 'L':
+    // FIXME: properly analyze this constraint:
+    //  must be one of 0xff, 0xffff, or 0xffffffff
+    return true;
+  case 'M':
+    Info.setRequiresImmediate(0, 3);
+    return true;
+  case 'N':
+    Info.setRequiresImmediate(0, 255);
+    return true;
+  case 'O':
+    Info.setRequiresImmediate(0, 127);
+    return true;
   case 'Y': // first letter of a pair:
     switch (*(Name+1)) {
     default: return false;
@@ -3504,19 +3626,31 @@
     IntPtrType = SignedLongLong;
     this->UserLabelPrefix = "";
   }
+
   void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const override {
     WindowsTargetInfo<X86_64TargetInfo>::getTargetDefines(Opts, Builder);
     Builder.defineMacro("_WIN64");
   }
+
   BuiltinVaListKind getBuiltinVaListKind() const override {
     return TargetInfo::CharPtrBuiltinVaList;
   }
+
   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
-    return (CC == CC_C ||
-            CC == CC_X86VectorCall ||
-            CC == CC_IntelOclBicc ||
-            CC == CC_X86_64SysV) ? CCCR_OK : CCCR_Warning;
+    switch (CC) {
+    case CC_X86StdCall:
+    case CC_X86ThisCall:
+    case CC_X86FastCall:
+      return CCCR_Ignore;
+    case CC_C:
+    case CC_X86VectorCall:
+    case CC_IntelOclBicc:
+    case CC_X86_64SysV:
+      return CCCR_OK;
+    default:
+      return CCCR_Warning;
+    }
   }
 };
 } // end anonymous namespace
@@ -3802,7 +3936,45 @@
     // FIXME: Should we just treat this as a feature?
     IsThumb = getTriple().getArchName().startswith("thumb");
 
-    setABI("aapcs-linux");
+    // FIXME: This duplicates code from the driver that sets the -target-abi
+    // option - this code is used if -target-abi isn't passed and should
+    // be unified in some way.
+    if (Triple.isOSBinFormatMachO()) {
+      // The backend is hardwired to assume AAPCS for M-class processors, ensure
+      // the frontend matches that.
+      if (Triple.getEnvironment() == llvm::Triple::EABI ||
+          Triple.getOS() == llvm::Triple::UnknownOS ||
+          StringRef(CPU).startswith("cortex-m")) {
+        setABI("aapcs");
+      } else {
+        setABI("apcs-gnu");
+      }
+    } else if (Triple.isOSWindows()) {
+      // FIXME: this is invalid for WindowsCE
+      setABI("aapcs");
+    } else {
+      // Select the default based on the platform.
+      switch (Triple.getEnvironment()) {
+      case llvm::Triple::Android:
+      case llvm::Triple::GNUEABI:
+      case llvm::Triple::GNUEABIHF:
+        setABI("aapcs-linux");
+        break;
+      case llvm::Triple::EABIHF:
+      case llvm::Triple::EABI:
+        setABI("aapcs");
+        break;
+      case llvm::Triple::GNU:
+	setABI("apcs-gnu");
+	break;
+      default:
+        if (Triple.getOS() == llvm::Triple::NetBSD)
+          setABI("apcs-gnu");
+        else
+          setABI("aapcs");
+        break;
+      }
+    }
 
     // ARM targets default to using the ARM C++ ABI.
     TheCXXABI.set(TargetCXXABI::GenericARM);
@@ -3838,11 +4010,6 @@
   }
 
   void getDefaultFeatures(llvm::StringMap<bool> &Features) const override {
-    if (IsAAPCS)
-      Features["aapcs"] = true;
-    else
-      Features["apcs"] = true;
-
     StringRef ArchName = getTriple().getArchName();
     if (CPU == "arm1136jf-s" || CPU == "arm1176jzf-s" || CPU == "mpcore")
       Features["vfp2"] = true;
@@ -3865,14 +4032,14 @@
       Features["neon"] = true;
       Features["hwdiv"] = true;
       Features["hwdiv-arm"] = true;
-    } else if (CPU == "cortex-a53" || CPU == "cortex-a57") {
+    } else if (CPU == "cortex-a53" || CPU == "cortex-a57" || CPU == "cortex-a72") {
       Features["fp-armv8"] = true;
       Features["neon"] = true;
       Features["hwdiv"] = true;
       Features["hwdiv-arm"] = true;
       Features["crc"] = true;
       Features["crypto"] = true;
-    } else if (CPU == "cortex-r5" ||
+    } else if (CPU == "cortex-r5" || CPU == "cortex-r7" ||
                // Enable the hwdiv extension for all v8a AArch32 cores by
                // default.
                ArchName == "armv8a" || ArchName == "armv8" ||
@@ -3881,7 +4048,8 @@
                ArchName == "thumbebv8a" || ArchName == "thumbebv8") {
       Features["hwdiv"] = true;
       Features["hwdiv-arm"] = true;
-    } else if (CPU == "cortex-m3" || CPU == "cortex-m4" || CPU == "cortex-m7") {
+    } else if (CPU == "cortex-m3" || CPU == "cortex-m4" || CPU == "cortex-m7" ||
+               CPU == "sc300") {
       Features["hwdiv"] = true;
     }
   }
@@ -3981,13 +4149,13 @@
         .Cases("cortex-a5", "cortex-a7", "cortex-a8", "7A")
         .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait",
                "7A")
-        .Cases("cortex-r4", "cortex-r5", "7R")
+        .Cases("cortex-r4", "cortex-r5", "cortex-r7", "7R")
         .Case("swift", "7S")
         .Case("cyclone", "8A")
-        .Case("cortex-m3", "7M")
+        .Cases("sc300", "cortex-m3", "7M")
         .Cases("cortex-m4", "cortex-m7", "7EM")
-        .Case("cortex-m0", "6M")
-        .Cases("cortex-a53", "cortex-a57", "8A")
+        .Cases("sc000", "cortex-m0", "cortex-m0plus", "cortex-m1", "6M")
+        .Cases("cortex-a53", "cortex-a57", "cortex-a72", "8A")
         .Default(nullptr);
   }
   static const char *getCPUProfile(StringRef Name) {
@@ -3995,9 +4163,10 @@
         .Cases("cortex-a5", "cortex-a7", "cortex-a8", "A")
         .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait",
                "A")
-        .Cases("cortex-a53", "cortex-a57", "A")
-        .Cases("cortex-m3", "cortex-m4", "cortex-m0", "cortex-m7", "M")
-        .Cases("cortex-r4", "cortex-r5", "R")
+        .Cases("cortex-a53", "cortex-a57", "cortex-a72", "A")
+        .Cases("cortex-m3", "cortex-m4", "cortex-m0", "cortex-m0plus", "M")
+        .Cases("cortex-m1", "cortex-m7", "sc000", "sc300", "M")
+        .Cases("cortex-r4", "cortex-r5", "cortex-r7", "R")
         .Default("");
   }
   bool setCPU(const std::string &Name) override {
@@ -4158,6 +4327,13 @@
       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
     }
+
+    bool is5EOrAbove = (CPUArchVer >= 6 ||
+                        (CPUArchVer == 5 &&
+                         CPUArch.find('E') != StringRef::npos));
+    bool is32Bit = (!IsThumb || supportsThumb2(ArchName, CPUArch, CPUArchVer));
+    if (is5EOrAbove && is32Bit && (CPUProfile != "M" || CPUArch  == "7EM"))
+      Builder.defineMacro("__ARM_FEATURE_DSP");
   }
   void getTargetBuiltins(const Builtin::Info *&Records,
                          unsigned &NumRecords) const override {
@@ -4182,6 +4358,13 @@
     case 'P': // VFP Floating point register double precision
       Info.setAllowsRegister();
       return true;
+    case 'I':
+    case 'J':
+    case 'K':
+    case 'L':
+    case 'M':
+      // FIXME
+      return true;
     case 'Q': // A memory address that is a single base register.
       Info.setAllowsMemory();
       return true;
@@ -4501,13 +4684,20 @@
     MaxAtomicInlineWidth = 128;
     MaxAtomicPromoteWidth = 128;
 
-    LongDoubleWidth = LongDoubleAlign = 128;
+    LongDoubleWidth = LongDoubleAlign = SuitableAlign = 128;
     LongDoubleFormat = &llvm::APFloat::IEEEquad;
 
     // {} in inline assembly are neon specifiers, not assembly variant
     // specifiers.
     NoAsmVariants = true;
 
+    // AAPCS gives rules for bitfields. 7.1.7 says: "The container type
+    // contributes to the alignment of the containing aggregate in the same way
+    // a plain (non bit-field) member of that type would, without exception for
+    // zero-sized or anonymous bit-fields."
+    UseBitFieldTypeAlignment = true;
+    UseZeroLengthBitfieldAlignment = true;
+
     // AArch64 targets default to using the ARM C++ ABI.
     TheCXXABI.set(TargetCXXABI::GenericAArch64);
   }
@@ -4524,7 +4714,7 @@
   bool setCPU(const std::string &Name) override {
     bool CPUKnown = llvm::StringSwitch<bool>(Name)
                         .Case("generic", true)
-                        .Cases("cortex-a53", "cortex-a57", true)
+                        .Cases("cortex-a53", "cortex-a57", "cortex-a72", true)
                         .Case("cyclone", true)
                         .Default(false);
     return CPUKnown;
@@ -4834,7 +5024,7 @@
     WCharType = SignedInt;
     UseSignedCharForObjCBool = false;
 
-    LongDoubleWidth = LongDoubleAlign = 64;
+    LongDoubleWidth = LongDoubleAlign = SuitableAlign = 64;
     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
 
     TheCXXABI.set(TargetCXXABI::iOS64);
@@ -5045,6 +5235,16 @@
   bool validateAsmConstraint(const char *&Name,
                              TargetInfo::ConstraintInfo &info) const override {
     // FIXME: Implement!
+    switch (*Name) {
+    case 'I': // Signed 13-bit constant
+    case 'J': // Zero
+    case 'K': // 32-bit constant with the low 12 bits clear
+    case 'L': // A constant in the range supported by movcc (11-bit signed imm)
+    case 'M': // A constant in the range supported by movrcc (19-bit signed imm)
+    case 'N': // Same as 'K' but zext (required for SIMode)
+    case 'O': // The constant 4096
+      return true;
+    }
     return false;
   }
   const char *getClobbers() const override {
@@ -5337,6 +5537,13 @@
     bool
     validateAsmConstraint(const char *&Name,
                           TargetInfo::ConstraintInfo &info) const override {
+      // FIXME: implement
+      switch (*Name) {
+      case 'K': // the constant 1
+      case 'L': // constant -1^20 .. 1^19
+      case 'M': // constant 1-4:
+        return true;
+      }
       // No target constraints for now.
       return false;
     }
@@ -5376,6 +5583,8 @@
       3, // opencl_global
       4, // opencl_local
       5, // opencl_constant
+      // FIXME: generic has to be added to the target
+      0, // opencl_generic
       0, // cuda_device
       0, // cuda_constant
       0  // cuda_shared
@@ -5467,7 +5676,9 @@
                      const std::string &CPUStr)
       : TargetInfo(Triple), CPU(CPUStr), IsMips16(false), IsMicromips(false),
         IsNan2008(false), IsSingleFloat(false), FloatABI(HardFloat),
-        DspRev(NoDSP), HasMSA(false), HasFP64(false), ABI(ABIStr) {}
+        DspRev(NoDSP), HasMSA(false), HasFP64(false), ABI(ABIStr) {
+    TheCXXABI.set(TargetCXXABI::GenericMIPS);
+  }
 
   bool isNaN2008Default() const {
     return CPU == "mips32r6" || CPU == "mips64r6";
@@ -5477,6 +5688,10 @@
     return CPU == "mips32r6" || ABI == "n32" || ABI == "n64" || ABI == "64";
   }
 
+  bool isNan2008() const override {
+    return IsNan2008;
+  }
+
   StringRef getABI() const override { return ABI; }
   bool setCPU(const std::string &Name) override {
     bool IsMips32 = getTriple().getArch() == llvm::Triple::mips ||
@@ -5490,23 +5705,19 @@
         .Case("mips5", true)
         .Case("mips32", IsMips32)
         .Case("mips32r2", IsMips32)
+        .Case("mips32r3", IsMips32)
+        .Case("mips32r5", IsMips32)
         .Case("mips32r6", IsMips32)
         .Case("mips64", true)
         .Case("mips64r2", true)
+        .Case("mips64r3", true)
+        .Case("mips64r5", true)
         .Case("mips64r6", true)
         .Case("octeon", true)
         .Default(false);
   }
   const std::string& getCPU() const { return CPU; }
   void getDefaultFeatures(llvm::StringMap<bool> &Features) const override {
-    // The backend enables certain ABI's by default according to the
-    // architecture.
-    // Disable both possible defaults so that we don't end up with multiple
-    // ABI's selected and trigger an assertion.
-    Features["o32"] = false;
-    Features["n64"] = false;
-
-    Features[ABI] = true;
     if (CPU == "octeon")
       Features["mips64r2"] = Features["cnmips"] = true;
     else
@@ -5631,6 +5842,15 @@
     case 'x': // hilo register pair
       Info.setAllowsRegister();
       return true;
+    case 'I': // Signed 16-bit constant
+    case 'J': // Integer 0
+    case 'K': // Unsigned 16-bit constant
+    case 'L': // Signed 32-bit constant, lower 16-bit zeros (for lui)
+    case 'M': // Constants not loadable via lui, addiu, or ori
+    case 'N': // Constant -1 to -65535
+    case 'O': // A signed 15-bit constant
+    case 'P': // A constant between 1 go 65535
+      return true;
     case 'R': // An address that can be used in a non-macro load or store
       Info.setAllowsMemory();
       return true;
@@ -5638,8 +5858,28 @@
   }
 
   const char *getClobbers() const override {
-    // FIXME: Implement!
-    return "";
+    // In GCC, $1 is not widely used in generated code (it's used only in a few
+    // specific situations), so there is no real need for users to add it to
+    // the clobbers list if they want to use it in their inline assembly code.
+    //
+    // In LLVM, $1 is treated as a normal GPR and is always allocatable during
+    // code generation, so using it in inline assembly without adding it to the
+    // clobbers list can cause conflicts between the inline assembly code and
+    // the surrounding generated code.
+    //
+    // Another problem is that LLVM is allowed to choose $1 for inline assembly
+    // operands, which will conflict with the ".set at" assembler option (which
+    // we use only for inline assembly, in order to maintain compatibility with
+    // GCC) and will also conflict with the user's usage of $1.
+    //
+    // The easiest way to avoid these conflicts and keep $1 as an allocatable
+    // register for generated code is to automatically clobber $1 for all inline
+    // assembly code.
+    //
+    // FIXME: We should automatically clobber $1 only for inline assembly code
+    // which actually uses it. This would allow LLVM to use $1 for inline
+    // assembly operands if the user's assembly code doesn't use it.
+    return "~{$1}";
   }
 
   bool handleTargetFeatures(std::vector<std::string> &Features,
@@ -5711,6 +5951,8 @@
       : MipsTargetInfoBase(Triple, "o32", "mips32r2") {
     SizeType = UnsignedInt;
     PtrDiffType = SignedInt;
+    Int64Type = SignedLongLong;
+    IntMaxType = Int64Type;
     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
   }
   bool setABI(const std::string &Name) override {
@@ -5732,6 +5974,12 @@
       Builder.defineMacro("__mips_isa_rev", "1");
     else if (CPUStr == "mips32r2")
       Builder.defineMacro("__mips_isa_rev", "2");
+    else if (CPUStr == "mips32r3")
+      Builder.defineMacro("__mips_isa_rev", "3");
+    else if (CPUStr == "mips32r5")
+      Builder.defineMacro("__mips_isa_rev", "5");
+    else if (CPUStr == "mips32r6")
+      Builder.defineMacro("__mips_isa_rev", "6");
 
     if (ABI == "o32") {
       Builder.defineMacro("__mips_o32");
@@ -5838,6 +6086,8 @@
     PointerWidth = PointerAlign = 64;
     SizeType = UnsignedLong;
     PtrDiffType = SignedLong;
+    Int64Type = SignedLong;
+    IntMaxType = Int64Type;
   }
 
   void setN32ABITypes() {
@@ -5845,6 +6095,8 @@
     PointerWidth = PointerAlign = 32;
     SizeType = UnsignedInt;
     PtrDiffType = SignedInt;
+    Int64Type = SignedLongLong;
+    IntMaxType = Int64Type;
   }
 
   bool setABI(const std::string &Name) override {
@@ -5875,6 +6127,12 @@
       Builder.defineMacro("__mips_isa_rev", "1");
     else if (CPUStr == "mips64r2")
       Builder.defineMacro("__mips_isa_rev", "2");
+    else if (CPUStr == "mips64r3")
+      Builder.defineMacro("__mips_isa_rev", "3");
+    else if (CPUStr == "mips64r5")
+      Builder.defineMacro("__mips_isa_rev", "5");
+    else if (CPUStr == "mips64r6")
+      Builder.defineMacro("__mips_isa_rev", "6");
 
     if (ABI == "n32") {
       Builder.defineMacro("__mips_n32");
@@ -6051,7 +6309,7 @@
     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
     DescriptionString =
-        "e-S128-p:64:64-v16:16-v32:32-v64:64-v96:32-v128:32-m:e-n8:16:32:64";
+        "e-m:e-v128:32-v16:16-v32:32-v96:32-n8:16:32:64-S128";
   }
 
   void getTargetDefines(const LangOptions &Opts,
@@ -6099,6 +6357,7 @@
     1,    // opencl_global
     3,    // opencl_local
     2,    // opencl_constant
+    4,    // opencl_generic
     0,    // cuda_device
     0,    // cuda_constant
     0     // cuda_shared
@@ -6144,6 +6403,15 @@
     BuiltinVaListKind getBuiltinVaListKind() const override {
       return TargetInfo::VoidPtrBuiltinVaList;
     }
+
+    CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
+      return (CC == CC_SpirFunction ||
+              CC == CC_SpirKernel) ? CCCR_OK : CCCR_Warning;
+    }
+
+    CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
+      return CC_SpirFunction;
+    }
   };
 
 
@@ -6470,6 +6738,7 @@
   case llvm::Triple::nvptx64:
     return new NVPTX64TargetInfo(Triple);
 
+  case llvm::Triple::amdgcn:
   case llvm::Triple::r600:
     return new R600TargetInfo(Triple);
 
@@ -6595,6 +6864,8 @@
     }
     case llvm::Triple::NaCl:
       return new NaClTargetInfo<X86_64TargetInfo>(Triple);
+    case llvm::Triple::PS4:
+      return new PS4OSTargetInfo<X86_64TargetInfo>(Triple);
     default:
       return new X86_64TargetInfo(Triple);
     }
diff --git a/lib/Basic/VirtualFileSystem.cpp b/lib/Basic/VirtualFileSystem.cpp
index 617b82e..c89195e 100644
--- a/lib/Basic/VirtualFileSystem.cpp
+++ b/lib/Basic/VirtualFileSystem.cpp
@@ -11,10 +11,10 @@
 
 #include "clang/Basic/VirtualFileSystem.h"
 #include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/iterator_range.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
diff --git a/lib/CodeGen/ABIInfo.h b/lib/CodeGen/ABIInfo.h
index 2976b60..7e7f7fa 100644
--- a/lib/CodeGen/ABIInfo.h
+++ b/lib/CodeGen/ABIInfo.h
@@ -44,9 +44,12 @@
     CodeGen::CodeGenTypes &CGT;
   protected:
     llvm::CallingConv::ID RuntimeCC;
+    llvm::CallingConv::ID BuiltinCC;
   public:
     ABIInfo(CodeGen::CodeGenTypes &cgt)
-      : CGT(cgt), RuntimeCC(llvm::CallingConv::C) {}
+      : CGT(cgt),
+        RuntimeCC(llvm::CallingConv::C),
+        BuiltinCC(llvm::CallingConv::C) {}
 
     virtual ~ABIInfo();
 
@@ -62,6 +65,11 @@
       return RuntimeCC;
     }
 
+    /// Return the calling convention to use for compiler builtins
+    llvm::CallingConv::ID getBuiltinCC() const {
+      return BuiltinCC;
+    }
+
     virtual void computeInfo(CodeGen::CGFunctionInfo &FI) const = 0;
 
     /// EmitVAArg - Emit the target dependent code to load a value of
diff --git a/lib/CodeGen/BackendUtil.cpp b/lib/CodeGen/BackendUtil.cpp
index 41f2131..da3e5ce 100644
--- a/lib/CodeGen/BackendUtil.cpp
+++ b/lib/CodeGen/BackendUtil.cpp
@@ -15,22 +15,23 @@
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/Utils.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/CodeGen/RegAllocRegistry.h"
 #include "llvm/CodeGen/SchedulerRegistry.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/MC/SubtargetFeature.h"
-#include "llvm/PassManager.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Target/TargetSubtargetInfo.h"
@@ -39,6 +40,7 @@
 #include "llvm/Transforms/Instrumentation.h"
 #include "llvm/Transforms/ObjCARC.h"
 #include "llvm/Transforms/Scalar.h"
+#include "llvm/Transforms/Utils/SymbolRewriter.h"
 #include <memory>
 using namespace clang;
 using namespace llvm;
@@ -54,37 +56,44 @@
 
   Timer CodeGenerationTime;
 
-  mutable PassManager *CodeGenPasses;
-  mutable PassManager *PerModulePasses;
-  mutable FunctionPassManager *PerFunctionPasses;
+  mutable legacy::PassManager *CodeGenPasses;
+  mutable legacy::PassManager *PerModulePasses;
+  mutable legacy::FunctionPassManager *PerFunctionPasses;
 
 private:
-  PassManager *getCodeGenPasses() const {
+  TargetIRAnalysis getTargetIRAnalysis() const {
+    if (TM)
+      return TM->getTargetIRAnalysis();
+
+    return TargetIRAnalysis();
+  }
+
+  legacy::PassManager *getCodeGenPasses() const {
     if (!CodeGenPasses) {
-      CodeGenPasses = new PassManager();
+      CodeGenPasses = new legacy::PassManager();
       CodeGenPasses->add(new DataLayoutPass());
-      if (TM)
-        TM->addAnalysisPasses(*CodeGenPasses);
+      CodeGenPasses->add(
+          createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
     }
     return CodeGenPasses;
   }
 
-  PassManager *getPerModulePasses() const {
+  legacy::PassManager *getPerModulePasses() const {
     if (!PerModulePasses) {
-      PerModulePasses = new PassManager();
+      PerModulePasses = new legacy::PassManager();
       PerModulePasses->add(new DataLayoutPass());
-      if (TM)
-        TM->addAnalysisPasses(*PerModulePasses);
+      PerModulePasses->add(
+          createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
     }
     return PerModulePasses;
   }
 
-  FunctionPassManager *getPerFunctionPasses() const {
+  legacy::FunctionPassManager *getPerFunctionPasses() const {
     if (!PerFunctionPasses) {
-      PerFunctionPasses = new FunctionPassManager(TheModule);
+      PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
       PerFunctionPasses->add(new DataLayoutPass());
-      if (TM)
-        TM->addAnalysisPasses(*PerFunctionPasses);
+      PerFunctionPasses->add(
+          createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
     }
     return PerFunctionPasses;
   }
@@ -162,7 +171,7 @@
 }
 
 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
-                                       PassManagerBase &PM) {
+                                       legacy::PassManagerBase &PM) {
   const PassManagerBuilderWrapper &BuilderWrapper =
       static_cast<const PassManagerBuilderWrapper &>(Builder);
   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
@@ -170,17 +179,17 @@
 }
 
 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
-                                     PassManagerBase &PM) {
+                                     legacy::PassManagerBase &PM) {
   PM.add(createAddDiscriminatorsPass());
 }
 
 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
-                                    PassManagerBase &PM) {
+                                    legacy::PassManagerBase &PM) {
   PM.add(createBoundsCheckingPass());
 }
 
 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
-                                     PassManagerBase &PM) {
+                                     legacy::PassManagerBase &PM) {
   const PassManagerBuilderWrapper &BuilderWrapper =
       static_cast<const PassManagerBuilderWrapper&>(Builder);
   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
@@ -188,13 +197,13 @@
 }
 
 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
-                                      PassManagerBase &PM) {
+                                      legacy::PassManagerBase &PM) {
   PM.add(createAddressSanitizerFunctionPass());
   PM.add(createAddressSanitizerModulePass());
 }
 
 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
-                                   PassManagerBase &PM) {
+                                   legacy::PassManagerBase &PM) {
   const PassManagerBuilderWrapper &BuilderWrapper =
       static_cast<const PassManagerBuilderWrapper&>(Builder);
   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
@@ -214,24 +223,35 @@
 }
 
 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
-                                   PassManagerBase &PM) {
+                                   legacy::PassManagerBase &PM) {
   PM.add(createThreadSanitizerPass());
 }
 
 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
-                                     PassManagerBase &PM) {
+                                     legacy::PassManagerBase &PM) {
   const PassManagerBuilderWrapper &BuilderWrapper =
       static_cast<const PassManagerBuilderWrapper&>(Builder);
   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
-  PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFile));
+  PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
 }
 
-static TargetLibraryInfo *createTLI(llvm::Triple &TargetTriple,
-                                    const CodeGenOptions &CodeGenOpts) {
-  TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
+static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
+                                         const CodeGenOptions &CodeGenOpts) {
+  TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
   if (!CodeGenOpts.SimplifyLibCalls)
-    TLI->disableAllFunctions();
-  return TLI;
+    TLII->disableAllFunctions();
+  return TLII;
+}
+
+static void addSymbolRewriterPass(const CodeGenOptions &Opts,
+                                  legacy::PassManager *MPM) {
+  llvm::SymbolRewriter::RewriteDescriptorList DL;
+
+  llvm::SymbolRewriter::RewriteMapParser MapParser;
+  for (const auto &MapFile : Opts.RewriteMapFiles)
+    MapParser.parse(MapFile, &DL);
+
+  MPM->add(createRewriteSymbolsPass(DL));
 }
 
 void EmitAssemblyHelper::CreatePasses() {
@@ -319,7 +339,7 @@
 
   // Figure out TargetLibraryInfo.
   Triple TargetTriple(TheModule->getTargetTriple());
-  PMBuilder.LibraryInfo = createTLI(TargetTriple, CodeGenOpts);
+  PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
 
   switch (Inlining) {
   case CodeGenOptions::NoInlining: break;
@@ -339,13 +359,15 @@
   }
 
   // Set up the per-function pass manager.
-  FunctionPassManager *FPM = getPerFunctionPasses();
+  legacy::FunctionPassManager *FPM = getPerFunctionPasses();
   if (CodeGenOpts.VerifyModule)
     FPM->add(createVerifierPass());
   PMBuilder.populateFunctionPassManager(*FPM);
 
   // Set up the per-module pass manager.
-  PassManager *MPM = getPerModulePasses();
+  legacy::PassManager *MPM = getPerModulePasses();
+  if (!CodeGenOpts.RewriteMapFiles.empty())
+    addSymbolRewriterPass(CodeGenOpts, MPM);
   if (CodeGenOpts.VerifyModule)
     MPM->add(createDebugInfoVerifierPass());
 
@@ -366,6 +388,12 @@
       MPM->add(createStripSymbolsPass(true));
   }
 
+  if (CodeGenOpts.ProfileInstrGenerate) {
+    InstrProfOptions Options;
+    Options.NoRedZone = CodeGenOpts.DisableRedZone;
+    MPM->add(createInstrProfilingPass(Options));
+  }
+
   PMBuilder.populateModulePassManager(*MPM);
 }
 
@@ -412,7 +440,7 @@
                                     BackendArgs.data());
 
   std::string FeaturesStr;
-  if (TargetOpts.Features.size()) {
+  if (!TargetOpts.Features.empty()) {
     SubtargetFeatures Features;
     for (std::vector<std::string>::const_iterator
            it = TargetOpts.Features.begin(),
@@ -499,6 +527,7 @@
   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
   Options.FunctionSections = CodeGenOpts.FunctionSections;
   Options.DataSections = CodeGenOpts.DataSections;
+  Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
 
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
@@ -506,6 +535,7 @@
   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
+  Options.MCOptions.ABIName = TargetOpts.ABI;
 
   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
                                                      FeaturesStr, Options,
@@ -518,14 +548,13 @@
                                        formatted_raw_ostream &OS) {
 
   // Create the code generator passes.
-  PassManager *PM = getCodeGenPasses();
+  legacy::PassManager *PM = getCodeGenPasses();
 
   // Add LibraryInfo.
   llvm::Triple TargetTriple(TheModule->getTargetTriple());
-  PM->add(createTLI(TargetTriple, CodeGenOpts));
-
-  // Add Target specific analysis passes.
-  TM->addAnalysisPasses(*PM);
+  std::unique_ptr<TargetLibraryInfoImpl> TLII(
+      createTLII(TargetTriple, CodeGenOpts));
+  PM->add(new TargetLibraryInfoWrapperPass(*TLII));
 
   // Normal mode, emit a .s or .o file by running the code generator. Note,
   // this also adds codegenerator level optimization passes.
@@ -626,9 +655,8 @@
   // If an optional clang TargetInfo description string was passed in, use it to
   // verify the LLVM TargetMachine's DataLayout.
   if (AsmHelper.TM && !TDesc.empty()) {
-    std::string DLDesc = AsmHelper.TM->getSubtargetImpl()
-                             ->getDataLayout()
-                             ->getStringRepresentation();
+    std::string DLDesc =
+        AsmHelper.TM->getDataLayout()->getStringRepresentation();
     if (DLDesc != TDesc) {
       unsigned DiagID = Diags.getCustomDiagID(
           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
diff --git a/lib/CodeGen/CGAtomic.cpp b/lib/CodeGen/CGAtomic.cpp
index f4d90a6..2af2264 100644
--- a/lib/CodeGen/CGAtomic.cpp
+++ b/lib/CodeGen/CGAtomic.cpp
@@ -13,6 +13,7 @@
 
 #include "CodeGenFunction.h"
 #include "CGCall.h"
+#include "CGRecordLayout.h"
 #include "CodeGenModule.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
@@ -36,37 +37,72 @@
     CharUnits LValueAlign;
     TypeEvaluationKind EvaluationKind;
     bool UseLibcall;
+    LValue LVal;
+    CGBitFieldInfo BFI;
   public:
-    AtomicInfo(CodeGenFunction &CGF, LValue &lvalue) : CGF(CGF) {
-      assert(lvalue.isSimple());
-
-      AtomicTy = lvalue.getType();
-      ValueTy = AtomicTy->castAs<AtomicType>()->getValueType();
-      EvaluationKind = CGF.getEvaluationKind(ValueTy);
-
+    AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
+        : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
+          EvaluationKind(TEK_Scalar), UseLibcall(true) {
+      assert(!lvalue.isGlobalReg());
       ASTContext &C = CGF.getContext();
+      if (lvalue.isSimple()) {
+        AtomicTy = lvalue.getType();
+        if (auto *ATy = AtomicTy->getAs<AtomicType>())
+          ValueTy = ATy->getValueType();
+        else
+          ValueTy = AtomicTy;
+        EvaluationKind = CGF.getEvaluationKind(ValueTy);
 
-      uint64_t ValueAlignInBits;
-      uint64_t AtomicAlignInBits;
-      TypeInfo ValueTI = C.getTypeInfo(ValueTy);
-      ValueSizeInBits = ValueTI.Width;
-      ValueAlignInBits = ValueTI.Align;
+        uint64_t ValueAlignInBits;
+        uint64_t AtomicAlignInBits;
+        TypeInfo ValueTI = C.getTypeInfo(ValueTy);
+        ValueSizeInBits = ValueTI.Width;
+        ValueAlignInBits = ValueTI.Align;
 
-      TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
-      AtomicSizeInBits = AtomicTI.Width;
-      AtomicAlignInBits = AtomicTI.Align;
+        TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
+        AtomicSizeInBits = AtomicTI.Width;
+        AtomicAlignInBits = AtomicTI.Align;
 
-      assert(ValueSizeInBits <= AtomicSizeInBits);
-      assert(ValueAlignInBits <= AtomicAlignInBits);
+        assert(ValueSizeInBits <= AtomicSizeInBits);
+        assert(ValueAlignInBits <= AtomicAlignInBits);
 
-      AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
-      ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
-      if (lvalue.getAlignment().isZero())
-        lvalue.setAlignment(AtomicAlign);
+        AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
+        ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
+        if (lvalue.getAlignment().isZero())
+          lvalue.setAlignment(AtomicAlign);
 
-      UseLibcall =
-        (AtomicSizeInBits > uint64_t(C.toBits(lvalue.getAlignment())) ||
-         AtomicSizeInBits > C.getTargetInfo().getMaxAtomicInlineWidth());
+        LVal = lvalue;
+      } else if (lvalue.isBitField()) {
+        auto &OrigBFI = lvalue.getBitFieldInfo();
+        auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
+        AtomicSizeInBits = C.toBits(
+            C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
+                .RoundUpToAlignment(lvalue.getAlignment()));
+        auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldAddr());
+        auto OffsetInChars =
+            (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
+            lvalue.getAlignment();
+        VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
+            VoidPtrAddr, OffsetInChars.getQuantity());
+        auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
+            VoidPtrAddr,
+            CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
+            "atomic_bitfield_base");
+        BFI = OrigBFI;
+        BFI.Offset = Offset;
+        BFI.StorageSize = AtomicSizeInBits;
+        LVal = LValue::MakeBitfield(Addr, BFI, lvalue.getType(),
+                                    lvalue.getAlignment());
+      } else if (lvalue.isVectorElt()) {
+        AtomicSizeInBits = C.getTypeSize(lvalue.getType());
+        LVal = lvalue;
+      } else {
+        assert(lvalue.isExtVectorElt());
+        AtomicSizeInBits = C.getTypeSize(lvalue.getType());
+        LVal = lvalue;
+      }
+      UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
+          AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
     }
 
     QualType getAtomicType() const { return AtomicTy; }
@@ -74,9 +110,10 @@
     CharUnits getAtomicAlignment() const { return AtomicAlign; }
     CharUnits getValueAlignment() const { return ValueAlign; }
     uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
-    uint64_t getValueSizeInBits() const { return AtomicSizeInBits; }
+    uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
     TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
     bool shouldUseLibcall() const { return UseLibcall; }
+    const LValue &getAtomicLValue() const { return LVal; }
 
     /// Is the atomic size larger than the underlying value type?
     ///
@@ -88,7 +125,7 @@
       return (ValueSizeInBits != AtomicSizeInBits);
     }
 
-    bool emitMemSetZeroIfNecessary(LValue dest) const;
+    bool emitMemSetZeroIfNecessary() const;
 
     llvm::Value *getAtomicSizeValue() const {
       CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
@@ -104,17 +141,24 @@
                                AggValueSlot resultSlot,
                                SourceLocation loc) const;
 
+    /// \brief Converts a rvalue to integer value.
+    llvm::Value *convertRValueToInt(RValue RVal) const;
+
+    RValue convertIntToValue(llvm::Value *IntVal, AggValueSlot ResultSlot,
+                             SourceLocation Loc) const;
+
     /// Copy an atomic r-value into atomic-layout memory.
-    void emitCopyIntoMemory(RValue rvalue, LValue lvalue) const;
+    void emitCopyIntoMemory(RValue rvalue) const;
 
     /// Project an l-value down to the value field.
-    LValue projectValue(LValue lvalue) const {
-      llvm::Value *addr = lvalue.getAddress();
+    LValue projectValue() const {
+      assert(LVal.isSimple());
+      llvm::Value *addr = LVal.getAddress();
       if (hasPadding())
         addr = CGF.Builder.CreateStructGEP(addr, 0);
 
-      return LValue::MakeAddr(addr, getValueType(), lvalue.getAlignment(),
-                              CGF.getContext(), lvalue.getTBAAInfo());
+      return LValue::MakeAddr(addr, getValueType(), LVal.getAlignment(),
+                              CGF.getContext(), LVal.getTBAAInfo());
     }
 
     /// Materialize an atomic r-value in atomic-layout memory.
@@ -167,14 +211,15 @@
   llvm_unreachable("bad evaluation kind");
 }
 
-bool AtomicInfo::emitMemSetZeroIfNecessary(LValue dest) const {
-  llvm::Value *addr = dest.getAddress();
+bool AtomicInfo::emitMemSetZeroIfNecessary() const {
+  assert(LVal.isSimple());
+  llvm::Value *addr = LVal.getAddress();
   if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
     return false;
 
   CGF.Builder.CreateMemSet(addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
                            AtomicSizeInBits / 8,
-                           dest.getAlignment().getQuantity());
+                           LVal.getAlignment().getQuantity());
   return true;
 }
 
@@ -588,8 +633,14 @@
     break;
   }
 
-  if (!E->getType()->isVoidType() && !Dest)
-    Dest = CreateMemTemp(E->getType(), ".atomicdst");
+  QualType RValTy = E->getType().getUnqualifiedType();
+
+  auto GetDest = [&] {
+    if (!RValTy->isVoidType() && !Dest) {
+      Dest = CreateMemTemp(RValTy, ".atomicdst");
+    }
+    return Dest;
+  };
 
   // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
   if (UseLibcall) {
@@ -729,33 +780,30 @@
       } else {
         // Value is returned through parameter before the order.
         RetTy = getContext().VoidTy;
-        Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
-                 getContext().VoidPtrTy);
+        Args.add(RValue::get(EmitCastToVoidPtr(Dest)), getContext().VoidPtrTy);
       }
     }
     // order is always the last parameter
     Args.add(RValue::get(Order),
              getContext().IntTy);
 
-    const CGFunctionInfo &FuncInfo =
-        CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
-            FunctionType::ExtInfo(), RequiredArgs::All);
-    llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
-    llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
-    RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
-    if (!RetTy->isVoidType()) {
-      if (UseOptimizedLibcall) {
-        if (HaveRetTy)
-          return Res;
-        llvm::StoreInst *StoreDest = Builder.CreateStore(
-            Res.getScalarVal(),
-            Builder.CreateBitCast(Dest, FTy->getReturnType()->getPointerTo()));
-        StoreDest->setAlignment(Align);
-      }
-    }
-    if (E->getType()->isVoidType())
+    RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
+    // The value is returned directly from the libcall.
+    if (HaveRetTy && !RetTy->isVoidType())
+      return Res;
+    // The value is returned via an explicit out param.
+    if (RetTy->isVoidType())
       return RValue::get(nullptr);
-    return convertTempToRValue(Dest, E->getType(), E->getExprLoc());
+    // The value is returned directly for optimized libcalls but the caller is
+    // expected an out-param.
+    if (UseOptimizedLibcall) {
+      llvm::Value *ResVal = Res.getScalarVal();
+      llvm::StoreInst *StoreDest = Builder.CreateStore(
+          ResVal,
+          Builder.CreateBitCast(GetDest(), ResVal->getType()->getPointerTo()));
+      StoreDest->setAlignment(Align);
+    }
+    return convertTempToRValue(Dest, RValTy, E->getExprLoc());
   }
 
   bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
@@ -765,13 +813,15 @@
                 E->getOp() == AtomicExpr::AO__atomic_load ||
                 E->getOp() == AtomicExpr::AO__atomic_load_n;
 
-  llvm::Type *IPtrTy =
-      llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
-  llvm::Value *OrigDest = Dest;
-  Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
-  if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
-  if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
-  if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
+  llvm::Type *ITy =
+      llvm::IntegerType::get(getLLVMContext(), Size * 8);
+  llvm::Value *OrigDest = GetDest();
+  Ptr = Builder.CreateBitCast(
+      Ptr, ITy->getPointerTo(Ptr->getType()->getPointerAddressSpace()));
+  if (Val1) Val1 = Builder.CreateBitCast(Val1, ITy->getPointerTo());
+  if (Val2) Val2 = Builder.CreateBitCast(Val2, ITy->getPointerTo());
+  if (Dest && !E->isCmpXChg())
+    Dest = Builder.CreateBitCast(Dest, ITy->getPointerTo());
 
   if (isa<llvm::ConstantInt>(Order)) {
     int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
@@ -808,9 +858,9 @@
       // enforce that in general.
       break;
     }
-    if (E->getType()->isVoidType())
+    if (RValTy->isVoidType())
       return RValue::get(nullptr);
-    return convertTempToRValue(OrigDest, E->getType(), E->getExprLoc());
+    return convertTempToRValue(OrigDest, RValTy, E->getExprLoc());
   }
 
   // Long case, when Order isn't obviously constant.
@@ -876,9 +926,9 @@
 
   // Cleanup and return
   Builder.SetInsertPoint(ContBB);
-  if (E->getType()->isVoidType())
+  if (RValTy->isVoidType())
     return RValue::get(nullptr);
-  return convertTempToRValue(OrigDest, E->getType(), E->getExprLoc());
+  return convertTempToRValue(OrigDest, RValTy, E->getExprLoc());
 }
 
 llvm::Value *AtomicInfo::emitCastToAtomicIntPointer(llvm::Value *addr) const {
@@ -892,42 +942,148 @@
 RValue AtomicInfo::convertTempToRValue(llvm::Value *addr,
                                        AggValueSlot resultSlot,
                                        SourceLocation loc) const {
-  if (EvaluationKind == TEK_Aggregate)
-    return resultSlot.asRValue();
+  if (LVal.isSimple()) {
+    if (EvaluationKind == TEK_Aggregate)
+      return resultSlot.asRValue();
 
-  // Drill into the padding structure if we have one.
-  if (hasPadding())
-    addr = CGF.Builder.CreateStructGEP(addr, 0);
+    // Drill into the padding structure if we have one.
+    if (hasPadding())
+      addr = CGF.Builder.CreateStructGEP(addr, 0);
 
-  // Otherwise, just convert the temporary to an r-value using the
-  // normal conversion routine.
-  return CGF.convertTempToRValue(addr, getValueType(), loc);
+    // Otherwise, just convert the temporary to an r-value using the
+    // normal conversion routine.
+    return CGF.convertTempToRValue(addr, getValueType(), loc);
+  } else if (LVal.isBitField())
+    return CGF.EmitLoadOfBitfieldLValue(LValue::MakeBitfield(
+        addr, LVal.getBitFieldInfo(), LVal.getType(), LVal.getAlignment()));
+  else if (LVal.isVectorElt())
+    return CGF.EmitLoadOfLValue(LValue::MakeVectorElt(addr, LVal.getVectorIdx(),
+                                                      LVal.getType(),
+                                                      LVal.getAlignment()),
+                                loc);
+  assert(LVal.isExtVectorElt());
+  return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
+      addr, LVal.getExtVectorElts(), LVal.getType(), LVal.getAlignment()));
+}
+
+RValue AtomicInfo::convertIntToValue(llvm::Value *IntVal,
+                                     AggValueSlot ResultSlot,
+                                     SourceLocation Loc) const {
+  assert(LVal.isSimple());
+  // Try not to in some easy cases.
+  assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
+  if (getEvaluationKind() == TEK_Scalar && !hasPadding()) {
+    auto *ValTy = CGF.ConvertTypeForMem(ValueTy);
+    if (ValTy->isIntegerTy()) {
+      assert(IntVal->getType() == ValTy && "Different integer types.");
+      return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
+    } else if (ValTy->isPointerTy())
+      return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
+    else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
+      return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
+  }
+
+  // Create a temporary.  This needs to be big enough to hold the
+  // atomic integer.
+  llvm::Value *Temp;
+  bool TempIsVolatile = false;
+  CharUnits TempAlignment;
+  if (getEvaluationKind() == TEK_Aggregate) {
+    assert(!ResultSlot.isIgnored());
+    Temp = ResultSlot.getAddr();
+    TempAlignment = getValueAlignment();
+    TempIsVolatile = ResultSlot.isVolatile();
+  } else {
+    Temp = CGF.CreateMemTemp(getAtomicType(), "atomic-temp");
+    TempAlignment = getAtomicAlignment();
+  }
+
+  // Slam the integer into the temporary.
+  llvm::Value *CastTemp = emitCastToAtomicIntPointer(Temp);
+  CGF.Builder.CreateAlignedStore(IntVal, CastTemp, TempAlignment.getQuantity())
+      ->setVolatile(TempIsVolatile);
+
+  return convertTempToRValue(Temp, ResultSlot, Loc);
+}
+
+/// An LValue is a candidate for having its loads and stores be made atomic if
+/// we are operating under /volatile:ms *and* the LValue itself is volatile and
+/// performing such an operation can be performed without a libcall.
+bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
+  AtomicInfo AI(*this, LV);
+  bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
+  // An atomic is inline if we don't need to use a libcall.
+  bool AtomicIsInline = !AI.shouldUseLibcall();
+  return CGM.getCodeGenOpts().MSVolatile && IsVolatile && AtomicIsInline;
+}
+
+/// An type is a candidate for having its loads and stores be made atomic if
+/// we are operating under /volatile:ms *and* we know the access is volatile and
+/// performing such an operation can be performed without a libcall.
+bool CodeGenFunction::typeIsSuitableForInlineAtomic(QualType Ty,
+                                                    bool IsVolatile) const {
+  // An atomic is inline if we don't need to use a libcall (e.g. it is builtin).
+  bool AtomicIsInline = getContext().getTargetInfo().hasBuiltinAtomic(
+      getContext().getTypeSize(Ty), getContext().getTypeAlign(Ty));
+  return CGM.getCodeGenOpts().MSVolatile && IsVolatile && AtomicIsInline;
+}
+
+RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
+                                       AggValueSlot Slot) {
+  llvm::AtomicOrdering AO;
+  bool IsVolatile = LV.isVolatileQualified();
+  if (LV.getType()->isAtomicType()) {
+    AO = llvm::SequentiallyConsistent;
+  } else {
+    AO = llvm::Acquire;
+    IsVolatile = true;
+  }
+  return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
 }
 
 /// Emit a load from an l-value of atomic type.  Note that the r-value
 /// we produce is an r-value of the atomic *value* type.
 RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
+                                       llvm::AtomicOrdering AO, bool IsVolatile,
                                        AggValueSlot resultSlot) {
   AtomicInfo atomics(*this, src);
+  LValue LVal = atomics.getAtomicLValue();
+  llvm::Value *SrcAddr = nullptr;
+  llvm::AllocaInst *NonSimpleTempAlloca = nullptr;
+  if (LVal.isSimple())
+    SrcAddr = LVal.getAddress();
+  else {
+    if (LVal.isBitField())
+      SrcAddr = LVal.getBitFieldAddr();
+    else if (LVal.isVectorElt())
+      SrcAddr = LVal.getVectorAddr();
+    else {
+      assert(LVal.isExtVectorElt());
+      SrcAddr = LVal.getExtVectorAddr();
+    }
+    NonSimpleTempAlloca = CreateTempAlloca(
+        SrcAddr->getType()->getPointerElementType(), "atomic-load-temp");
+    NonSimpleTempAlloca->setAlignment(getContext().toBits(src.getAlignment()));
+  }
 
   // Check whether we should use a library call.
   if (atomics.shouldUseLibcall()) {
     llvm::Value *tempAddr;
-    if (!resultSlot.isIgnored()) {
-      assert(atomics.getEvaluationKind() == TEK_Aggregate);
-      tempAddr = resultSlot.getAddr();
-    } else {
-      tempAddr = CreateMemTemp(atomics.getAtomicType(), "atomic-load-temp");
-    }
+    if (LVal.isSimple()) {
+      if (!resultSlot.isIgnored()) {
+        assert(atomics.getEvaluationKind() == TEK_Aggregate);
+        tempAddr = resultSlot.getAddr();
+      } else
+        tempAddr = CreateMemTemp(atomics.getAtomicType(), "atomic-load-temp");
+    } else
+      tempAddr = NonSimpleTempAlloca;
 
     // void __atomic_load(size_t size, void *mem, void *return, int order);
     CallArgList args;
     args.add(RValue::get(atomics.getAtomicSizeValue()),
              getContext().getSizeType());
-    args.add(RValue::get(EmitCastToVoidPtr(src.getAddress())),
-             getContext().VoidPtrTy);
-    args.add(RValue::get(EmitCastToVoidPtr(tempAddr)),
-             getContext().VoidPtrTy);
+    args.add(RValue::get(EmitCastToVoidPtr(SrcAddr)), getContext().VoidPtrTy);
+    args.add(RValue::get(EmitCastToVoidPtr(tempAddr)), getContext().VoidPtrTy);
     args.add(RValue::get(llvm::ConstantInt::get(
                  IntTy, AtomicExpr::AO_ABI_memory_order_seq_cst)),
              getContext().IntTy);
@@ -938,94 +1094,62 @@
   }
 
   // Okay, we're doing this natively.
-  llvm::Value *addr = atomics.emitCastToAtomicIntPointer(src.getAddress());
+  llvm::Value *addr = atomics.emitCastToAtomicIntPointer(SrcAddr);
   llvm::LoadInst *load = Builder.CreateLoad(addr, "atomic-load");
-  load->setAtomic(llvm::SequentiallyConsistent);
+  load->setAtomic(AO);
 
   // Other decoration.
   load->setAlignment(src.getAlignment().getQuantity());
-  if (src.isVolatileQualified())
+  if (IsVolatile)
     load->setVolatile(true);
   if (src.getTBAAInfo())
     CGM.DecorateInstruction(load, src.getTBAAInfo());
 
-  // Okay, turn that back into the original value type.
-  QualType valueType = atomics.getValueType();
-  llvm::Value *result = load;
-
   // If we're ignoring an aggregate return, don't do anything.
   if (atomics.getEvaluationKind() == TEK_Aggregate && resultSlot.isIgnored())
     return RValue::getAggregate(nullptr, false);
 
-  // The easiest way to do this this is to go through memory, but we
-  // try not to in some easy cases.
-  if (atomics.getEvaluationKind() == TEK_Scalar && !atomics.hasPadding()) {
-    llvm::Type *resultTy = CGM.getTypes().ConvertTypeForMem(valueType);
-    if (isa<llvm::IntegerType>(resultTy)) {
-      assert(result->getType() == resultTy);
-      result = EmitFromMemory(result, valueType);
-    } else if (isa<llvm::PointerType>(resultTy)) {
-      result = Builder.CreateIntToPtr(result, resultTy);
-    } else {
-      result = Builder.CreateBitCast(result, resultTy);
-    }
-    return RValue::get(result);
-  }
+  // Okay, turn that back into the original value type.
+  if (src.isSimple())
+    return atomics.convertIntToValue(load, resultSlot, loc);
 
-  // Create a temporary.  This needs to be big enough to hold the
-  // atomic integer.
-  llvm::Value *temp;
-  bool tempIsVolatile = false;
-  CharUnits tempAlignment;
-  if (atomics.getEvaluationKind() == TEK_Aggregate) {
-    assert(!resultSlot.isIgnored());
-    temp = resultSlot.getAddr();
-    tempAlignment = atomics.getValueAlignment();
-    tempIsVolatile = resultSlot.isVolatile();
-  } else {
-    temp = CreateMemTemp(atomics.getAtomicType(), "atomic-load-temp");
-    tempAlignment = atomics.getAtomicAlignment();
-  }
-
-  // Slam the integer into the temporary.
-  llvm::Value *castTemp = atomics.emitCastToAtomicIntPointer(temp);
-  Builder.CreateAlignedStore(result, castTemp, tempAlignment.getQuantity())
-    ->setVolatile(tempIsVolatile);
-
-  return atomics.convertTempToRValue(temp, resultSlot, loc);
+  auto *IntAddr = atomics.emitCastToAtomicIntPointer(NonSimpleTempAlloca);
+  Builder.CreateAlignedStore(load, IntAddr, src.getAlignment().getQuantity());
+  return atomics.convertTempToRValue(NonSimpleTempAlloca, resultSlot, loc);
 }
 
 
 
 /// Copy an r-value into memory as part of storing to an atomic type.
 /// This needs to create a bit-pattern suitable for atomic operations.
-void AtomicInfo::emitCopyIntoMemory(RValue rvalue, LValue dest) const {
+void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
+  assert(LVal.isSimple());
   // If we have an r-value, the rvalue should be of the atomic type,
   // which means that the caller is responsible for having zeroed
   // any padding.  Just do an aggregate copy of that type.
   if (rvalue.isAggregate()) {
-    CGF.EmitAggregateCopy(dest.getAddress(),
+    CGF.EmitAggregateCopy(LVal.getAddress(),
                           rvalue.getAggregateAddr(),
                           getAtomicType(),
                           (rvalue.isVolatileQualified()
-                           || dest.isVolatileQualified()),
-                          dest.getAlignment());
+                           || LVal.isVolatileQualified()),
+                          LVal.getAlignment());
     return;
   }
 
   // Okay, otherwise we're copying stuff.
 
   // Zero out the buffer if necessary.
-  emitMemSetZeroIfNecessary(dest);
+  emitMemSetZeroIfNecessary();
 
   // Drill past the padding if present.
-  dest = projectValue(dest);
+  LValue TempLVal = projectValue();
 
   // Okay, store the rvalue in.
   if (rvalue.isScalar()) {
-    CGF.EmitStoreOfScalar(rvalue.getScalarVal(), dest, /*init*/ true);
+    CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
   } else {
-    CGF.EmitStoreOfComplex(rvalue.getComplexVal(), dest, /*init*/ true);
+    CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
   }
 }
 
@@ -1040,17 +1164,60 @@
 
   // Otherwise, make a temporary and materialize into it.
   llvm::Value *temp = CGF.CreateMemTemp(getAtomicType(), "atomic-store-temp");
-  LValue tempLV = CGF.MakeAddrLValue(temp, getAtomicType(), getAtomicAlignment());
-  emitCopyIntoMemory(rvalue, tempLV);
+  LValue tempLV =
+      CGF.MakeAddrLValue(temp, getAtomicType(), getAtomicAlignment());
+  AtomicInfo Atomics(CGF, tempLV);
+  Atomics.emitCopyIntoMemory(rvalue);
   return temp;
 }
 
+llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
+  // If we've got a scalar value of the right size, try to avoid going
+  // through memory.
+  if (RVal.isScalar() && !hasPadding()) {
+    llvm::Value *Value = RVal.getScalarVal();
+    if (isa<llvm::IntegerType>(Value->getType()))
+      return Value;
+    else {
+      llvm::IntegerType *InputIntTy =
+          llvm::IntegerType::get(CGF.getLLVMContext(), getValueSizeInBits());
+      if (isa<llvm::PointerType>(Value->getType()))
+        return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
+      else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
+        return CGF.Builder.CreateBitCast(Value, InputIntTy);
+    }
+  }
+  // Otherwise, we need to go through memory.
+  // Put the r-value in memory.
+  llvm::Value *Addr = materializeRValue(RVal);
+
+  // Cast the temporary to the atomic int type and pull a value out.
+  Addr = emitCastToAtomicIntPointer(Addr);
+  return CGF.Builder.CreateAlignedLoad(Addr,
+                                       getAtomicAlignment().getQuantity());
+}
+
+void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
+                                      bool isInit) {
+  bool IsVolatile = lvalue.isVolatileQualified();
+  llvm::AtomicOrdering AO;
+  if (lvalue.getType()->isAtomicType()) {
+    AO = llvm::SequentiallyConsistent;
+  } else {
+    AO = llvm::Release;
+    IsVolatile = true;
+  }
+  return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
+}
+
 /// Emit a store to an l-value of atomic type.
 ///
 /// Note that the r-value is expected to be an r-value *of the atomic
 /// type*; this means that for aggregate r-values, it should include
 /// storage for any padding that was necessary.
-void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest, bool isInit) {
+void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
+                                      llvm::AtomicOrdering AO, bool IsVolatile,
+                                      bool isInit) {
   // If this is an aggregate r-value, it should agree in type except
   // maybe for address-space qualification.
   assert(!rvalue.isAggregate() ||
@@ -1061,7 +1228,7 @@
 
   // If this is an initialization, just put the value there normally.
   if (isInit) {
-    atomics.emitCopyIntoMemory(rvalue, dest);
+    atomics.emitCopyIntoMemory(rvalue);
     return;
   }
 
@@ -1086,63 +1253,104 @@
   }
 
   // Okay, we're doing this natively.
-  llvm::Value *intValue;
-
-  // If we've got a scalar value of the right size, try to avoid going
-  // through memory.
-  if (rvalue.isScalar() && !atomics.hasPadding()) {
-    llvm::Value *value = rvalue.getScalarVal();
-    if (isa<llvm::IntegerType>(value->getType())) {
-      intValue = value;
-    } else {
-      llvm::IntegerType *inputIntTy =
-        llvm::IntegerType::get(getLLVMContext(), atomics.getValueSizeInBits());
-      if (isa<llvm::PointerType>(value->getType())) {
-        intValue = Builder.CreatePtrToInt(value, inputIntTy);
-      } else {
-        intValue = Builder.CreateBitCast(value, inputIntTy);
-      }
-    }
-
-  // Otherwise, we need to go through memory.
-  } else {
-    // Put the r-value in memory.
-    llvm::Value *addr = atomics.materializeRValue(rvalue);
-
-    // Cast the temporary to the atomic int type and pull a value out.
-    addr = atomics.emitCastToAtomicIntPointer(addr);
-    intValue = Builder.CreateAlignedLoad(addr,
-                                 atomics.getAtomicAlignment().getQuantity());
-  }
+  llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
 
   // Do the atomic store.
   llvm::Value *addr = atomics.emitCastToAtomicIntPointer(dest.getAddress());
   llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
 
   // Initializations don't need to be atomic.
-  if (!isInit) store->setAtomic(llvm::SequentiallyConsistent);
+  if (!isInit) store->setAtomic(AO);
 
   // Other decoration.
   store->setAlignment(dest.getAlignment().getQuantity());
-  if (dest.isVolatileQualified())
+  if (IsVolatile)
     store->setVolatile(true);
   if (dest.getTBAAInfo())
     CGM.DecorateInstruction(store, dest.getTBAAInfo());
 }
 
+/// Emit a compare-and-exchange op for atomic type.
+///
+std::pair<RValue, RValue> CodeGenFunction::EmitAtomicCompareExchange(
+    LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
+    llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
+    AggValueSlot Slot) {
+  // If this is an aggregate r-value, it should agree in type except
+  // maybe for address-space qualification.
+  assert(!Expected.isAggregate() ||
+         Expected.getAggregateAddr()->getType()->getPointerElementType() ==
+             Obj.getAddress()->getType()->getPointerElementType());
+  assert(!Desired.isAggregate() ||
+         Desired.getAggregateAddr()->getType()->getPointerElementType() ==
+             Obj.getAddress()->getType()->getPointerElementType());
+  AtomicInfo Atomics(*this, Obj);
+
+  if (Failure >= Success)
+    // Don't assert on undefined behavior.
+    Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
+
+  auto Alignment = Atomics.getValueAlignment();
+  // Check whether we should use a library call.
+  if (Atomics.shouldUseLibcall()) {
+    auto *ExpectedAddr = Atomics.materializeRValue(Expected);
+    // Produce a source address.
+    auto *DesiredAddr = Atomics.materializeRValue(Desired);
+    // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
+    // void *desired, int success, int failure);
+    CallArgList Args;
+    Args.add(RValue::get(Atomics.getAtomicSizeValue()),
+             getContext().getSizeType());
+    Args.add(RValue::get(EmitCastToVoidPtr(Obj.getAddress())),
+             getContext().VoidPtrTy);
+    Args.add(RValue::get(EmitCastToVoidPtr(ExpectedAddr)),
+             getContext().VoidPtrTy);
+    Args.add(RValue::get(EmitCastToVoidPtr(DesiredAddr)),
+             getContext().VoidPtrTy);
+    Args.add(RValue::get(llvm::ConstantInt::get(IntTy, Success)),
+             getContext().IntTy);
+    Args.add(RValue::get(llvm::ConstantInt::get(IntTy, Failure)),
+             getContext().IntTy);
+    auto SuccessFailureRVal = emitAtomicLibcall(
+        *this, "__atomic_compare_exchange", getContext().BoolTy, Args);
+    auto *PreviousVal =
+        Builder.CreateAlignedLoad(ExpectedAddr, Alignment.getQuantity());
+    return std::make_pair(RValue::get(PreviousVal), SuccessFailureRVal);
+  }
+
+  // If we've got a scalar value of the right size, try to avoid going
+  // through memory.
+  auto *ExpectedIntVal = Atomics.convertRValueToInt(Expected);
+  auto *DesiredIntVal = Atomics.convertRValueToInt(Desired);
+
+  // Do the atomic store.
+  auto *Addr = Atomics.emitCastToAtomicIntPointer(Obj.getAddress());
+  auto *Inst = Builder.CreateAtomicCmpXchg(Addr, ExpectedIntVal, DesiredIntVal,
+                                          Success, Failure);
+  // Other decoration.
+  Inst->setVolatile(Obj.isVolatileQualified());
+  Inst->setWeak(IsWeak);
+
+  // Okay, turn that back into the original value type.
+  auto *PreviousVal = Builder.CreateExtractValue(Inst, /*Idxs=*/0);
+  auto *SuccessFailureVal = Builder.CreateExtractValue(Inst, /*Idxs=*/1);
+  return std::make_pair(Atomics.convertIntToValue(PreviousVal, Slot, Loc),
+                        RValue::get(SuccessFailureVal));
+}
+
 void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
   AtomicInfo atomics(*this, dest);
 
   switch (atomics.getEvaluationKind()) {
   case TEK_Scalar: {
     llvm::Value *value = EmitScalarExpr(init);
-    atomics.emitCopyIntoMemory(RValue::get(value), dest);
+    atomics.emitCopyIntoMemory(RValue::get(value));
     return;
   }
 
   case TEK_Complex: {
     ComplexPairTy value = EmitComplexExpr(init);
-    atomics.emitCopyIntoMemory(RValue::getComplex(value), dest);
+    atomics.emitCopyIntoMemory(RValue::getComplex(value));
     return;
   }
 
@@ -1151,8 +1359,8 @@
     // of atomic type.
     bool Zeroed = false;
     if (!init->getType()->isAtomicType()) {
-      Zeroed = atomics.emitMemSetZeroIfNecessary(dest);
-      dest = atomics.projectValue(dest);
+      Zeroed = atomics.emitMemSetZeroIfNecessary();
+      dest = atomics.projectValue();
     }
 
     // Evaluate the expression directly into the destination.
diff --git a/lib/CodeGen/CGBlocks.cpp b/lib/CodeGen/CGBlocks.cpp
index f088cd6..7b8e839 100644
--- a/lib/CodeGen/CGBlocks.cpp
+++ b/lib/CodeGen/CGBlocks.cpp
@@ -792,9 +792,10 @@
       // emission.
       src = LocalDeclMap.lookup(variable);
       if (!src) {
-        DeclRefExpr declRef(const_cast<VarDecl *>(variable),
-                            /*refersToEnclosing*/ CI.isNested(), type,
-                            VK_LValue, SourceLocation());
+        DeclRefExpr declRef(
+            const_cast<VarDecl *>(variable),
+            /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
+            VK_LValue, SourceLocation());
         src = EmitDeclRefLValue(&declRef).getAddress();
       }
     }
@@ -863,12 +864,15 @@
 
       // We use one of these or the other depending on whether the
       // reference is nested.
-      DeclRefExpr declRef(const_cast<VarDecl*>(variable),
-                          /*refersToEnclosing*/ CI.isNested(), type,
-                          VK_LValue, SourceLocation());
+      DeclRefExpr declRef(const_cast<VarDecl *>(variable),
+                          /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
+                          type, VK_LValue, SourceLocation());
 
       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
                            &declRef, VK_RValue);
+      // FIXME: Pass a specific location for the expr init so that the store is
+      // attributed to a reasonable location - otherwise it may be attributed to
+      // locations of subexpressions in the initialization.
       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
                      MakeAddrLValue(blockField, type, align),
                      /*captured by init*/ false);
@@ -915,7 +919,7 @@
   // };
   BlockDescriptorType =
     llvm::StructType::create("struct.__block_descriptor",
-                             UnsignedLongTy, UnsignedLongTy, NULL);
+                             UnsignedLongTy, UnsignedLongTy, nullptr);
 
   // Now form a pointer to that.
   BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
@@ -938,7 +942,7 @@
   GenericBlockLiteralType =
     llvm::StructType::create("struct.__block_literal_generic",
                              VoidPtrTy, IntTy, IntTy, VoidPtrTy,
-                             BlockDescPtrTy, NULL);
+                             BlockDescPtrTy, nullptr);
 
   return GenericBlockLiteralType;
 }
@@ -1103,6 +1107,8 @@
   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
 
   CurGD = GD;
+
+  CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
   
   BlockInfo = &blockInfo;
 
@@ -1130,8 +1136,7 @@
   args.push_back(&selfDecl);
 
   // Now add the rest of the parameters.
-  for (auto i : blockDecl->params())
-    args.push_back(i);
+  args.append(blockDecl->param_begin(), blockDecl->param_end());
 
   // Create the function declaration.
   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
@@ -1172,7 +1177,7 @@
     Alloca->setAlignment(Align);
     // Set the DebugLocation to empty, so the store is recognized as a
     // frame setup instruction by llvm::DwarfDebug::beginFunction().
-    NoLocation NL(*this, Builder);
+    auto NL = ApplyDebugLocation::CreateEmpty(*this);
     Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
     BlockPointerDbgLoc = Alloca;
   }
@@ -1215,8 +1220,6 @@
     RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
     Cnt.beginRegion(Builder);
     EmitStmt(blockDecl->getBody());
-    PGO.emitInstrumentationData();
-    PGO.destroyRegionCounters();
   }
 
   // Remember where we were...
@@ -1324,11 +1327,10 @@
                                           nullptr, SC_Static,
                                           false,
                                           false);
-  // Create a scope with an artificial location for the body of this function.
-  ArtificialLocation AL(*this, Builder);
+  auto NL = ApplyDebugLocation::CreateEmpty(*this);
   StartFunction(FD, C.VoidTy, Fn, FI, args);
-  AL.Emit();
-
+  // Create a scope with an artificial location for the body of this function.
+  auto AL = ApplyDebugLocation::CreateArtificial(*this);
   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
 
   llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
@@ -1496,9 +1498,9 @@
                                           nullptr, SC_Static,
                                           false, false);
   // Create a scope with an artificial location for the body of this function.
-  ArtificialLocation AL(*this, Builder);
+  auto NL = ApplyDebugLocation::CreateEmpty(*this);
   StartFunction(FD, C.VoidTy, Fn, FI, args);
-  AL.Emit();
+  auto AL = ApplyDebugLocation::CreateArtificial(*this);
 
   llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
 
diff --git a/lib/CodeGen/CGBuilder.h b/lib/CodeGen/CGBuilder.h
index 72ba4fa..6610659 100644
--- a/lib/CodeGen/CGBuilder.h
+++ b/lib/CodeGen/CGBuilder.h
@@ -33,7 +33,7 @@
                     llvm::BasicBlock *BB,
                     llvm::BasicBlock::iterator InsertPt) const;
 private:
-  void operator=(const CGBuilderInserter &) LLVM_DELETED_FUNCTION;
+  void operator=(const CGBuilderInserter &) = delete;
 
   CodeGenFunction *CGF;
 };
diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp
index 494e1ef..bf7d86f 100644
--- a/lib/CodeGen/CGBuiltin.cpp
+++ b/lib/CodeGen/CGBuiltin.cpp
@@ -20,7 +20,10 @@
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/IR/CallSite.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
 
 using namespace clang;
@@ -185,7 +188,8 @@
 }
 
 RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD,
-                                        unsigned BuiltinID, const CallExpr *E) {
+                                        unsigned BuiltinID, const CallExpr *E,
+                                        ReturnValueSlot ReturnValue) {
   // See if we can constant fold this builtin.  If so, don't emit it at all.
   Expr::EvalResult Result;
   if (E->EvaluateAsRValue(Result, CGM.getContext()) &&
@@ -386,9 +390,14 @@
     Value *ArgValue = EmitScalarExpr(E->getArg(0));
     llvm::Type *ArgType = ArgValue->getType();
 
-    Value *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
     Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
+    // Don't generate llvm.expect on -O0 as the backend won't use it for
+    // anything.
+    // Note, we still IRGen ExpectedValue because it could have side-effects.
+    if (CGM.getCodeGenOpts().OptimizationLevel == 0)
+      return RValue::get(ArgValue);
 
+    Value *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
     Value *Result = Builder.CreateCall2(FnExpect, ArgValue, ExpectedValue,
                                         "expval");
     return RValue::get(Result);
@@ -850,6 +859,8 @@
       return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
   }
   case Builtin::BI__builtin_setjmp: {
+    if (!getTargetHooks().hasSjLjLowering(*this))
+      break;
     // Buffer is a void**.
     Value *Buf = EmitScalarExpr(E->getArg(0));
 
@@ -872,6 +883,8 @@
     return RValue::get(Builder.CreateCall(F, Buf));
   }
   case Builtin::BI__builtin_longjmp: {
+    if (!getTargetHooks().hasSjLjLowering(*this))
+      break;
     Value *Buf = EmitScalarExpr(E->getArg(0));
     Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
 
@@ -1354,6 +1367,9 @@
     return RValue::get(Builder.CreateCall(F, Arg0));
   }
 
+  case Builtin::BI__builtin_pow:
+  case Builtin::BI__builtin_powf:
+  case Builtin::BI__builtin_powl:
   case Builtin::BIpow:
   case Builtin::BIpowf:
   case Builtin::BIpowl: {
@@ -1566,6 +1582,13 @@
   case Builtin::BI__noop:
     // __noop always evaluates to an integer literal zero.
     return RValue::get(ConstantInt::get(IntTy, 0));
+  case Builtin::BI__builtin_call_with_static_chain: {
+    const CallExpr *Call = cast<CallExpr>(E->getArg(0));
+    const Expr *Chain = E->getArg(1);
+    return EmitCall(Call->getCallee()->getType(),
+                    EmitScalarExpr(Call->getCallee()), Call, ReturnValue,
+                    Call->getCalleeDecl(), EmitScalarExpr(Chain));
+  }
   case Builtin::BI_InterlockedExchange:
   case Builtin::BI_InterlockedExchangePointer:
     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
@@ -1640,6 +1663,67 @@
         Builder.CreateAlignedLoad(IntToPtr, /*Align=*/4, /*isVolatile=*/true);
     return RValue::get(Load);
   }
+
+  case Builtin::BI__exception_code:
+  case Builtin::BI_exception_code:
+    return RValue::get(EmitSEHExceptionCode());
+  case Builtin::BI__exception_info:
+  case Builtin::BI_exception_info:
+    return RValue::get(EmitSEHExceptionInfo());
+  case Builtin::BI__abnormal_termination:
+  case Builtin::BI_abnormal_termination:
+    return RValue::get(EmitSEHAbnormalTermination());
+  case Builtin::BI_setjmpex: {
+    if (getTarget().getTriple().isOSMSVCRT()) {
+      llvm::Type *ArgTypes[] = {Int8PtrTy, Int8PtrTy};
+      llvm::AttributeSet ReturnsTwiceAttr =
+          AttributeSet::get(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
+                            llvm::Attribute::ReturnsTwice);
+      llvm::Constant *SetJmpEx = CGM.CreateRuntimeFunction(
+          llvm::FunctionType::get(IntTy, ArgTypes, /*isVarArg=*/false),
+          "_setjmpex", ReturnsTwiceAttr);
+      llvm::Value *Buf =
+          Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), Int8PtrTy);
+      llvm::Value *FrameAddr =
+          Builder.CreateCall(CGM.getIntrinsic(Intrinsic::frameaddress),
+                             ConstantInt::get(Int32Ty, 0));
+      llvm::Value *Args[] = {Buf, FrameAddr};
+      llvm::CallSite CS = EmitRuntimeCallOrInvoke(SetJmpEx, Args);
+      CS.setAttributes(ReturnsTwiceAttr);
+      return RValue::get(CS.getInstruction());
+    }
+  }
+  case Builtin::BI_setjmp: {
+    if (getTarget().getTriple().isOSMSVCRT()) {
+      llvm::AttributeSet ReturnsTwiceAttr =
+          AttributeSet::get(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
+                            llvm::Attribute::ReturnsTwice);
+      llvm::Value *Buf =
+          Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), Int8PtrTy);
+      llvm::CallSite CS;
+      if (getTarget().getTriple().getArch() == llvm::Triple::x86) {
+        llvm::Type *ArgTypes[] = {Int8PtrTy, IntTy};
+        llvm::Constant *SetJmp3 = CGM.CreateRuntimeFunction(
+            llvm::FunctionType::get(IntTy, ArgTypes, /*isVarArg=*/true),
+            "_setjmp3", ReturnsTwiceAttr);
+        llvm::Value *Count = ConstantInt::get(IntTy, 0);
+        llvm::Value *Args[] = {Buf, Count};
+        CS = EmitRuntimeCallOrInvoke(SetJmp3, Args);
+      } else {
+        llvm::Type *ArgTypes[] = {Int8PtrTy, Int8PtrTy};
+        llvm::Constant *SetJmp = CGM.CreateRuntimeFunction(
+            llvm::FunctionType::get(IntTy, ArgTypes, /*isVarArg=*/false),
+            "_setjmp", ReturnsTwiceAttr);
+        llvm::Value *FrameAddr =
+            Builder.CreateCall(CGM.getIntrinsic(Intrinsic::frameaddress),
+                               ConstantInt::get(Int32Ty, 0));
+        llvm::Value *Args[] = {Buf, FrameAddr};
+        CS = EmitRuntimeCallOrInvoke(SetJmp, Args);
+      }
+      CS.setAttributes(ReturnsTwiceAttr);
+      return RValue::get(CS.getInstruction());
+    }
+  }
   }
 
   // If this is an alias for a lib function (e.g. __builtin_sin), emit
@@ -1752,6 +1836,7 @@
   case llvm::Triple::ppc64le:
     return EmitPPCBuiltinExpr(BuiltinID, E);
   case llvm::Triple::r600:
+  case llvm::Triple::amdgcn:
     return EmitR600BuiltinExpr(BuiltinID, E);
   default:
     return nullptr;
@@ -2523,7 +2608,7 @@
   // Return type.
   SmallVector<llvm::Type *, 3> Tys;
   if (Modifier & AddRetType) {
-    llvm::Type *Ty = ConvertType(E->getCallReturnType());
+    llvm::Type *Ty = ConvertType(E->getCallReturnType(getContext()));
     if (Modifier & VectorizeRetType)
       Ty = llvm::VectorType::get(
           Ty, VectorSize ? VectorSize / Ty->getPrimitiveSizeInBits() : 1);
@@ -3122,39 +3207,59 @@
   return CGF.EmitNeonCall(TblF, TblOps, Name);
 }
 
-Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
-                                           const CallExpr *E) {
-  unsigned HintID = static_cast<unsigned>(-1);
+Value *CodeGenFunction::GetValueForARMHint(unsigned BuiltinID) {
   switch (BuiltinID) {
-  default: break;
+  default:
+    return nullptr;
   case ARM::BI__builtin_arm_nop:
-    HintID = 0;
-    break;
+    return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
+                              llvm::ConstantInt::get(Int32Ty, 0));
   case ARM::BI__builtin_arm_yield:
   case ARM::BI__yield:
-    HintID = 1;
-    break;
+    return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
+                              llvm::ConstantInt::get(Int32Ty, 1));
   case ARM::BI__builtin_arm_wfe:
   case ARM::BI__wfe:
-    HintID = 2;
-    break;
+    return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
+                              llvm::ConstantInt::get(Int32Ty, 2));
   case ARM::BI__builtin_arm_wfi:
   case ARM::BI__wfi:
-    HintID = 3;
-    break;
+    return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
+                              llvm::ConstantInt::get(Int32Ty, 3));
   case ARM::BI__builtin_arm_sev:
   case ARM::BI__sev:
-    HintID = 4;
-    break;
+    return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
+                              llvm::ConstantInt::get(Int32Ty, 4));
   case ARM::BI__builtin_arm_sevl:
   case ARM::BI__sevl:
-    HintID = 5;
-    break;
+    return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
+                              llvm::ConstantInt::get(Int32Ty, 5));
   }
+}
 
-  if (HintID != static_cast<unsigned>(-1)) {
-    Function *F = CGM.getIntrinsic(Intrinsic::arm_hint);
-    return Builder.CreateCall(F, llvm::ConstantInt::get(Int32Ty, HintID));
+Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
+                                           const CallExpr *E) {
+  if (auto Hint = GetValueForARMHint(BuiltinID))
+    return Hint;
+
+  if (BuiltinID == ARM::BI__emit) {
+    bool IsThumb = getTarget().getTriple().getArch() == llvm::Triple::thumb;
+    llvm::FunctionType *FTy =
+        llvm::FunctionType::get(VoidTy, /*Variadic=*/false);
+
+    APSInt Value;
+    if (!E->getArg(0)->EvaluateAsInt(Value, CGM.getContext()))
+      llvm_unreachable("Sema will ensure that the parameter is constant");
+
+    uint64_t ZExtValue = Value.zextOrTrunc(IsThumb ? 16 : 32).getZExtValue();
+
+    llvm::InlineAsm *Emit =
+        IsThumb ? InlineAsm::get(FTy, ".inst.n 0x" + utohexstr(ZExtValue), "",
+                                 /*SideEffects=*/true)
+                : InlineAsm::get(FTy, ".inst 0x" + utohexstr(ZExtValue), "",
+                                 /*SideEffects=*/true);
+
+    return Builder.CreateCall(Emit);
   }
 
   if (BuiltinID == ARM::BI__builtin_arm_dbg) {
@@ -3257,7 +3362,7 @@
     Function *F = CGM.getIntrinsic(BuiltinID == ARM::BI__builtin_arm_stlex
                                        ? Intrinsic::arm_stlexd
                                        : Intrinsic::arm_strexd);
-    llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty, NULL);
+    llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty, nullptr);
 
     Value *Tmp = CreateMemTemp(E->getArg(0)->getType());
     Value *Val = EmitScalarExpr(E->getArg(0));
@@ -4028,7 +4133,7 @@
     Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_stlex
                                        ? Intrinsic::aarch64_stlxp
                                        : Intrinsic::aarch64_stxp);
-    llvm::Type *STy = llvm::StructType::get(Int64Ty, Int64Ty, NULL);
+    llvm::Type *STy = llvm::StructType::get(Int64Ty, Int64Ty, nullptr);
 
     Value *One = llvm::ConstantInt::get(Int32Ty, 1);
     Value *Tmp = Builder.CreateAlloca(ConvertType(E->getArg(0)->getType()),
@@ -4217,36 +4322,36 @@
   case NEON::BI__builtin_neon_vceqzs_f32:
     Ops.push_back(EmitScalarExpr(E->getArg(0)));
     return EmitAArch64CompareBuiltinExpr(
-        Ops[0], ConvertType(E->getCallReturnType()), ICmpInst::FCMP_OEQ,
-        ICmpInst::ICMP_EQ, "vceqz");
+        Ops[0], ConvertType(E->getCallReturnType(getContext())),
+        ICmpInst::FCMP_OEQ, ICmpInst::ICMP_EQ, "vceqz");
   case NEON::BI__builtin_neon_vcgezd_s64:
   case NEON::BI__builtin_neon_vcgezd_f64:
   case NEON::BI__builtin_neon_vcgezs_f32:
     Ops.push_back(EmitScalarExpr(E->getArg(0)));
     return EmitAArch64CompareBuiltinExpr(
-        Ops[0], ConvertType(E->getCallReturnType()), ICmpInst::FCMP_OGE,
-        ICmpInst::ICMP_SGE, "vcgez");
+        Ops[0], ConvertType(E->getCallReturnType(getContext())),
+        ICmpInst::FCMP_OGE, ICmpInst::ICMP_SGE, "vcgez");
   case NEON::BI__builtin_neon_vclezd_s64:
   case NEON::BI__builtin_neon_vclezd_f64:
   case NEON::BI__builtin_neon_vclezs_f32:
     Ops.push_back(EmitScalarExpr(E->getArg(0)));
     return EmitAArch64CompareBuiltinExpr(
-        Ops[0], ConvertType(E->getCallReturnType()), ICmpInst::FCMP_OLE,
-        ICmpInst::ICMP_SLE, "vclez");
+        Ops[0], ConvertType(E->getCallReturnType(getContext())),
+        ICmpInst::FCMP_OLE, ICmpInst::ICMP_SLE, "vclez");
   case NEON::BI__builtin_neon_vcgtzd_s64:
   case NEON::BI__builtin_neon_vcgtzd_f64:
   case NEON::BI__builtin_neon_vcgtzs_f32:
     Ops.push_back(EmitScalarExpr(E->getArg(0)));
     return EmitAArch64CompareBuiltinExpr(
-        Ops[0], ConvertType(E->getCallReturnType()), ICmpInst::FCMP_OGT,
-        ICmpInst::ICMP_SGT, "vcgtz");
+        Ops[0], ConvertType(E->getCallReturnType(getContext())),
+        ICmpInst::FCMP_OGT, ICmpInst::ICMP_SGT, "vcgtz");
   case NEON::BI__builtin_neon_vcltzd_s64:
   case NEON::BI__builtin_neon_vcltzd_f64:
   case NEON::BI__builtin_neon_vcltzs_f32:
     Ops.push_back(EmitScalarExpr(E->getArg(0)));
     return EmitAArch64CompareBuiltinExpr(
-        Ops[0], ConvertType(E->getCallReturnType()), ICmpInst::FCMP_OLT,
-        ICmpInst::ICMP_SLT, "vcltz");
+        Ops[0], ConvertType(E->getCallReturnType(getContext())),
+        ICmpInst::FCMP_OLT, ICmpInst::ICMP_SLT, "vcltz");
 
   case NEON::BI__builtin_neon_vceqzd_u64: {
     llvm::Type *Ty = llvm::Type::getInt64Ty(getLLVMContext());
@@ -4698,7 +4803,7 @@
   case NEON::BI__builtin_neon_vfmad_lane_f64:
   case NEON::BI__builtin_neon_vfmad_laneq_f64: {
     Ops.push_back(EmitScalarExpr(E->getArg(3)));
-    llvm::Type *Ty = ConvertType(E->getCallReturnType());
+    llvm::Type *Ty = ConvertType(E->getCallReturnType(getContext()));
     Value *F = CGM.getIntrinsic(Intrinsic::fma, Ty);
     Ops[2] = Builder.CreateExtractElement(Ops[2], Ops[3], "extract");
     return Builder.CreateCall3(F, Ops[1], Ops[2], Ops[0]);
@@ -5825,104 +5930,95 @@
     Ops[0] = Builder.CreateBitCast(Ops[0], PtrTy);
     return Builder.CreateStore(Ops[1], Ops[0]);
   }
-  case X86::BI__builtin_ia32_palignr: {
-    unsigned shiftVal = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
-
-    // If palignr is shifting the pair of input vectors less than 9 bytes,
-    // emit a shuffle instruction.
-    if (shiftVal <= 8) {
-      SmallVector<llvm::Constant*, 8> Indices;
-      for (unsigned i = 0; i != 8; ++i)
-        Indices.push_back(llvm::ConstantInt::get(Int32Ty, shiftVal + i));
-
-      Value* SV = llvm::ConstantVector::get(Indices);
-      return Builder.CreateShuffleVector(Ops[1], Ops[0], SV, "palignr");
-    }
-
-    // If palignr is shifting the pair of input vectors more than 8 but less
-    // than 16 bytes, emit a logical right shift of the destination.
-    if (shiftVal < 16) {
-      // MMX has these as 1 x i64 vectors for some odd optimization reasons.
-      llvm::Type *VecTy = llvm::VectorType::get(Int64Ty, 1);
-
-      Ops[0] = Builder.CreateBitCast(Ops[0], VecTy, "cast");
-      Ops[1] = llvm::ConstantInt::get(VecTy, (shiftVal-8) * 8);
-
-      // create i32 constant
-      llvm::Function *F = CGM.getIntrinsic(Intrinsic::x86_mmx_psrl_q);
-      return Builder.CreateCall(F, makeArrayRef(Ops.data(), 2), "palignr");
-    }
-
-    // If palignr is shifting the pair of vectors more than 16 bytes, emit zero.
-    return llvm::Constant::getNullValue(ConvertType(E->getType()));
-  }
-  case X86::BI__builtin_ia32_palignr128: {
-    unsigned shiftVal = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
-
-    // If palignr is shifting the pair of input vectors less than 17 bytes,
-    // emit a shuffle instruction.
-    if (shiftVal <= 16) {
-      SmallVector<llvm::Constant*, 16> Indices;
-      for (unsigned i = 0; i != 16; ++i)
-        Indices.push_back(llvm::ConstantInt::get(Int32Ty, shiftVal + i));
-
-      Value* SV = llvm::ConstantVector::get(Indices);
-      return Builder.CreateShuffleVector(Ops[1], Ops[0], SV, "palignr");
-    }
-
-    // If palignr is shifting the pair of input vectors more than 16 but less
-    // than 32 bytes, emit a logical right shift of the destination.
-    if (shiftVal < 32) {
-      llvm::Type *VecTy = llvm::VectorType::get(Int64Ty, 2);
-
-      Ops[0] = Builder.CreateBitCast(Ops[0], VecTy, "cast");
-      Ops[1] = llvm::ConstantInt::get(Int32Ty, (shiftVal-16) * 8);
-
-      // create i32 constant
-      llvm::Function *F = CGM.getIntrinsic(Intrinsic::x86_sse2_psrl_dq);
-      return Builder.CreateCall(F, makeArrayRef(Ops.data(), 2), "palignr");
-    }
-
-    // If palignr is shifting the pair of vectors more than 32 bytes, emit zero.
-    return llvm::Constant::getNullValue(ConvertType(E->getType()));
-  }
+  case X86::BI__builtin_ia32_palignr128:
   case X86::BI__builtin_ia32_palignr256: {
-    unsigned shiftVal = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
+    unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
 
-    // If palignr is shifting the pair of input vectors less than 17 bytes,
-    // emit a shuffle instruction.
-    if (shiftVal <= 16) {
-      SmallVector<llvm::Constant*, 32> Indices;
-      // 256-bit palignr operates on 128-bit lanes so we need to handle that
-      for (unsigned l = 0; l != 2; ++l) {
-        unsigned LaneStart = l * 16;
-        unsigned LaneEnd = (l+1) * 16;
-        for (unsigned i = 0; i != 16; ++i) {
-          unsigned Idx = shiftVal + i + LaneStart;
-          if (Idx >= LaneEnd) Idx += 16; // end of lane, switch operand
-          Indices.push_back(llvm::ConstantInt::get(Int32Ty, Idx));
-        }
+    unsigned NumElts =
+      cast<llvm::VectorType>(Ops[0]->getType())->getNumElements();
+    assert(NumElts % 16 == 0);
+    unsigned NumLanes = NumElts / 16;
+    unsigned NumLaneElts = NumElts / NumLanes;
+
+    // If palignr is shifting the pair of vectors more than the size of two
+    // lanes, emit zero.
+    if (ShiftVal >= (2 * NumLaneElts))
+      return llvm::Constant::getNullValue(ConvertType(E->getType()));
+
+    // If palignr is shifting the pair of input vectors more than one lane,
+    // but less than two lanes, convert to shifting in zeroes.
+    if (ShiftVal > NumLaneElts) {
+      ShiftVal -= NumLaneElts;
+      Ops[0] = llvm::Constant::getNullValue(Ops[0]->getType());
+    }
+
+    SmallVector<llvm::Constant*, 32> Indices;
+    // 256-bit palignr operates on 128-bit lanes so we need to handle that
+    for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
+      for (unsigned i = 0; i != NumLaneElts; ++i) {
+        unsigned Idx = ShiftVal + i;
+        if (Idx >= NumLaneElts)
+          Idx += NumElts - NumLaneElts; // End of lane, switch operand.
+        Indices.push_back(llvm::ConstantInt::get(Int32Ty, Idx + l));
       }
-
-      Value* SV = llvm::ConstantVector::get(Indices);
-      return Builder.CreateShuffleVector(Ops[1], Ops[0], SV, "palignr");
     }
 
-    // If palignr is shifting the pair of input vectors more than 16 but less
-    // than 32 bytes, emit a logical right shift of the destination.
-    if (shiftVal < 32) {
-      llvm::Type *VecTy = llvm::VectorType::get(Int64Ty, 4);
+    Value* SV = llvm::ConstantVector::get(Indices);
+    return Builder.CreateShuffleVector(Ops[1], Ops[0], SV, "palignr");
+  }
+  case X86::BI__builtin_ia32_pslldqi256: {
+    // Shift value is in bits so divide by 8.
+    unsigned shiftVal = cast<llvm::ConstantInt>(Ops[1])->getZExtValue() >> 3;
 
-      Ops[0] = Builder.CreateBitCast(Ops[0], VecTy, "cast");
-      Ops[1] = llvm::ConstantInt::get(Int32Ty, (shiftVal-16) * 8);
+    // If pslldq is shifting the vector more than 15 bytes, emit zero.
+    if (shiftVal >= 16)
+      return llvm::Constant::getNullValue(ConvertType(E->getType()));
 
-      // create i32 constant
-      llvm::Function *F = CGM.getIntrinsic(Intrinsic::x86_avx2_psrl_dq);
-      return Builder.CreateCall(F, makeArrayRef(Ops.data(), 2), "palignr");
+    SmallVector<llvm::Constant*, 32> Indices;
+    // 256-bit pslldq operates on 128-bit lanes so we need to handle that
+    for (unsigned l = 0; l != 32; l += 16) {
+      for (unsigned i = 0; i != 16; ++i) {
+        unsigned Idx = 32 + i - shiftVal;
+        if (Idx < 32) Idx -= 16; // end of lane, switch operand.
+        Indices.push_back(llvm::ConstantInt::get(Int32Ty, Idx + l));
+      }
     }
 
-    // If palignr is shifting the pair of vectors more than 32 bytes, emit zero.
-    return llvm::Constant::getNullValue(ConvertType(E->getType()));
+    llvm::Type *VecTy = llvm::VectorType::get(Int8Ty, 32);
+    Ops[0] = Builder.CreateBitCast(Ops[0], VecTy, "cast");
+    Value *Zero = llvm::Constant::getNullValue(VecTy);
+
+    Value *SV = llvm::ConstantVector::get(Indices);
+    SV = Builder.CreateShuffleVector(Zero, Ops[0], SV, "pslldq");
+    llvm::Type *ResultType = ConvertType(E->getType());
+    return Builder.CreateBitCast(SV, ResultType, "cast");
+  }
+  case X86::BI__builtin_ia32_psrldqi256: {
+    // Shift value is in bits so divide by 8.
+    unsigned shiftVal = cast<llvm::ConstantInt>(Ops[1])->getZExtValue() >> 3;
+
+    // If psrldq is shifting the vector more than 15 bytes, emit zero.
+    if (shiftVal >= 16)
+      return llvm::Constant::getNullValue(ConvertType(E->getType()));
+
+    SmallVector<llvm::Constant*, 32> Indices;
+    // 256-bit psrldq operates on 128-bit lanes so we need to handle that
+    for (unsigned l = 0; l != 32; l += 16) {
+      for (unsigned i = 0; i != 16; ++i) {
+        unsigned Idx = i + shiftVal;
+        if (Idx >= 16) Idx += 16; // end of lane, switch operand.
+        Indices.push_back(llvm::ConstantInt::get(Int32Ty, Idx + l));
+      }
+    }
+
+    llvm::Type *VecTy = llvm::VectorType::get(Int8Ty, 32);
+    Ops[0] = Builder.CreateBitCast(Ops[0], VecTy, "cast");
+    Value *Zero = llvm::Constant::getNullValue(VecTy);
+
+    Value *SV = llvm::ConstantVector::get(Indices);
+    SV = Builder.CreateShuffleVector(Ops[0], Zero, SV, "psrldq");
+    llvm::Type *ResultType = ConvertType(E->getType());
+    return Builder.CreateBitCast(SV, ResultType, "cast");
   }
   case X86::BI__builtin_ia32_movntps:
   case X86::BI__builtin_ia32_movntps256:
@@ -5932,8 +6028,8 @@
   case X86::BI__builtin_ia32_movntdq256:
   case X86::BI__builtin_ia32_movnti:
   case X86::BI__builtin_ia32_movnti64: {
-    llvm::MDNode *Node = llvm::MDNode::get(getLLVMContext(),
-                                           Builder.getInt32(1));
+    llvm::MDNode *Node = llvm::MDNode::get(
+        getLLVMContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
 
     // Convert the type of the pointer to a pointer to the stored type.
     Value *BC = Builder.CreateBitCast(Ops[0],
@@ -5956,20 +6052,10 @@
   // 3DNow!
   case X86::BI__builtin_ia32_pswapdsf:
   case X86::BI__builtin_ia32_pswapdsi: {
-    const char *name = nullptr;
-    Intrinsic::ID ID = Intrinsic::not_intrinsic;
-    switch(BuiltinID) {
-    default: llvm_unreachable("Unsupported intrinsic!");
-    case X86::BI__builtin_ia32_pswapdsf:
-    case X86::BI__builtin_ia32_pswapdsi:
-      name = "pswapd";
-      ID = Intrinsic::x86_3dnowa_pswapd;
-      break;
-    }
     llvm::Type *MMXTy = llvm::Type::getX86_MMXTy(getLLVMContext());
     Ops[0] = Builder.CreateBitCast(Ops[0], MMXTy, "cast");
-    llvm::Function *F = CGM.getIntrinsic(ID);
-    return Builder.CreateCall(F, Ops, name);
+    llvm::Function *F = CGM.getIntrinsic(Intrinsic::x86_3dnowa_pswapd);
+    return Builder.CreateCall(F, Ops, "pswapd");
   }
   case X86::BI__builtin_ia32_rdrand16_step:
   case X86::BI__builtin_ia32_rdrand32_step:
@@ -6011,6 +6097,154 @@
     Value *F = CGM.getIntrinsic(Intrinsic::x86_avx2_vbroadcasti128);
     return Builder.CreateCall(F, Builder.CreateBitCast(VecTmp, Int8PtrTy));
   }
+  // SSE comparison intrisics
+  case X86::BI__builtin_ia32_cmpeqps:
+  case X86::BI__builtin_ia32_cmpltps:
+  case X86::BI__builtin_ia32_cmpleps:
+  case X86::BI__builtin_ia32_cmpunordps:
+  case X86::BI__builtin_ia32_cmpneqps:
+  case X86::BI__builtin_ia32_cmpnltps:
+  case X86::BI__builtin_ia32_cmpnleps:
+  case X86::BI__builtin_ia32_cmpordps:
+  case X86::BI__builtin_ia32_cmpeqss:
+  case X86::BI__builtin_ia32_cmpltss:
+  case X86::BI__builtin_ia32_cmpless:
+  case X86::BI__builtin_ia32_cmpunordss:
+  case X86::BI__builtin_ia32_cmpneqss:
+  case X86::BI__builtin_ia32_cmpnltss:
+  case X86::BI__builtin_ia32_cmpnless:
+  case X86::BI__builtin_ia32_cmpordss:
+  case X86::BI__builtin_ia32_cmpeqpd:
+  case X86::BI__builtin_ia32_cmpltpd:
+  case X86::BI__builtin_ia32_cmplepd:
+  case X86::BI__builtin_ia32_cmpunordpd:
+  case X86::BI__builtin_ia32_cmpneqpd:
+  case X86::BI__builtin_ia32_cmpnltpd:
+  case X86::BI__builtin_ia32_cmpnlepd:
+  case X86::BI__builtin_ia32_cmpordpd:
+  case X86::BI__builtin_ia32_cmpeqsd:
+  case X86::BI__builtin_ia32_cmpltsd:
+  case X86::BI__builtin_ia32_cmplesd:
+  case X86::BI__builtin_ia32_cmpunordsd:
+  case X86::BI__builtin_ia32_cmpneqsd:
+  case X86::BI__builtin_ia32_cmpnltsd:
+  case X86::BI__builtin_ia32_cmpnlesd:
+  case X86::BI__builtin_ia32_cmpordsd:
+    // These exist so that the builtin that takes an immediate can be bounds
+    // checked by clang to avoid passing bad immediates to the backend. Since
+    // AVX has a larger immediate than SSE we would need separate builtins to
+    // do the different bounds checking. Rather than create a clang specific
+    // SSE only builtin, this implements eight separate builtins to match gcc
+    // implementation.
+
+    // Choose the immediate.
+    unsigned Imm;
+    switch (BuiltinID) {
+    default: llvm_unreachable("Unsupported intrinsic!");
+    case X86::BI__builtin_ia32_cmpeqps:
+    case X86::BI__builtin_ia32_cmpeqss:
+    case X86::BI__builtin_ia32_cmpeqpd:
+    case X86::BI__builtin_ia32_cmpeqsd:
+      Imm = 0;
+      break;
+    case X86::BI__builtin_ia32_cmpltps:
+    case X86::BI__builtin_ia32_cmpltss:
+    case X86::BI__builtin_ia32_cmpltpd:
+    case X86::BI__builtin_ia32_cmpltsd:
+      Imm = 1;
+      break;
+    case X86::BI__builtin_ia32_cmpleps:
+    case X86::BI__builtin_ia32_cmpless:
+    case X86::BI__builtin_ia32_cmplepd:
+    case X86::BI__builtin_ia32_cmplesd:
+      Imm = 2;
+      break;
+    case X86::BI__builtin_ia32_cmpunordps:
+    case X86::BI__builtin_ia32_cmpunordss:
+    case X86::BI__builtin_ia32_cmpunordpd:
+    case X86::BI__builtin_ia32_cmpunordsd:
+      Imm = 3;
+      break;
+    case X86::BI__builtin_ia32_cmpneqps:
+    case X86::BI__builtin_ia32_cmpneqss:
+    case X86::BI__builtin_ia32_cmpneqpd:
+    case X86::BI__builtin_ia32_cmpneqsd:
+      Imm = 4;
+      break;
+    case X86::BI__builtin_ia32_cmpnltps:
+    case X86::BI__builtin_ia32_cmpnltss:
+    case X86::BI__builtin_ia32_cmpnltpd:
+    case X86::BI__builtin_ia32_cmpnltsd:
+      Imm = 5;
+      break;
+    case X86::BI__builtin_ia32_cmpnleps:
+    case X86::BI__builtin_ia32_cmpnless:
+    case X86::BI__builtin_ia32_cmpnlepd:
+    case X86::BI__builtin_ia32_cmpnlesd:
+      Imm = 6;
+      break;
+    case X86::BI__builtin_ia32_cmpordps:
+    case X86::BI__builtin_ia32_cmpordss:
+    case X86::BI__builtin_ia32_cmpordpd:
+    case X86::BI__builtin_ia32_cmpordsd:
+      Imm = 7;
+      break;
+    }
+
+    // Choose the intrinsic ID.
+    const char *name;
+    Intrinsic::ID ID;
+    switch (BuiltinID) {
+    default: llvm_unreachable("Unsupported intrinsic!");
+    case X86::BI__builtin_ia32_cmpeqps:
+    case X86::BI__builtin_ia32_cmpltps:
+    case X86::BI__builtin_ia32_cmpleps:
+    case X86::BI__builtin_ia32_cmpunordps:
+    case X86::BI__builtin_ia32_cmpneqps:
+    case X86::BI__builtin_ia32_cmpnltps:
+    case X86::BI__builtin_ia32_cmpnleps:
+    case X86::BI__builtin_ia32_cmpordps:
+      name = "cmpps";
+      ID = Intrinsic::x86_sse_cmp_ps;
+      break;
+    case X86::BI__builtin_ia32_cmpeqss:
+    case X86::BI__builtin_ia32_cmpltss:
+    case X86::BI__builtin_ia32_cmpless:
+    case X86::BI__builtin_ia32_cmpunordss:
+    case X86::BI__builtin_ia32_cmpneqss:
+    case X86::BI__builtin_ia32_cmpnltss:
+    case X86::BI__builtin_ia32_cmpnless:
+    case X86::BI__builtin_ia32_cmpordss:
+      name = "cmpss";
+      ID = Intrinsic::x86_sse_cmp_ss;
+      break;
+    case X86::BI__builtin_ia32_cmpeqpd:
+    case X86::BI__builtin_ia32_cmpltpd:
+    case X86::BI__builtin_ia32_cmplepd:
+    case X86::BI__builtin_ia32_cmpunordpd:
+    case X86::BI__builtin_ia32_cmpneqpd:
+    case X86::BI__builtin_ia32_cmpnltpd:
+    case X86::BI__builtin_ia32_cmpnlepd:
+    case X86::BI__builtin_ia32_cmpordpd:
+      name = "cmppd";
+      ID = Intrinsic::x86_sse2_cmp_pd;
+      break;
+    case X86::BI__builtin_ia32_cmpeqsd:
+    case X86::BI__builtin_ia32_cmpltsd:
+    case X86::BI__builtin_ia32_cmplesd:
+    case X86::BI__builtin_ia32_cmpunordsd:
+    case X86::BI__builtin_ia32_cmpneqsd:
+    case X86::BI__builtin_ia32_cmpnltsd:
+    case X86::BI__builtin_ia32_cmpnlesd:
+    case X86::BI__builtin_ia32_cmpordsd:
+      name = "cmpsd";
+      ID = Intrinsic::x86_sse2_cmp_sd;
+      break;
+    }
+
+    Ops.push_back(llvm::ConstantInt::get(Int8Ty, Imm));
+    llvm::Function *F = CGM.getIntrinsic(ID);
+    return Builder.CreateCall(F, Ops, name);
   }
 }
 
@@ -6214,6 +6448,9 @@
   case R600::BI__builtin_amdgpu_ldexp:
   case R600::BI__builtin_amdgpu_ldexpf:
     return emitFPIntBuiltin(*this, E, Intrinsic::AMDGPU_ldexp);
+  case R600::BI__builtin_amdgpu_class:
+  case R600::BI__builtin_amdgpu_classf:
+    return emitFPIntBuiltin(*this, E, Intrinsic::AMDGPU_class);
    default:
     return nullptr;
   }
diff --git a/lib/CodeGen/CGCXX.cpp b/lib/CodeGen/CGCXX.cpp
index e467891..9f0e67e 100644
--- a/lib/CodeGen/CGCXX.cpp
+++ b/lib/CodeGen/CGCXX.cpp
@@ -167,9 +167,9 @@
   }
 
   if (!InEveryTU) {
-    /// If we don't have a definition for the destructor yet, don't
-    /// emit.  We can't emit aliases to declarations; that's just not
-    /// how aliases work.
+    // If we don't have a definition for the destructor yet, don't
+    // emit.  We can't emit aliases to declarations; that's just not
+    // how aliases work.
     if (Ref->isDeclaration())
       return true;
   }
diff --git a/lib/CodeGen/CGCXXABI.h b/lib/CodeGen/CGCXXABI.h
index c52b8e2..cc5c1b2 100644
--- a/lib/CodeGen/CGCXXABI.h
+++ b/lib/CodeGen/CGCXXABI.h
@@ -213,6 +213,7 @@
                                        const CXXDeleteExpr *DE,
                                        llvm::Value *Ptr, QualType ElementType,
                                        const CXXDestructorDecl *Dtor) = 0;
+  virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
 
   virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
 
diff --git a/lib/CodeGen/CGCall.cpp b/lib/CodeGen/CGCall.cpp
index 2ced44d..7e6fef9 100644
--- a/lib/CodeGen/CGCall.cpp
+++ b/lib/CodeGen/CGCall.cpp
@@ -51,6 +51,8 @@
   case CC_X86Pascal: return llvm::CallingConv::C;
   // TODO: Add support for __vectorcall to LLVM.
   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
+  case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
+  case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
   }
 }
 
@@ -83,22 +85,23 @@
   // When translating an unprototyped function type, always use a
   // variadic type.
   return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
-                                 false, None, FTNP->getExtInfo(),
-                                 RequiredArgs(0));
+                                 /*instanceMethod=*/false,
+                                 /*chainCall=*/false, None,
+                                 FTNP->getExtInfo(), RequiredArgs(0));
 }
 
 /// Arrange the LLVM function layout for a value of the given function
 /// type, on top of any implicit parameters already stored.
 static const CGFunctionInfo &
-arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool IsInstanceMethod,
+arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
                         SmallVectorImpl<CanQualType> &prefix,
                         CanQual<FunctionProtoType> FTP) {
   RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
   // FIXME: Kill copy.
-  for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
-    prefix.push_back(FTP->getParamType(i));
+  prefix.append(FTP->param_type_begin(), FTP->param_type_end());
   CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
-  return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
+  return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
+                                     /*chainCall=*/false, prefix,
                                      FTP->getExtInfo(), required);
 }
 
@@ -107,7 +110,8 @@
 const CGFunctionInfo &
 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
   SmallVector<CanQualType, 16> argTypes;
-  return ::arrangeLLVMFunctionInfo(*this, false, argTypes, FTP);
+  return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
+                                   FTP);
 }
 
 static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
@@ -130,9 +134,6 @@
   if (PcsAttr *PCS = D->getAttr<PcsAttr>())
     return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
 
-  if (D->hasAttr<PnaclCallAttr>())
-    return CC_PnaclCall;
-
   if (D->hasAttr<IntelOclBiccAttr>())
     return CC_IntelOclBicc;
 
@@ -205,8 +206,7 @@
   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
 
   // Add the formal parameters.
-  for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
-    argTypes.push_back(FTP->getParamType(i));
+  argTypes.append(FTP->param_type_begin(), FTP->param_type_end());
 
   TheCXXABI.buildStructorSignature(MD, Type, argTypes);
 
@@ -219,7 +219,9 @@
                                : TheCXXABI.hasMostDerivedReturn(GD)
                                      ? CGM.getContext().VoidPtrTy
                                      : Context.VoidTy;
-  return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
+  return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
+                                 /*chainCall=*/false, argTypes, extInfo,
+                                 required);
 }
 
 /// Arrange a call to a C++ method, passing the given arguments.
@@ -243,7 +245,9 @@
                                      : Context.VoidTy;
 
   FunctionType::ExtInfo Info = FPT->getExtInfo();
-  return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
+  return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
+                                 /*chainCall=*/false, ArgTypes, Info,
+                                 Required);
 }
 
 /// Arrange the argument and result information for the declaration or
@@ -262,8 +266,9 @@
   // non-variadic type.
   if (isa<FunctionNoProtoType>(FTy)) {
     CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
-    return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
-                                   noProto->getExtInfo(), RequiredArgs::All);
+    return arrangeLLVMFunctionInfo(
+        noProto->getReturnType(), /*instanceMethod=*/false,
+        /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
   }
 
   assert(isa<FunctionProtoType>(FTy));
@@ -307,8 +312,9 @@
   RequiredArgs required =
     (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
 
-  return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
-                                 argTys, einfo, required);
+  return arrangeLLVMFunctionInfo(
+      GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
+      /*chainCall=*/false, argTys, einfo, required);
 }
 
 const CGFunctionInfo &
@@ -335,7 +341,8 @@
   assert(MD->isVirtual() && "only virtual memptrs have thunks");
   CanQual<FunctionProtoType> FTP = GetFormalType(MD);
   CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
-  return arrangeLLVMFunctionInfo(Context.VoidTy, false, ArgTys,
+  return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
+                                 /*chainCall=*/false, ArgTys,
                                  FTP->getExtInfo(), RequiredArgs(1));
 }
 
@@ -346,7 +353,8 @@
                             CodeGenModule &CGM,
                             const CallArgList &args,
                             const FunctionType *fnType,
-                            unsigned numExtraRequiredArgs) {
+                            unsigned numExtraRequiredArgs,
+                            bool chainCall) {
   assert(args.size() >= numExtraRequiredArgs);
 
   // In most cases, there are no optional arguments.
@@ -368,8 +376,13 @@
     required = RequiredArgs(args.size());
   }
 
-  return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
-                                     fnType->getExtInfo(), required);
+  // FIXME: Kill copy.
+  SmallVector<CanQualType, 16> argTypes;
+  for (const auto &arg : args)
+    argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
+  return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
+                                     /*instanceMethod=*/false, chainCall,
+                                     argTypes, fnType->getExtInfo(), required);
 }
 
 /// Figure out the rules for calling a function with the given formal
@@ -378,8 +391,10 @@
 /// target-dependent in crazy ways.
 const CGFunctionInfo &
 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
-                                      const FunctionType *fnType) {
-  return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
+                                      const FunctionType *fnType,
+                                      bool chainCall) {
+  return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
+                                     chainCall ? 1 : 0, chainCall);
 }
 
 /// A block function call is essentially a free-function call with an
@@ -387,7 +402,8 @@
 const CGFunctionInfo &
 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
                                        const FunctionType *fnType) {
-  return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
+  return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
+                                     /*chainCall=*/false);
 }
 
 const CGFunctionInfo &
@@ -399,8 +415,9 @@
   SmallVector<CanQualType, 16> argTypes;
   for (const auto &Arg : args)
     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
-  return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
-                                 info, required);
+  return arrangeLLVMFunctionInfo(
+      GetReturnType(resultType), /*instanceMethod=*/false,
+      /*chainCall=*/false, argTypes, info, required);
 }
 
 /// Arrange a call to a C++ method, passing the given arguments.
@@ -414,8 +431,9 @@
     argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
 
   FunctionType::ExtInfo info = FPT->getExtInfo();
-  return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
-                                 argTypes, info, required);
+  return arrangeLLVMFunctionInfo(
+      GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
+      /*chainCall=*/false, argTypes, info, required);
 }
 
 const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
@@ -428,13 +446,15 @@
 
   RequiredArgs required =
     (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
-  return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
-                                 required);
+  return arrangeLLVMFunctionInfo(
+      GetReturnType(resultType), /*instanceMethod=*/false,
+      /*chainCall=*/false, argTypes, info, required);
 }
 
 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
-  return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
-                                 FunctionType::ExtInfo(), RequiredArgs::All);
+  return arrangeLLVMFunctionInfo(
+      getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
+      None, FunctionType::ExtInfo(), RequiredArgs::All);
 }
 
 /// Arrange the argument and result information for an abstract value
@@ -442,22 +462,20 @@
 /// above functions ultimately defer to.
 const CGFunctionInfo &
 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
-                                      bool IsInstanceMethod,
+                                      bool instanceMethod,
+                                      bool chainCall,
                                       ArrayRef<CanQualType> argTypes,
                                       FunctionType::ExtInfo info,
                                       RequiredArgs required) {
-#ifndef NDEBUG
-  for (ArrayRef<CanQualType>::const_iterator
-         I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
-    assert(I->isCanonicalAsParam());
-#endif
+  assert(std::all_of(argTypes.begin(), argTypes.end(),
+                     std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
 
   unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
 
   // Lookup or create unique function info.
   llvm::FoldingSetNodeID ID;
-  CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
-                          argTypes);
+  CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
+                          resultType, argTypes);
 
   void *insertPos = nullptr;
   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
@@ -465,8 +483,8 @@
     return *FI;
 
   // Construct the function info.  We co-allocate the ArgInfos.
-  FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
-                              required);
+  FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
+                              resultType, argTypes, required);
   FunctionInfos.InsertNode(FI, insertPos);
 
   bool inserted = FunctionsBeingProcessed.insert(FI).second;
@@ -494,7 +512,8 @@
 }
 
 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
-                                       bool IsInstanceMethod,
+                                       bool instanceMethod,
+                                       bool chainCall,
                                        const FunctionType::ExtInfo &info,
                                        CanQualType resultType,
                                        ArrayRef<CanQualType> argTypes,
@@ -505,7 +524,8 @@
   FI->CallingConvention = llvmCC;
   FI->EffectiveCallingConvention = llvmCC;
   FI->ASTCallingConvention = info.getCC();
-  FI->InstanceMethod = IsInstanceMethod;
+  FI->InstanceMethod = instanceMethod;
+  FI->ChainCall = chainCall;
   FI->NoReturn = info.getNoReturn();
   FI->ReturnsRetained = info.getProducesResult();
   FI->Required = required;
@@ -1343,6 +1363,7 @@
                                            bool AttrOnCallSite) {
   llvm::AttrBuilder FuncAttrs;
   llvm::AttrBuilder RetAttrs;
+  bool HasOptnone = false;
 
   CallingConv = FI.getEffectiveCallingConvention();
 
@@ -1379,16 +1400,22 @@
       FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
       FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
     }
-    if (TargetDecl->hasAttr<MallocAttr>())
+    if (TargetDecl->hasAttr<RestrictAttr>())
       RetAttrs.addAttribute(llvm::Attribute::NoAlias);
     if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
       RetAttrs.addAttribute(llvm::Attribute::NonNull);
+
+    HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
   }
 
-  if (CodeGenOpts.OptimizeSize)
-    FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
-  if (CodeGenOpts.OptimizeSize == 2)
-    FuncAttrs.addAttribute(llvm::Attribute::MinSize);
+  // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
+  if (!HasOptnone) {
+    if (CodeGenOpts.OptimizeSize)
+      FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
+    if (CodeGenOpts.OptimizeSize == 2)
+      FuncAttrs.addAttribute(llvm::Attribute::MinSize);
+  }
+
   if (CodeGenOpts.DisableRedZone)
     FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
   if (CodeGenOpts.NoImplicitFloat)
@@ -1493,7 +1520,6 @@
         getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
   }
 
-
   unsigned ArgNo = 0;
   for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
                                           E = FI.arg_end();
@@ -1521,7 +1547,9 @@
         Attrs.addAttribute(llvm::Attribute::ZExt);
       // FALL THROUGH
     case ABIArgInfo::Direct:
-      if (AI.getInReg())
+      if (ArgNo == 0 && FI.isChainCall())
+        Attrs.addAttribute(llvm::Attribute::Nest);
+      else if (AI.getInReg())
         Attrs.addAttribute(llvm::Attribute::InReg);
       break;
 
@@ -2312,7 +2340,7 @@
   }
 
   if (!RetDbgLoc.isUnknown())
-    Ret->setDebugLoc(RetDbgLoc);
+    Ret->setDebugLoc(std::move(RetDbgLoc));
 }
 
 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
@@ -2647,12 +2675,7 @@
                                    CallExpr::const_arg_iterator ArgBeg,
                                    CallExpr::const_arg_iterator ArgEnd,
                                    const FunctionDecl *CalleeDecl,
-                                   unsigned ParamsToSkip,
-                                   bool ForceColumnInfo) {
-  CGDebugInfo *DI = getDebugInfo();
-  SourceLocation CallLoc;
-  if (DI) CallLoc = DI->getLocation();
-
+                                   unsigned ParamsToSkip) {
   // We *have* to evaluate arguments from right to left in the MS C++ ABI,
   // because arguments are destroyed left to right in the callee.
   if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
@@ -2673,8 +2696,6 @@
       EmitCallArg(Args, *Arg, ArgTypes[I]);
       emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
                           CalleeDecl, ParamsToSkip + I);
-      // Restore the debug location.
-      if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
     }
 
     // Un-reverse the arguments we just evaluated so they match up with the LLVM
@@ -2689,8 +2710,6 @@
     EmitCallArg(Args, *Arg, ArgTypes[I]);
     emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
                         CalleeDecl, ParamsToSkip + I);
-    // Restore the debug location.
-    if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
   }
 }
 
@@ -2713,8 +2732,22 @@
 
 }
 
+struct DisableDebugLocationUpdates {
+  CodeGenFunction &CGF;
+  bool disabledDebugInfo;
+  DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
+    if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
+      CGF.disableDebugInfo();
+  }
+  ~DisableDebugLocationUpdates() {
+    if (disabledDebugInfo)
+      CGF.enableDebugInfo();
+  }
+};
+
 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
                                   QualType type) {
+  DisableDebugLocationUpdates Dis(*this, E);
   if (const ObjCIndirectCopyRestoreExpr *CRE
         = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
     assert(getLangOpts().ObjCAutoRefCount);
@@ -3269,7 +3302,8 @@
 
   llvm::BasicBlock *InvokeDest = nullptr;
   if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
-                          llvm::Attribute::NoUnwind))
+                          llvm::Attribute::NoUnwind) ||
+      currentFunctionUsesSEHTry())
     InvokeDest = getInvokeDest();
 
   llvm::CallSite CS;
@@ -3289,6 +3323,12 @@
         Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
                            llvm::Attribute::AlwaysInline);
 
+  // Disable inlining inside SEH __try blocks.
+  if (isSEHTryScope())
+    Attrs =
+        Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
+                           llvm::Attribute::NoInline);
+
   CS.setAttributes(Attrs);
   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
 
diff --git a/lib/CodeGen/CGClass.cpp b/lib/CodeGen/CGClass.cpp
index 8138c6f..5649708 100644
--- a/lib/CodeGen/CGClass.cpp
+++ b/lib/CodeGen/CGClass.cpp
@@ -24,6 +24,7 @@
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/Frontend/CodeGenOptions.h"
+#include "llvm/IR/Intrinsics.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -544,6 +545,7 @@
                                   CXXCtorInitializer *MemberInit,
                                   const CXXConstructorDecl *Constructor,
                                   FunctionArgList &Args) {
+  ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
   assert(MemberInit->isAnyMemberInitializer() &&
          "Must have member initializer!");
   assert(MemberInit->getInit() && "Must have initializer!");
@@ -600,9 +602,9 @@
   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
 }
 
-void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
-                                              LValue LHS, Expr *Init,
-                                             ArrayRef<VarDecl *> ArrayIndexes) {
+void CodeGenFunction::EmitInitializerForField(
+    FieldDecl *Field, LValue LHS, Expr *Init,
+    ArrayRef<VarDecl *> ArrayIndexes) {
   QualType FieldType = Field->getType();
   switch (getEvaluationKind(FieldType)) {
   case TEK_Scalar:
@@ -781,8 +783,6 @@
   // delegation optimization.
   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
-    if (CGDebugInfo *DI = getDebugInfo()) 
-      DI->EmitLocation(Builder, Ctor->getLocEnd());
     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
     return;
   }
@@ -1735,7 +1735,7 @@
                                              bool Delegating, llvm::Value *This,
                                              const CXXConstructExpr *E) {
   // If this is a trivial constructor, just emit what's needed.
-  if (D->isTrivial()) {
+  if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding()) {
     if (E->getNumArgs() == 0) {
       // Trivial default constructor, no codegen required.
       assert(D->isDefaultConstructor() &&
@@ -1748,9 +1748,10 @@
            "trivial 1-arg ctor not a copy/move ctor");
 
     const Expr *Arg = E->getArg(0);
-    QualType Ty = Arg->getType();
+    QualType SrcTy = Arg->getType();
     llvm::Value *Src = EmitLValue(Arg).getAddress();
-    EmitAggregateCopy(This, Src, Ty);
+    QualType DestTy = getContext().getTypeDeclType(D->getParent());
+    EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
     return;
   }
 
@@ -1785,11 +1786,14 @@
 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
                                         llvm::Value *This, llvm::Value *Src,
                                         const CXXConstructExpr *E) {
-  if (D->isTrivial()) {
+  if (D->isTrivial() &&
+      !D->getParent()->mayInsertExtraPadding()) {
     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
     assert(D->isCopyOrMoveConstructor() &&
            "trivial 1-arg ctor not a copy/move ctor");
-    EmitAggregateCopy(This, Src, E->arg_begin()->getType());
+    EmitAggregateCopyCtor(This, Src,
+                          getContext().getTypeDeclType(D->getParent()),
+                          E->arg_begin()->getType());
     return;
   }
   llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
@@ -1949,6 +1953,14 @@
                                          const CXXRecordDecl *NearestVBase,
                                          CharUnits OffsetFromNearestVBase,
                                          const CXXRecordDecl *VTableClass) {
+  const CXXRecordDecl *RD = Base.getBase();
+
+  // Don't initialize the vtable pointer if the class is marked with the
+  // 'novtable' attribute.
+  if ((RD == VTableClass || RD == NearestVBase) &&
+      VTableClass->hasAttr<MSNoVTableAttr>())
+    return;
+
   // Compute the address point.
   bool NeedsVirtualOffset;
   llvm::Value *VTableAddressPoint =
@@ -1982,10 +1994,14 @@
                                                   NonVirtualOffset,
                                                   VirtualOffset);
 
-  // Finally, store the address point.
-  llvm::Type *AddressPointPtrTy =
-    VTableAddressPoint->getType()->getPointerTo();
-  VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
+  // Finally, store the address point. Use the same LLVM types as the field to
+  // support optimization.
+  llvm::Type *VTablePtrTy =
+      llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
+          ->getPointerTo()
+          ->getPointerTo();
+  VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
+  VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
   CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
 }
@@ -2072,6 +2088,38 @@
   return VTable;
 }
 
+void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
+                                                llvm::Value *VTable) {
+  if (!SanOpts.has(SanitizerKind::CFIVptr))
+    return;
+
+  const CXXRecordDecl *RD = MD->getParent();
+  // FIXME: Add blacklisting scheme.
+  if (RD->isInStdNamespace())
+    return;
+
+  std::string OutName;
+  llvm::raw_string_ostream Out(OutName);
+  CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
+
+  llvm::Value *BitSetName = llvm::MetadataAsValue::get(
+      getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
+
+  llvm::Value *BitSetTest = Builder.CreateCall2(
+      CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
+      Builder.CreateBitCast(VTable, CGM.Int8PtrTy), BitSetName);
+
+  llvm::BasicBlock *ContBlock = createBasicBlock("vtable.check.cont");
+  llvm::BasicBlock *TrapBlock = createBasicBlock("vtable.check.trap");
+
+  Builder.CreateCondBr(BitSetTest, ContBlock, TrapBlock);
+
+  EmitBlock(TrapBlock);
+  Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
+  Builder.CreateUnreachable();
+
+  EmitBlock(ContBlock);
+}
 
 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
 // quite what we want.
@@ -2157,26 +2205,12 @@
   
   // Check if this is a call expr that returns a record type.
   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
-    return CE->getCallReturnType()->isRecordType();
+    return CE->getCallReturnType(getContext())->isRecordType();
 
   // We can't devirtualize the call.
   return false;
 }
 
-llvm::Value *
-CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
-                                             const CXXMethodDecl *MD,
-                                             llvm::Value *This) {
-  llvm::FunctionType *fnType =
-    CGM.getTypes().GetFunctionType(
-                             CGM.getTypes().arrangeCXXMethodDeclaration(MD));
-
-  if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
-    return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
-
-  return CGM.GetAddrOfFunction(MD, fnType);
-}
-
 void CodeGenFunction::EmitForwardingCallToLambda(
                                       const CXXMethodDecl *callOperator,
                                       CallArgList &callArgs) {
diff --git a/lib/CodeGen/CGCleanup.cpp b/lib/CodeGen/CGCleanup.cpp
index d81e3a5..566befc 100644
--- a/lib/CodeGen/CGCleanup.cpp
+++ b/lib/CodeGen/CGCleanup.cpp
@@ -861,11 +861,6 @@
 
   // Emit the EH cleanup if required.
   if (RequiresEHCleanup) {
-    CGDebugInfo *DI = getDebugInfo();
-    SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
-    if (DI)
-      DI->EmitLocation(Builder, CurEHLocation);
-
     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
 
     EmitBlock(EHEntry);
diff --git a/lib/CodeGen/CGCleanup.h b/lib/CodeGen/CGCleanup.h
index dd156c6..5f94aec 100644
--- a/lib/CodeGen/CGCleanup.h
+++ b/lib/CodeGen/CGCleanup.h
@@ -284,15 +284,13 @@
     delete ExtInfo;
   }
   // Objects of EHCleanupScope are not destructed. Use Destroy().
-  ~EHCleanupScope() LLVM_DELETED_FUNCTION;
+  ~EHCleanupScope() = delete;
 
   bool isNormalCleanup() const { return CleanupBits.IsNormalCleanup; }
   llvm::BasicBlock *getNormalBlock() const { return NormalBlock; }
   void setNormalBlock(llvm::BasicBlock *BB) { NormalBlock = BB; }
 
   bool isEHCleanup() const { return CleanupBits.IsEHCleanup; }
-  llvm::BasicBlock *getEHBlock() const { return getCachedEHDispatchBlock(); }
-  void setEHBlock(llvm::BasicBlock *BB) { setCachedEHDispatchBlock(BB); }
 
   bool isActive() const { return CleanupBits.IsActive; }
   void setActive(bool A) { CleanupBits.IsActive = A; }
diff --git a/lib/CodeGen/CGDebugInfo.cpp b/lib/CodeGen/CGDebugInfo.cpp
index 416f69e..6d78ee8 100644
--- a/lib/CodeGen/CGDebugInfo.cpp
+++ b/lib/CodeGen/CGDebugInfo.cpp
@@ -52,54 +52,60 @@
          "Region stack mismatch, stack not empty!");
 }
 
-SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
-                                               CGBuilderTy &B)
-    : DI(CGF.getDebugInfo()), Builder(B) {
-  if (DI) {
-    SavedLoc = DI->getLocation();
-    DI->CurLoc = SourceLocation();
+ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
+                                       SourceLocation TemporaryLocation)
+    : CGF(CGF) {
+  init(TemporaryLocation);
+}
+
+ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
+                                       bool DefaultToEmpty,
+                                       SourceLocation TemporaryLocation)
+    : CGF(CGF) {
+  init(TemporaryLocation, DefaultToEmpty);
+}
+
+void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
+                              bool DefaultToEmpty) {
+  if (auto *DI = CGF.getDebugInfo()) {
+    OriginalLocation = CGF.Builder.getCurrentDebugLocation();
+    if (TemporaryLocation.isInvalid()) {
+      if (DefaultToEmpty)
+        CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc());
+      else {
+        // Construct a location that has a valid scope, but no line info.
+        assert(!DI->LexicalBlockStack.empty());
+        llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
+        CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
+      }
+    } else
+      DI->EmitLocation(CGF.Builder, TemporaryLocation);
   }
 }
 
-SaveAndRestoreLocation::~SaveAndRestoreLocation() {
-  if (DI)
-    DI->EmitLocation(Builder, SavedLoc);
+ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
+    : CGF(CGF) {
+  init(E->getExprLoc());
 }
 
-NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
-    : SaveAndRestoreLocation(CGF, B) {
-  if (DI)
-    Builder.SetCurrentDebugLocation(llvm::DebugLoc());
-}
-
-NoLocation::~NoLocation() {
-  if (DI)
-    assert(Builder.getCurrentDebugLocation().isUnknown());
-}
-
-ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
-    : SaveAndRestoreLocation(CGF, B) {
-  if (DI)
-    Builder.SetCurrentDebugLocation(llvm::DebugLoc());
-}
-
-void ArtificialLocation::Emit() {
-  if (DI) {
-    // Sync the Builder.
-    DI->EmitLocation(Builder, SavedLoc);
-    DI->CurLoc = SourceLocation();
-    // Construct a location that has a valid scope, but no line info.
-    assert(!DI->LexicalBlockStack.empty());
-    llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
-    Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
+ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
+    : CGF(CGF) {
+  if (CGF.getDebugInfo()) {
+    OriginalLocation = CGF.Builder.getCurrentDebugLocation();
+    if (!Loc.isUnknown())
+      CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
   }
 }
 
-ArtificialLocation::~ArtificialLocation() {
-  if (DI)
-    assert(Builder.getCurrentDebugLocation().getLine() == 0);
+ApplyDebugLocation::~ApplyDebugLocation() {
+  // Query CGF so the location isn't overwritten when location updates are
+  // temporarily disabled (for C++ default function arguments)
+  if (CGF.getDebugInfo())
+    CGF.Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
 }
 
+/// ArtificialLocation - An RAII object that temporarily switches to
+/// an artificial debug location that has a valid scope, but no line
 void CGDebugInfo::setLocation(SourceLocation Loc) {
   // If the new location isn't valid return.
   if (Loc.isInvalid())
@@ -126,13 +132,13 @@
         LBF.getScope(), getOrCreateFile(CurLoc));
     llvm::MDNode *N = D;
     LexicalBlockStack.pop_back();
-    LexicalBlockStack.push_back(N);
+    LexicalBlockStack.emplace_back(N);
   } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
     llvm::DIDescriptor D =
         DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
     llvm::MDNode *N = D;
     LexicalBlockStack.pop_back();
-    LexicalBlockStack.push_back(N);
+    LexicalBlockStack.emplace_back(N);
   }
 }
 
@@ -141,10 +147,9 @@
   if (!Context)
     return TheCU;
 
-  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
-      RegionMap.find(Context);
+  auto I = RegionMap.find(Context);
   if (I != RegionMap.end()) {
-    llvm::Value *V = I->second;
+    llvm::Metadata *V = I->second;
     return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
   }
 
@@ -256,18 +261,17 @@
 
   // Cache the results.
   const char *fname = PLoc.getFilename();
-  llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
-      DIFileCache.find(fname);
+  auto it = DIFileCache.find(fname);
 
   if (it != DIFileCache.end()) {
     // Verify that the information still exists.
-    if (llvm::Value *V = it->second)
+    if (llvm::Metadata *V = it->second)
       return llvm::DIFile(cast<llvm::MDNode>(V));
   }
 
   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
 
-  DIFileCache[fname] = F;
+  DIFileCache[fname].reset(F);
   return F;
 }
 
@@ -424,9 +428,10 @@
         DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
                                   0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
 
-    ObjTy.setArrays(DBuilder.getOrCreateArray(
-        &*DBuilder.createMemberType(ObjTy, "isa", getOrCreateMainFile(), 0,
-                                    Size, 0, 0, 0, ISATy)));
+    DBuilder.replaceArrays(
+        ObjTy,
+        DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
+            ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
     return ObjTy;
   }
   case BuiltinType::ObjCSel: {
@@ -616,6 +621,21 @@
   return FullName;
 }
 
+static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
+   llvm::dwarf::Tag Tag;
+  if (RD->isStruct() || RD->isInterface())
+    Tag = llvm::dwarf::DW_TAG_structure_type;
+  else if (RD->isUnion())
+    Tag = llvm::dwarf::DW_TAG_union_type;
+  else {
+    // FIXME: This could be a struct type giving a default visibility different
+    // than C++ class type, but needs llvm metadata changes first.
+    assert(RD->isClass());
+    Tag = llvm::dwarf::DW_TAG_class_type;
+  }
+  return Tag;
+}
+
 // Creates a forward declaration for a RecordDecl in the given context.
 llvm::DICompositeType
 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
@@ -627,21 +647,15 @@
   unsigned Line = getLineNumber(RD->getLocation());
   StringRef RDName = getClassName(RD);
 
-  llvm::dwarf::Tag Tag;
-  if (RD->isStruct() || RD->isInterface())
-    Tag = llvm::dwarf::DW_TAG_structure_type;
-  else if (RD->isUnion())
-    Tag = llvm::dwarf::DW_TAG_union_type;
-  else {
-    assert(RD->isClass());
-    Tag = llvm::dwarf::DW_TAG_class_type;
-  }
 
   // Create the type.
   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
-  llvm::DICompositeType RetTy = DBuilder.createReplaceableForwardDecl(
-      Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0, FullName);
-  ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
+  llvm::DICompositeType RetTy = DBuilder.createReplaceableCompositeType(
+      getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, 0, 0,
+      llvm::DIDescriptor::FlagFwdDecl, FullName);
+  ReplaceMap.emplace_back(
+      std::piecewise_construct, std::make_tuple(Ty),
+      std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
   return RetTy;
 }
 
@@ -680,7 +694,7 @@
   if (BlockLiteralGeneric)
     return BlockLiteralGeneric;
 
-  SmallVector<llvm::Value *, 8> EltTys;
+  SmallVector<llvm::Metadata *, 8> EltTys;
   llvm::DIType FieldTy;
   QualType FType;
   uint64_t FieldSize, FieldOffset;
@@ -784,7 +798,7 @@
 
 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
                                      llvm::DIFile Unit) {
-  SmallVector<llvm::Value *, 16> EltTys;
+  SmallVector<llvm::Metadata *, 16> EltTys;
 
   // Add the result type at least.
   EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
@@ -857,10 +871,9 @@
 }
 
 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
-void
-CGDebugInfo::CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
-                                       SmallVectorImpl<llvm::Value *> &elements,
-                                       llvm::DIType RecordTy) {
+void CGDebugInfo::CollectRecordLambdaFields(
+    const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
+    llvm::DIType RecordTy) {
   // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
   // has the name and the location of the variable so we should iterate over
   // both concurrently.
@@ -928,14 +941,14 @@
   unsigned Flags = getAccessFlag(Var->getAccess(), RD);
   llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
       RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
-  StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
+  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
   return GV;
 }
 
 /// CollectRecordNormalField - Helper for CollectRecordFields.
 void CGDebugInfo::CollectRecordNormalField(
     const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile tunit,
-    SmallVectorImpl<llvm::Value *> &elements, llvm::DIType RecordTy,
+    SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType RecordTy,
     const RecordDecl *RD) {
   StringRef name = field->getName();
   QualType type = field->getType();
@@ -959,10 +972,10 @@
 
 /// CollectRecordFields - A helper function to collect debug info for
 /// record fields. This is used while creating debug info entry for a Record.
-void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
-                                      llvm::DIFile tunit,
-                                      SmallVectorImpl<llvm::Value *> &elements,
-                                      llvm::DICompositeType RecordTy) {
+void CGDebugInfo::CollectRecordFields(
+    const RecordDecl *record, llvm::DIFile tunit,
+    SmallVectorImpl<llvm::Metadata *> &elements,
+    llvm::DICompositeType RecordTy) {
   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
 
   if (CXXDecl && CXXDecl->isLambda())
@@ -978,8 +991,7 @@
     for (const auto *I : record->decls())
       if (const auto *V = dyn_cast<VarDecl>(I)) {
         // Reuse the existing static member declaration if one exists
-        llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
-            StaticDataMemberCache.find(V->getCanonicalDecl());
+        auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
         if (MI != StaticDataMemberCache.end()) {
           assert(MI->second &&
                  "Static data member declaration should still exist");
@@ -1019,7 +1031,7 @@
       getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
   assert(Args.getNumElements() && "Invalid number of arguments!");
 
-  SmallVector<llvm::Value *, 16> Elts;
+  SmallVector<llvm::Metadata *, 16> Elts;
 
   // First element is always return type. For 'void' functions it is NULL.
   Elts.push_back(Args.getElement(0));
@@ -1036,7 +1048,7 @@
     llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
     llvm::DIType ThisPtrType =
         DBuilder.createPointerType(PointeeType, Size, Align);
-    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
+    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
     // TODO: This and the artificial type below are misleading, the
     // types aren't artificial the argument is, but the current
     // metadata doesn't represent that.
@@ -1044,7 +1056,7 @@
     Elts.push_back(ThisPtrType);
   } else {
     llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
-    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
+    TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
     Elts.push_back(ThisPtrType);
   }
@@ -1147,7 +1159,7 @@
       /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
       CGM.getLangOpts().Optimize, nullptr, TParamsArray);
 
-  SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
+  SPCache[Method->getCanonicalDecl()].reset(SP);
 
   return SP;
 }
@@ -1157,7 +1169,7 @@
 /// a Record.
 void CGDebugInfo::CollectCXXMemberFunctions(
     const CXXRecordDecl *RD, llvm::DIFile Unit,
-    SmallVectorImpl<llvm::Value *> &EltTys, llvm::DIType RecordTy) {
+    SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType RecordTy) {
 
   // Since we want more than just the individual member decls if we
   // have templated functions iterate over every declaration to gather
@@ -1188,7 +1200,7 @@
     auto MI = SPCache.find(Method->getCanonicalDecl());
     EltTys.push_back(MI == SPCache.end()
                          ? CreateCXXMemberFunction(Method, Unit, RecordTy)
-                         : static_cast<llvm::Value *>(MI->second));
+                         : static_cast<llvm::Metadata *>(MI->second));
   }
 }
 
@@ -1196,7 +1208,7 @@
 /// C++ base classes. This is used while creating debug info entry for
 /// a Record.
 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
-                                  SmallVectorImpl<llvm::Value *> &EltTys,
+                                  SmallVectorImpl<llvm::Metadata *> &EltTys,
                                   llvm::DIType RecordTy) {
 
   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
@@ -1238,7 +1250,7 @@
 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
                                    ArrayRef<TemplateArgument> TAList,
                                    llvm::DIFile Unit) {
-  SmallVector<llvm::Value *, 16> TemplateParams;
+  SmallVector<llvm::Metadata *, 16> TemplateParams;
   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
     const TemplateArgument &TA = TAList[i];
     StringRef Name;
@@ -1263,7 +1275,7 @@
       const ValueDecl *D = TA.getAsDecl();
       QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
       llvm::DIType TTy = getOrCreateType(T, Unit);
-      llvm::Value *V = nullptr;
+      llvm::Constant *V = nullptr;
       const CXXMethodDecl *MD;
       // Variable pointer template parameters have a value that is the address
       // of the variable.
@@ -1295,7 +1307,7 @@
     case TemplateArgument::NullPtr: {
       QualType T = TA.getNullPtrType();
       llvm::DIType TTy = getOrCreateType(T, Unit);
-      llvm::Value *V = nullptr;
+      llvm::Constant *V = nullptr;
       // Special case member data pointer null values since they're actually -1
       // instead of zero.
       if (const MemberPointerType *MPT =
@@ -1332,7 +1344,7 @@
       QualType T = E->getType();
       if (E->isGLValue())
         T = CGM.getContext().getLValueReferenceType(T);
-      llvm::Value *V = CGM.EmitConstantExpr(E, T);
+      llvm::Constant *V = CGM.EmitConstantExpr(E, T);
       assert(V && "Expression in template argument isn't constant");
       llvm::DIType TTy = getOrCreateType(T, Unit);
       llvm::DITemplateValueParameter TVP =
@@ -1385,7 +1397,7 @@
   ASTContext &Context = CGM.getContext();
 
   /* Function type */
-  llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
+  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
   llvm::DITypeArray SElements = DBuilder.getOrCreateTypeArray(STy);
   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
@@ -1404,7 +1416,7 @@
 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
 /// debug info entry in EltTys vector.
 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
-                                    SmallVectorImpl<llvm::Value *> &EltTys) {
+                                    SmallVectorImpl<llvm::Metadata *> &EltTys) {
   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
 
   // If there is a primary base then it will hold vtable info.
@@ -1447,12 +1459,11 @@
   void *TyPtr = Ty.getAsOpaquePtr();
   auto I = TypeCache.find(TyPtr);
   if (I == TypeCache.end() ||
-      !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
-           .isForwardDecl())
+      !llvm::DIType(cast<llvm::MDNode>(I->second)).isForwardDecl())
     return;
   llvm::DIType Res = CreateTypeDefinition(Ty->castAs<EnumType>());
   assert(!Res.isForwardDecl());
-  TypeCache[TyPtr] = Res;
+  TypeCache[TyPtr].reset(Res);
 }
 
 void CGDebugInfo::completeType(const RecordDecl *RD) {
@@ -1482,12 +1493,11 @@
   void *TyPtr = Ty.getAsOpaquePtr();
   auto I = TypeCache.find(TyPtr);
   if (I != TypeCache.end() &&
-      !llvm::DIType(cast<llvm::MDNode>(static_cast<llvm::Value *>(I->second)))
-           .isForwardDecl())
+      !llvm::DIType(cast<llvm::MDNode>(I->second)).isForwardDecl())
     return;
   llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
   assert(!Res.isForwardDecl());
-  TypeCache[TyPtr] = Res;
+  TypeCache[TyPtr].reset(Res);
 }
 
 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
@@ -1564,18 +1574,19 @@
   assert(FwdDecl.isCompositeType() &&
          "The debug type of a RecordType should be a llvm::DICompositeType");
 
-  if (FwdDecl.isForwardDecl())
+  const RecordDecl *D = RD->getDefinition();
+  if (!D || !D->isCompleteDefinition())
     return FwdDecl;
 
   if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
     CollectContainingType(CXXDecl, FwdDecl);
 
   // Push the struct on region stack.
-  LexicalBlockStack.push_back(&*FwdDecl);
-  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
+  LexicalBlockStack.emplace_back(&*FwdDecl);
+  RegionMap[Ty->getDecl()].reset(FwdDecl);
 
   // Convert all the elements.
-  SmallVector<llvm::Value *, 16> EltTys;
+  SmallVector<llvm::Metadata *, 16> EltTys;
   // what about nested types?
 
   // Note: The split of CXXDecl information here is intentional, the
@@ -1597,9 +1608,13 @@
   RegionMap.erase(Ty->getDecl());
 
   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
-  FwdDecl.setArrays(Elements);
+  DBuilder.replaceArrays(FwdDecl, Elements);
 
-  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
+  if (FwdDecl->isTemporary())
+    FwdDecl = llvm::DICompositeType(llvm::MDNode::replaceWithPermanent(
+      llvm::TempMDNode(FwdDecl.get())));
+
+  RegionMap[Ty->getDecl()].reset(FwdDecl);
   return FwdDecl;
 }
 
@@ -1650,7 +1665,7 @@
   // debug type since we won't be able to lay out the entire type.
   ObjCInterfaceDecl *Def = ID->getDefinition();
   if (!Def || !Def->getImplementation()) {
-    llvm::DIType FwdDecl = DBuilder.createReplaceableForwardDecl(
+    llvm::DIType FwdDecl = DBuilder.createReplaceableCompositeType(
         llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
         RuntimeLang);
     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
@@ -1680,14 +1695,14 @@
       llvm::DIArray(), RuntimeLang);
 
   QualType QTy(Ty, 0);
-  TypeCache[QTy.getAsOpaquePtr()] = RealDecl;
+  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
 
   // Push the struct on region stack.
-  LexicalBlockStack.push_back(static_cast<llvm::MDNode *>(RealDecl));
-  RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
+  LexicalBlockStack.emplace_back(static_cast<llvm::MDNode *>(RealDecl));
+  RegionMap[Ty->getDecl()].reset(RealDecl);
 
   // Convert all the elements.
-  SmallVector<llvm::Value *, 16> EltTys;
+  SmallVector<llvm::Metadata *, 16> EltTys;
 
   ObjCInterfaceDecl *SClass = ID->getSuperClass();
   if (SClass) {
@@ -1799,7 +1814,7 @@
   }
 
   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
-  RealDecl.setArrays(Elements);
+  DBuilder.replaceArrays(RealDecl, Elements);
 
   LexicalBlockStack.pop_back();
   return RealDecl;
@@ -1813,7 +1828,7 @@
     // Use Count == -1 to express such arrays.
     Count = -1;
 
-  llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
+  llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
@@ -1849,7 +1864,7 @@
   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
   // interior arrays, do we care?  Why aren't nested arrays represented the
   // obvious/recursive way?
-  SmallVector<llvm::Value *, 8> Subscripts;
+  SmallVector<llvm::Metadata *, 8> Subscripts;
   QualType EltTy(Ty, 0);
   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
     // If the number of elements is known, then count is that number. Otherwise,
@@ -1892,7 +1907,8 @@
   llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
   if (!Ty->getPointeeType()->isFunctionType())
     return DBuilder.createMemberPointerType(
-        getOrCreateType(Ty->getPointeeType(), U), ClassType);
+      getOrCreateType(Ty->getPointeeType(), U), ClassType,
+      CGM.getContext().getTypeSize(Ty));
 
   const FunctionProtoType *FPT =
       Ty->getPointeeType()->getAs<FunctionProtoType>();
@@ -1900,7 +1916,7 @@
       getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
                                         Ty->getClass(), FPT->getTypeQuals())),
                                     FPT, U),
-      ClassType);
+      ClassType, CGM.getContext().getTypeSize(Ty));
 }
 
 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile U) {
@@ -1929,10 +1945,12 @@
     llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
     unsigned Line = getLineNumber(ED->getLocation());
     StringRef EDName = ED->getName();
-    llvm::DIType RetTy = DBuilder.createReplaceableForwardDecl(
+    llvm::DIType RetTy = DBuilder.createReplaceableCompositeType(
         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
-        0, Size, Align, FullName);
-    ReplaceMap.push_back(std::make_pair(Ty, static_cast<llvm::Value *>(RetTy)));
+        0, Size, Align, llvm::DIDescriptor::FlagFwdDecl, FullName);
+    ReplaceMap.emplace_back(
+        std::piecewise_construct, std::make_tuple(Ty),
+        std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
     return RetTy;
   }
 
@@ -1951,7 +1969,7 @@
   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
 
   // Create DIEnumerator elements for each enumerator.
-  SmallVector<llvm::Value *, 16> Enumerators;
+  SmallVector<llvm::Metadata *, 16> Enumerators;
   ED = ED->getDefinition();
   for (const auto *Enum : ED->enumerators()) {
     Enumerators.push_back(DBuilder.createEnumerator(
@@ -2039,7 +2057,7 @@
   auto it = TypeCache.find(Ty.getAsOpaquePtr());
   if (it != TypeCache.end()) {
     // Verify that the debug info still exists.
-    if (llvm::Value *V = it->second)
+    if (llvm::Metadata *V = it->second)
       return llvm::DIType(cast<llvm::MDNode>(V));
   }
 
@@ -2074,7 +2092,7 @@
   void *TyPtr = Ty.getAsOpaquePtr();
 
   // And update the type cache.
-  TypeCache[TyPtr] = Res;
+  TypeCache[TyPtr].reset(Res);
 
   return Res;
 }
@@ -2206,10 +2224,10 @@
   // Propagate members from the declaration to the definition
   // CreateType(const RecordType*) will overwrite this with the members in the
   // correct order if the full type is needed.
-  Res.setArrays(T.getElements());
+  DBuilder.replaceArrays(Res, T.getElements());
 
   // And update the type cache.
-  TypeCache[QTy.getAsOpaquePtr()] = Res;
+  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
   return Res;
 }
 
@@ -2243,27 +2261,16 @@
 
   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
 
-  if (RD->isUnion())
-    RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line, Size,
-                                        Align, 0, llvm::DIArray(), 0, FullName);
-  else if (RD->isClass()) {
-    // FIXME: This could be a struct type giving a default visibility different
-    // than C++ class type, but needs llvm metadata changes first.
-    RealDecl = DBuilder.createClassType(
-        RDContext, RDName, DefUnit, Line, Size, Align, 0, 0, llvm::DIType(),
-        llvm::DIArray(), llvm::DIType(), llvm::DIArray(), FullName);
-  } else
-    RealDecl = DBuilder.createStructType(
-        RDContext, RDName, DefUnit, Line, Size, Align, 0, llvm::DIType(),
-        llvm::DIArray(), 0, llvm::DIType(), FullName);
+  RealDecl = DBuilder.createReplaceableCompositeType(getTagForRecord(RD),
+      RDName, RDContext, DefUnit, Line, 0, Size, Align, 0, FullName);
 
-  RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
-  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
+  RegionMap[Ty->getDecl()].reset(RealDecl);
+  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
 
   if (const ClassTemplateSpecializationDecl *TSpecial =
           dyn_cast<ClassTemplateSpecializationDecl>(RD))
-    RealDecl.setArrays(llvm::DIArray(),
-                       CollectCXXTemplateParams(TSpecial, DefUnit));
+    DBuilder.replaceArrays(RealDecl, llvm::DIArray(),
+                           CollectCXXTemplateParams(TSpecial, DefUnit));
   return RealDecl;
 }
 
@@ -2288,7 +2295,7 @@
   } else if (RD->isDynamicClass())
     ContainingType = RealDecl;
 
-  RealDecl.setContainingType(ContainingType);
+  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
 }
 
 /// CreateMemberType - Create new member and increase Offset by FType's size.
@@ -2401,8 +2408,9 @@
                                        CGM.getLangOpts().Optimize, nullptr,
                                        TParamsArray, getFunctionDeclaration(FD));
   const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
-  FwdDeclReplaceMap.push_back(std::make_pair(CanonDecl,
-                                             static_cast<llvm::Value *>(SP)));
+  FwdDeclReplaceMap.emplace_back(
+      std::piecewise_construct, std::make_tuple(CanonDecl),
+      std::make_tuple(static_cast<llvm::Metadata *>(SP)));
   return SP;
 }
 
@@ -2421,8 +2429,10 @@
                                              Line, getOrCreateType(T, Unit),
                                              !VD->isExternallyVisible(),
                                              nullptr, nullptr);
-  FwdDeclReplaceMap.push_back(std::make_pair(cast<VarDecl>(VD->getCanonicalDecl()),
-                                             static_cast<llvm::Value *>(GV)));
+  FwdDeclReplaceMap.emplace_back(
+      std::piecewise_construct,
+      std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
+      std::make_tuple(static_cast<llvm::Metadata *>(GV)));
   return GV;
 }
 
@@ -2434,13 +2444,10 @@
   if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
                            getOrCreateFile(TD->getLocation()));
-  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
-      DeclCache.find(D->getCanonicalDecl());
+  auto I = DeclCache.find(D->getCanonicalDecl());
 
-  if (I != DeclCache.end()) {
-    llvm::Value *V = I->second;
-    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
-  }
+  if (I != DeclCache.end())
+    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
 
   // No definition for now. Emit a forward definition that might be
   // merged with a potential upcoming definition.
@@ -2465,8 +2472,7 @@
   // Setup context.
   llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
 
-  llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
-      SPCache.find(FD->getCanonicalDecl());
+  auto MI = SPCache.find(FD->getCanonicalDecl());
   if (MI == SPCache.end()) {
     if (const CXXMethodDecl *MD =
             dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
@@ -2477,18 +2483,15 @@
     }
   }
   if (MI != SPCache.end()) {
-    llvm::Value *V = MI->second;
-    llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
+    llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(MI->second));
     if (SP.isSubprogram() && !SP.isDefinition())
       return SP;
   }
 
   for (auto NextFD : FD->redecls()) {
-    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
-        SPCache.find(NextFD->getCanonicalDecl());
+    auto MI = SPCache.find(NextFD->getCanonicalDecl());
     if (MI != SPCache.end()) {
-      llvm::Value *V = MI->second;
-      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
+      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(MI->second));
       if (SP.isSubprogram() && !SP.isDefinition())
         return SP;
     }
@@ -2513,7 +2516,7 @@
     return getOrCreateMethodType(Method, F);
   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
     // Add "self" and "_cmd"
-    SmallVector<llvm::Value *, 16> Elts;
+    SmallVector<llvm::Metadata *, 16> Elts;
 
     // First element is always return type. For 'void' functions it is NULL.
     QualType ResultTy = OMethod->getReturnType();
@@ -2546,7 +2549,7 @@
   // unspecified parameter.
   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
     if (FD->isVariadic()) {
-      SmallVector<llvm::Value *, 16> EltTys;
+      SmallVector<llvm::Metadata *, 16> EltTys;
       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
         for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
@@ -2581,15 +2584,13 @@
     LinkageName = Fn->getName();
   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
     // If there is a DISubprogram for this function available then use it.
-    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator FI =
-        SPCache.find(FD->getCanonicalDecl());
+    auto FI = SPCache.find(FD->getCanonicalDecl());
     if (FI != SPCache.end()) {
-      llvm::Value *V = FI->second;
-      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
+      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
         llvm::MDNode *SPN = SP;
-        LexicalBlockStack.push_back(SPN);
-        RegionMap[D] = llvm::WeakVH(SP);
+        LexicalBlockStack.emplace_back(SPN);
+        RegionMap[D].reset(SP);
         return;
       }
     }
@@ -2629,54 +2630,42 @@
   // code for the initialization of globals. Do not record these decls
   // as they will overwrite the actual VarDecl Decl in the cache.
   if (HasDecl && isa<FunctionDecl>(D))
-    DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
+    DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
 
   // Push the function onto the lexical block stack.
   llvm::MDNode *SPN = SP;
-  LexicalBlockStack.push_back(SPN);
+  LexicalBlockStack.emplace_back(SPN);
 
   if (HasDecl)
-    RegionMap[D] = llvm::WeakVH(SP);
+    RegionMap[D].reset(SP);
 }
 
 /// EmitLocation - Emit metadata to indicate a change in line/column
 /// information in the source file. If the location is invalid, the
 /// previous location will be reused.
-void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
-                               bool ForceColumnInfo) {
+void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
   // Update our current location
   setLocation(Loc);
 
   if (CurLoc.isInvalid() || CurLoc.isMacroID())
     return;
 
-  // Don't bother if things are the same as last time.
-  SourceManager &SM = CGM.getContext().getSourceManager();
-  if (CurLoc == PrevLoc ||
-      SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
-    // New Builder may not be in sync with CGDebugInfo.
-    if (!Builder.getCurrentDebugLocation().isUnknown() &&
-        Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
-            LexicalBlockStack.back())
-      return;
-
-  // Update last state.
-  PrevLoc = CurLoc;
-
   llvm::MDNode *Scope = LexicalBlockStack.back();
   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
-      getLineNumber(CurLoc), getColumnNumber(CurLoc, ForceColumnInfo), Scope));
+      getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
 }
 
 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
 /// the stack.
 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
+  llvm::MDNode *Back = nullptr;
+  if (!LexicalBlockStack.empty())
+    Back = LexicalBlockStack.back().get();
   llvm::DIDescriptor D = DBuilder.createLexicalBlock(
-      llvm::DIDescriptor(LexicalBlockStack.empty() ? nullptr
-                                                   : LexicalBlockStack.back()),
-      getOrCreateFile(CurLoc), getLineNumber(CurLoc), getColumnNumber(CurLoc));
+      llvm::DIDescriptor(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
+      getColumnNumber(CurLoc));
   llvm::MDNode *DN = D;
-  LexicalBlockStack.push_back(DN);
+  LexicalBlockStack.emplace_back(DN);
 }
 
 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
@@ -2732,7 +2721,7 @@
 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
                                                        uint64_t *XOffset) {
 
-  SmallVector<llvm::Value *, 5> EltTys;
+  SmallVector<llvm::Metadata *, 5> EltTys;
   QualType FType;
   uint64_t FieldSize, FieldOffset;
   unsigned FieldAlign;
@@ -2803,7 +2792,7 @@
 }
 
 /// EmitDeclare - Emit local variable declaration debug info.
-void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::LLVMConstants Tag,
+void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::Tag Tag,
                               llvm::Value *Storage, unsigned ArgNo,
                               CGBuilderTy &Builder) {
   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
@@ -2834,6 +2823,7 @@
     Line = getLineNumber(VD->getLocation());
     Column = getColumnNumber(VD->getLocation());
   }
+  SmallVector<int64_t, 9> Expr;
   unsigned Flags = 0;
   if (VD->isImplicit())
     Flags |= llvm::DIDescriptor::FlagArtificial;
@@ -2847,7 +2837,7 @@
   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
     if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
         !VD->getType()->isPointerType())
-      Flags |= llvm::DIDescriptor::FlagIndirectVariable;
+      Expr.push_back(llvm::dwarf::DW_OP_deref);
 
   llvm::MDNode *Scope = LexicalBlockStack.back();
 
@@ -2855,17 +2845,16 @@
   if (!Name.empty()) {
     if (VD->hasAttr<BlocksAttr>()) {
       CharUnits offset = CharUnits::fromQuantity(32);
-      SmallVector<int64_t, 9> addr;
-      addr.push_back(llvm::dwarf::DW_OP_plus);
+      Expr.push_back(llvm::dwarf::DW_OP_plus);
       // offset of __forwarding field
       offset = CGM.getContext().toCharUnitsFromBits(
           CGM.getTarget().getPointerWidth(0));
-      addr.push_back(offset.getQuantity());
-      addr.push_back(llvm::dwarf::DW_OP_deref);
-      addr.push_back(llvm::dwarf::DW_OP_plus);
+      Expr.push_back(offset.getQuantity());
+      Expr.push_back(llvm::dwarf::DW_OP_deref);
+      Expr.push_back(llvm::dwarf::DW_OP_plus);
       // offset of x field
       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
-      addr.push_back(offset.getQuantity());
+      Expr.push_back(offset.getQuantity());
 
       // Create the descriptor for the variable.
       llvm::DIVariable D = DBuilder.createLocalVariable(
@@ -2873,12 +2862,12 @@
 
       // Insert an llvm.dbg.declare into the current block.
       llvm::Instruction *Call =
-          DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr),
+          DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
                                  Builder.GetInsertBlock());
       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
       return;
     } else if (isa<VariableArrayType>(VD->getType()))
-      Flags |= llvm::DIDescriptor::FlagIndirectVariable;
+      Expr.push_back(llvm::dwarf::DW_OP_deref);
   } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
     // If VD is an anonymous union then Storage represents value for
     // all union fields.
@@ -2899,7 +2888,8 @@
 
         // Insert an llvm.dbg.declare into the current block.
         llvm::Instruction *Call = DBuilder.insertDeclare(
-            Storage, D, DBuilder.createExpression(), Builder.GetInsertBlock());
+            Storage, D, DBuilder.createExpression(Expr),
+            Builder.GetInsertBlock());
         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
       }
       return;
@@ -2913,7 +2903,7 @@
 
   // Insert an llvm.dbg.declare into the current block.
   llvm::Instruction *Call = DBuilder.insertDeclare(
-      Storage, D, DBuilder.createExpression(), Builder.GetInsertBlock());
+      Storage, D, DBuilder.createExpression(Expr), Builder.GetInsertBlock());
   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
 }
 
@@ -3047,7 +3037,7 @@
   const llvm::StructLayout *blockLayout =
       CGM.getDataLayout().getStructLayout(block.StructureType);
 
-  SmallVector<llvm::Value *, 16> fields;
+  SmallVector<llvm::Metadata *, 16> fields;
   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
                                    blockLayout->getElementOffsetInBits(0),
                                    tunit, tunit));
@@ -3181,8 +3171,7 @@
 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
   if (!D->isStaticDataMember())
     return llvm::DIDerivedType();
-  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
-      StaticDataMemberCache.find(D->getCanonicalDecl());
+  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
   if (MI != StaticDataMemberCache.end()) {
     assert(MI->second && "Static data member declaration should still exist");
     return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
@@ -3255,7 +3244,7 @@
         Var->hasInternalLinkage(), Var,
         getOrCreateStaticDataMemberDeclarationOrNull(D));
   }
-  DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
+  DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
 }
 
 /// EmitGlobalVariable - Emit global variable's debug info.
@@ -3291,13 +3280,12 @@
   llvm::DIDescriptor DContext =
       getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
 
-  auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH()));
-  if (!pair.second)
+  auto &GV = DeclCache[VD];
+  if (GV)
     return;
-  llvm::DIGlobalVariable GV = DBuilder.createGlobalVariable(
+  GV.reset(DBuilder.createGlobalVariable(
       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
-      true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD));
-  pair.first->second = llvm::WeakVH(GV);
+      true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
 }
 
 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
@@ -3333,11 +3321,11 @@
 llvm::DIImportedEntity
 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
-    return llvm::DIImportedEntity(nullptr);
-  llvm::WeakVH &VH = NamespaceAliasCache[&NA];
+    return llvm::DIImportedEntity();
+  auto &VH = NamespaceAliasCache[&NA];
   if (VH)
     return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
-  llvm::DIImportedEntity R(nullptr);
+  llvm::DIImportedEntity R;
   if (const NamespaceAliasDecl *Underlying =
           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
     // This could cache & dedup here rather than relying on metadata deduping.
@@ -3350,7 +3338,7 @@
         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
         getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
         getLineNumber(NA.getLocation()), NA.getName());
-  VH = R;
+  VH.reset(R);
   return R;
 }
 
@@ -3359,8 +3347,7 @@
 llvm::DINameSpace
 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
   NSDecl = NSDecl->getCanonicalDecl();
-  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
-    NameSpaceCache.find(NSDecl);
+  auto I = NameSpaceCache.find(NSDecl);
   if (I != NameSpaceCache.end())
     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
 
@@ -3370,7 +3357,7 @@
     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
   llvm::DINameSpace NS =
     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
-  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
+  NameSpaceCache[NSDecl].reset(NS);
   return NS;
 }
 
@@ -3401,19 +3388,19 @@
   for (const auto &p : FwdDeclReplaceMap) {
     assert(p.second);
     llvm::DIDescriptor FwdDecl(cast<llvm::MDNode>(p.second));
-    llvm::WeakVH VH;
+    llvm::Metadata *Repl;
 
     auto it = DeclCache.find(p.first);
-    // If there has been no definition for the declaration, call RAUV
+    // If there has been no definition for the declaration, call RAUW
     // with ourselves, that will destroy the temporary MDNode and
     // replace it with a standard one, avoiding leaking memory.
     if (it == DeclCache.end())
-      VH = p.second;
+      Repl = p.second;
     else
-      VH = it->second;
+      Repl = it->second;
 
     FwdDecl.replaceAllUsesWith(CGM.getLLVMContext(),
-                               llvm::DIDescriptor(cast<llvm::MDNode>(VH)));
+                               llvm::DIDescriptor(cast<llvm::MDNode>(Repl)));
   }
 
   // We keep our own list of retained types, because we need to look
diff --git a/lib/CodeGen/CGDebugInfo.h b/lib/CodeGen/CGDebugInfo.h
index 89d592e..62ba801 100644
--- a/lib/CodeGen/CGDebugInfo.h
+++ b/lib/CodeGen/CGDebugInfo.h
@@ -43,17 +43,17 @@
   class CodeGenFunction;
   class CGBlockInfo;
 
-/// CGDebugInfo - This class gathers all debug information during compilation
+/// \brief This class gathers all debug information during compilation
 /// and is responsible for emitting to llvm globals or pass directly to
 /// the backend.
 class CGDebugInfo {
-  friend class ArtificialLocation;
+  friend class ApplyDebugLocation;
   friend class SaveAndRestoreLocation;
   CodeGenModule &CGM;
   const CodeGenOptions::DebugInfoKind DebugKind;
   llvm::DIBuilder DBuilder;
   llvm::DICompileUnit TheCU;
-  SourceLocation CurLoc, PrevLoc;
+  SourceLocation CurLoc;
   llvm::DIType VTablePtrType;
   llvm::DIType ClassTy;
   llvm::DICompositeType ObjTy;
@@ -64,8 +64,8 @@
   llvm::DIType OCLEventDITy;
   llvm::DIType BlockLiteralGeneric;
 
-  /// TypeCache - Cache of previously constructed Types.
-  llvm::DenseMap<const void *, llvm::WeakVH> TypeCache;
+  /// \brief Cache of previously constructed Types.
+  llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
 
   struct ObjCInterfaceCacheEntry {
     const ObjCInterfaceType *Type;
@@ -76,42 +76,44 @@
         : Type(Type), Decl(Decl), Unit(Unit) {}
   };
 
-  /// ObjCInterfaceCache - Cache of previously constructed interfaces
+  /// \brief Cache of previously constructed interfaces
   /// which may change.
   llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
 
-  /// RetainedTypes - list of interfaces we want to keep even if orphaned.
+  /// \brief list of interfaces we want to keep even if orphaned.
   std::vector<void *> RetainedTypes;
 
-  /// ReplaceMap - Cache of forward declared types to RAUW at the end of
+  /// \brief Cache of forward declared types to RAUW at the end of
   /// compilation.
-  std::vector<std::pair<const TagType *, llvm::WeakVH>> ReplaceMap;
+  std::vector<std::pair<const TagType *, llvm::TrackingMDRef>> ReplaceMap;
 
   /// \brief Cache of replaceable forward declarartions (functions and
   /// variables) to RAUW at the end of compilation.
-  std::vector<std::pair<const DeclaratorDecl *, llvm::WeakVH>> FwdDeclReplaceMap;
+  std::vector<std::pair<const DeclaratorDecl *, llvm::TrackingMDRef>>
+      FwdDeclReplaceMap;
 
   // LexicalBlockStack - Keep track of our current nested lexical block.
-  std::vector<llvm::TrackingVH<llvm::MDNode> > LexicalBlockStack;
-  llvm::DenseMap<const Decl *, llvm::WeakVH> RegionMap;
+  std::vector<llvm::TrackingMDNodeRef> LexicalBlockStack;
+  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> RegionMap;
   // FnBeginRegionCount - Keep track of LexicalBlockStack counter at the
   // beginning of a function. This is used to pop unbalanced regions at
   // the end of a function.
   std::vector<unsigned> FnBeginRegionCount;
 
-  /// DebugInfoNames - This is a storage for names that are
+  /// \brief This is a storage for names that are
   /// constructed on demand. For example, C++ destructors, C++ operators etc..
   llvm::BumpPtrAllocator DebugInfoNames;
   StringRef CWDName;
 
-  llvm::DenseMap<const char *, llvm::WeakVH> DIFileCache;
-  llvm::DenseMap<const FunctionDecl *, llvm::WeakVH> SPCache;
+  llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;
+  llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;
   /// \brief Cache declarations relevant to DW_TAG_imported_declarations (C++
   /// using declarations) that aren't covered by other more specific caches.
-  llvm::DenseMap<const Decl *, llvm::WeakVH> DeclCache;
-  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH> NameSpaceCache;
-  llvm::DenseMap<const NamespaceAliasDecl *, llvm::WeakVH> NamespaceAliasCache;
-  llvm::DenseMap<const Decl *, llvm::WeakVH> StaticDataMemberCache;
+  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;
+  llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NameSpaceCache;
+  llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>
+      NamespaceAliasCache;
+  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> StaticDataMemberCache;
 
   /// Helper functions for getOrCreateType.
   unsigned Checksum(const ObjCInterfaceDecl *InterfaceDecl);
@@ -162,14 +164,12 @@
                                              llvm::DIFile F,
                                              llvm::DIType RecordTy);
 
-  void CollectCXXMemberFunctions(const CXXRecordDecl *Decl,
-                                 llvm::DIFile F,
-                                 SmallVectorImpl<llvm::Value *> &E,
+  void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile F,
+                                 SmallVectorImpl<llvm::Metadata *> &E,
                                  llvm::DIType T);
 
-  void CollectCXXBases(const CXXRecordDecl *Decl,
-                       llvm::DIFile F,
-                       SmallVectorImpl<llvm::Value *> &EltTys,
+  void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile F,
+                       SmallVectorImpl<llvm::Metadata *> &EltTys,
                        llvm::DIType RecordTy);
 
   llvm::DIArray
@@ -192,23 +192,21 @@
 
   // Helpers for collecting fields of a record.
   void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
-                                 SmallVectorImpl<llvm::Value *> &E,
+                                 SmallVectorImpl<llvm::Metadata *> &E,
                                  llvm::DIType RecordTy);
   llvm::DIDerivedType CreateRecordStaticField(const VarDecl *Var,
                                               llvm::DIType RecordTy,
                                               const RecordDecl* RD);
   void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
                                 llvm::DIFile F,
-                                SmallVectorImpl<llvm::Value *> &E,
-                                llvm::DIType RecordTy,
-                                const RecordDecl* RD);
+                                SmallVectorImpl<llvm::Metadata *> &E,
+                                llvm::DIType RecordTy, const RecordDecl *RD);
   void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile F,
-                           SmallVectorImpl<llvm::Value *> &E,
+                           SmallVectorImpl<llvm::Metadata *> &E,
                            llvm::DICompositeType RecordTy);
 
-  void CollectVTableInfo(const CXXRecordDecl *Decl,
-                         llvm::DIFile F,
-                         SmallVectorImpl<llvm::Value *> &EltTys);
+  void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile F,
+                         SmallVectorImpl<llvm::Metadata *> &EltTys);
 
   // CreateLexicalBlock - Create a new lexical block node and push it on
   // the stack.
@@ -220,20 +218,15 @@
 
   void finalize();
 
-  /// setLocation - Update the current source location. If \arg loc is
+  /// \brief Update the current source location. If \arg loc is
   /// invalid it is ignored.
   void setLocation(SourceLocation Loc);
 
-  /// getLocation - Return the current source location.
-  SourceLocation getLocation() const { return CurLoc; }
-
-  /// EmitLocation - Emit metadata to indicate a change in line/column
+  /// \brief Emit metadata to indicate a change in line/column
   /// information in the source file.
-  /// \param ForceColumnInfo  Assume DebugColumnInfo option is true.
-  void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
-                    bool ForceColumnInfo = false);
+  void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
 
-  /// EmitFunctionStart - Emit a call to llvm.dbg.function.start to indicate
+  /// \brief Emit a call to llvm.dbg.function.start to indicate
   /// start of a new function.
   /// \param Loc       The location of the function header.
   /// \param ScopeLoc  The location of the function body.
@@ -242,23 +235,23 @@
                          QualType FnType, llvm::Function *Fn,
                          CGBuilderTy &Builder);
 
-  /// EmitFunctionEnd - Constructs the debug code for exiting a function.
+  /// \brief Constructs the debug code for exiting a function.
   void EmitFunctionEnd(CGBuilderTy &Builder);
 
-  /// EmitLexicalBlockStart - Emit metadata to indicate the beginning of a
+  /// \brief Emit metadata to indicate the beginning of a
   /// new lexical block and push the block onto the stack.
   void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
 
-  /// EmitLexicalBlockEnd - Emit metadata to indicate the end of a new lexical
+  /// \brief Emit metadata to indicate the end of a new lexical
   /// block and pop the current block.
   void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
 
-  /// EmitDeclareOfAutoVariable - Emit call to llvm.dbg.declare for an automatic
+  /// \brief Emit call to llvm.dbg.declare for an automatic
   /// variable declaration.
   void EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,
                                  CGBuilderTy &Builder);
 
-  /// EmitDeclareOfBlockDeclRefVariable - Emit call to llvm.dbg.declare for an
+  /// \brief Emit call to llvm.dbg.declare for an
   /// imported variable declaration in a block.
   void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable,
                                          llvm::Value *storage,
@@ -266,12 +259,12 @@
                                          const CGBlockInfo &blockInfo,
                                          llvm::Instruction *InsertPoint = 0);
 
-  /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
+  /// \brief Emit call to llvm.dbg.declare for an argument
   /// variable declaration.
   void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
                                 unsigned ArgNo, CGBuilderTy &Builder);
 
-  /// EmitDeclareOfBlockLiteralArgVariable - Emit call to
+  /// \brief Emit call to
   /// llvm.dbg.declare for the block-literal argument to a block
   /// invocation function.
   void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
@@ -279,28 +272,28 @@
                                             llvm::Value *LocalAddr,
                                             CGBuilderTy &Builder);
 
-  /// EmitGlobalVariable - Emit information about a global variable.
+  /// \brief Emit information about a global variable.
   void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
 
-  /// EmitGlobalVariable - Emit global variable's debug info.
+  /// \brief Emit global variable's debug info.
   void EmitGlobalVariable(const ValueDecl *VD, llvm::Constant *Init);
 
-  /// \brief - Emit C++ using directive.
+  /// \brief Emit C++ using directive.
   void EmitUsingDirective(const UsingDirectiveDecl &UD);
 
-  /// EmitExplicitCastType - Emit the type explicitly casted to.
+  /// \brief Emit the type explicitly casted to.
   void EmitExplicitCastType(QualType Ty);
 
-  /// \brief - Emit C++ using declaration.
+  /// \brief Emit C++ using declaration.
   void EmitUsingDecl(const UsingDecl &UD);
 
-  /// \brief - Emit C++ namespace alias.
+  /// \brief Emit C++ namespace alias.
   llvm::DIImportedEntity EmitNamespaceAlias(const NamespaceAliasDecl &NA);
 
-  /// getOrCreateRecordType - Emit record type's standalone debug info.
+  /// \brief Emit record type's standalone debug info.
   llvm::DIType getOrCreateRecordType(QualType Ty, SourceLocation L);
 
-  /// getOrCreateInterfaceType - Emit an objective c interface type standalone
+  /// \brief Emit an objective c interface type standalone
   /// debug info.
   llvm::DIType getOrCreateInterfaceType(QualType Ty,
                                         SourceLocation Loc);
@@ -313,18 +306,18 @@
   void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
 
 private:
-  /// EmitDeclare - Emit call to llvm.dbg.declare for a variable declaration.
+  /// \brief Emit call to llvm.dbg.declare for a variable declaration.
   /// Tag accepts custom types DW_TAG_arg_variable and DW_TAG_auto_variable,
   /// otherwise would be of type llvm::dwarf::Tag.
-  void EmitDeclare(const VarDecl *decl, llvm::dwarf::LLVMConstants Tag,
-                   llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder);
+  void EmitDeclare(const VarDecl *decl, llvm::dwarf::Tag Tag, llvm::Value *AI,
+                   unsigned ArgNo, CGBuilderTy &Builder);
 
   // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
   // See BuildByRefType.
   llvm::DIType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
                                             uint64_t *OffSet);
 
-  /// getContextDescriptor - Get context info for the decl.
+  /// \brief Get context info for the decl.
   llvm::DIScope getContextDescriptor(const Decl *Decl);
 
   llvm::DIScope getCurrentContextDescriptor(const Decl *Decl);
@@ -333,38 +326,38 @@
   llvm::DICompositeType getOrCreateRecordFwdDecl(const RecordType *,
                                                  llvm::DIDescriptor);
 
-  /// createContextChain - Create a set of decls for the context chain.
+  /// \brief Create a set of decls for the context chain.
   llvm::DIDescriptor createContextChain(const Decl *Decl);
 
-  /// getCurrentDirname - Return current directory name.
+  /// \brief Return current directory name.
   StringRef getCurrentDirname();
 
-  /// CreateCompileUnit - Create new compile unit.
+  /// \brief Create new compile unit.
   void CreateCompileUnit();
 
-  /// getOrCreateFile - Get the file debug info descriptor for the input
+  /// \brief Get the file debug info descriptor for the input
   /// location.
   llvm::DIFile getOrCreateFile(SourceLocation Loc);
 
-  /// getOrCreateMainFile - Get the file info for main compile unit.
+  /// \brief Get the file info for main compile unit.
   llvm::DIFile getOrCreateMainFile();
 
-  /// getOrCreateType - Get the type from the cache or create a new type if
+  /// \brief Get the type from the cache or create a new type if
   /// necessary.
   llvm::DIType getOrCreateType(QualType Ty, llvm::DIFile Fg);
 
-  /// getOrCreateLimitedType - Get the type from the cache or create a new
+  /// \brief Get the type from the cache or create a new
   /// partial type if necessary.
   llvm::DIType getOrCreateLimitedType(const RecordType *Ty, llvm::DIFile F);
 
-  /// CreateTypeNode - Create type metadata for a source language type.
+  /// \brief Create type metadata for a source language type.
   llvm::DIType CreateTypeNode(QualType Ty, llvm::DIFile Fg);
 
-  /// getObjCInterfaceDecl - return the underlying ObjCInterfaceDecl
+  /// \brief return the underlying ObjCInterfaceDecl
   /// if Ty is an ObjCInterface or a pointer to one.
   ObjCInterfaceDecl* getObjCInterfaceDecl(QualType Ty);
 
-  /// CreateMemberType - Create new member and increase Offset by FType's size.
+  /// \brief Create new member and increase Offset by FType's size.
   llvm::DIType CreateMemberType(llvm::DIFile Unit, QualType FType,
                                 StringRef Name, uint64_t *Offset);
 
@@ -372,7 +365,7 @@
   /// declaration.
   llvm::DIDescriptor getDeclarationOrDefinition(const Decl *D);
 
-  /// getFunctionDeclaration - Return debug info descriptor to describe method
+  /// \brief Return debug info descriptor to describe method
   /// declaration for the given method definition.
   llvm::DISubprogram getFunctionDeclaration(const Decl *D);
 
@@ -396,30 +389,30 @@
                          StringRef LinkageName, llvm::GlobalVariable *Var,
                          llvm::DIDescriptor DContext);
 
-  /// getFunctionName - Get function name for the given FunctionDecl. If the
+  /// \brief Get function name for the given FunctionDecl. If the
   /// name is constructed on demand (e.g. C++ destructor) then the name
   /// is stored on the side.
   StringRef getFunctionName(const FunctionDecl *FD);
 
-  /// getObjCMethodName - Returns the unmangled name of an Objective-C method.
+  /// \brief Returns the unmangled name of an Objective-C method.
   /// This is the display name for the debugging info.
   StringRef getObjCMethodName(const ObjCMethodDecl *FD);
 
-  /// getSelectorName - Return selector name. This is used for debugging
+  /// \brief Return selector name. This is used for debugging
   /// info.
   StringRef getSelectorName(Selector S);
 
-  /// getClassName - Get class name including template argument list.
+  /// \brief Get class name including template argument list.
   StringRef getClassName(const RecordDecl *RD);
 
-  /// getVTableName - Get vtable name for the given Class.
+  /// \brief Get vtable name for the given Class.
   StringRef getVTableName(const CXXRecordDecl *Decl);
 
-  /// getLineNumber - Get line number for the location. If location is invalid
+  /// \brief Get line number for the location. If location is invalid
   /// then use current location.
   unsigned getLineNumber(SourceLocation Loc);
 
-  /// getColumnNumber - Get column number for the location. If location is
+  /// \brief Get column number for the location. If location is
   /// invalid then use current location.
   /// \param Force  Assume DebugColumnInfo option is true.
   unsigned getColumnNumber(SourceLocation Loc, bool Force=false);
@@ -439,7 +432,7 @@
                            StringRef &Name, StringRef &LinkageName,
                            llvm::DIDescriptor &VDContext);
 
-  /// internString - Allocate a copy of \p A using the DebugInfoNames allocator
+  /// \brief Allocate a copy of \p A using the DebugInfoNames allocator
   /// and return a reference to it. If multiple arguments are given the strings
   /// are concatenated.
   StringRef internString(StringRef A, StringRef B = StringRef()) {
@@ -450,50 +443,60 @@
   }
 };
 
-/// SaveAndRestoreLocation - An RAII object saves the current location
-/// and automatically restores it to the original value.
-class SaveAndRestoreLocation {
-protected:
-  SourceLocation SavedLoc;
-  CGDebugInfo *DI;
-  CGBuilderTy &Builder;
+/// \brief A scoped helper to set the current debug location to the specified
+/// location or preferred location of the specified Expr.
+class ApplyDebugLocation {
+private:
+  void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
+  ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
+                     SourceLocation TemporaryLocation);
+
+  llvm::DebugLoc OriginalLocation;
+  CodeGenFunction &CGF;
 public:
-  SaveAndRestoreLocation(CodeGenFunction &CGF, CGBuilderTy &B);
-  /// Autorestore everything back to normal.
-  ~SaveAndRestoreLocation();
-};
 
-/// NoLocation - An RAII object that temporarily disables debug
-/// locations. This is useful for emitting instructions that should be
-/// counted towards the function prologue.
-class NoLocation : public SaveAndRestoreLocation {
-public:
-  NoLocation(CodeGenFunction &CGF, CGBuilderTy &B);
-  /// Autorestore everything back to normal.
-  ~NoLocation();
-};
+  /// \brief Set the location to the (valid) TemporaryLocation.
+  ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
+  ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
+  ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
 
-/// ArtificialLocation - An RAII object that temporarily switches to
-/// an artificial debug location that has a valid scope, but no line
-/// information. This is useful when emitting compiler-generated
-/// helper functions that have no source location associated with
-/// them. The DWARF specification allows the compiler to use the
-/// special line number 0 to indicate code that can not be attributed
-/// to any source location.
-///
-/// This is necessary because passing an empty SourceLocation to
-/// CGDebugInfo::setLocation() will result in the last valid location
-/// being reused.
-class ArtificialLocation : public SaveAndRestoreLocation {
-public:
-  ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B);
+  ~ApplyDebugLocation();
 
-  /// Set the current location to line 0, but within the current scope
-  /// (= the top of the LexicalBlockStack).
-  void Emit();
+  /// \brief Apply TemporaryLocation if it is valid. Otherwise switch to an
+  /// artificial debug location that has a valid scope, but no line information.
+  ///
+  /// Artificial locations are useful when emitting compiler-generated helper
+  /// functions that have no source location associated with them. The DWARF
+  /// specification allows the compiler to use the special line number 0 to
+  /// indicate code that can not be attributed to any source location. Note that
+  /// passing an empty SourceLocation to CGDebugInfo::setLocation() will result
+  /// in the last valid location being reused.
+  static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
+    return ApplyDebugLocation(CGF, false, SourceLocation());
+  }
+  /// \brief Apply TemporaryLocation if it is valid. Otherwise switch to an
+  /// artificial debug location that has a valid scope, but no line information.
+  static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF,
+                                             SourceLocation TemporaryLocation) {
+    return ApplyDebugLocation(CGF, false, TemporaryLocation);
+  }
 
-  /// Autorestore everything back to normal.
-  ~ArtificialLocation();
+  /// \brief Set the IRBuilder to not attach debug locations.  Note that passing
+  /// an empty SourceLocation to CGDebugInfo::setLocation() will result in the
+  /// last valid location being reused.  Note that all instructions that do not
+  /// have a location at the beginning of a function are counted towards to
+  /// funciton prologue.
+  static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
+    return ApplyDebugLocation(CGF, true, SourceLocation());
+  }
+
+  /// \brief Apply TemporaryLocation if it is valid. Otherwise set the IRBuilder
+  /// to not attach debug locations.
+  static ApplyDebugLocation CreateDefaultEmpty(CodeGenFunction &CGF,
+                                             SourceLocation TemporaryLocation) {
+    return ApplyDebugLocation(CGF, true, TemporaryLocation);
+  }
+
 };
 
 
diff --git a/lib/CodeGen/CGDecl.cpp b/lib/CodeGen/CGDecl.cpp
index 959ac9a..fb72a9a 100644
--- a/lib/CodeGen/CGDecl.cpp
+++ b/lib/CodeGen/CGDecl.cpp
@@ -206,6 +206,9 @@
   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
   setGlobalVisibility(GV, &D);
 
+  if (supportsCOMDAT() && GV->isWeakForLinker())
+    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
+
   if (D.getTLSKind())
     setTLSMode(GV, D);
 
@@ -596,10 +599,8 @@
   lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
 }
 
-void CodeGenFunction::EmitScalarInit(const Expr *init,
-                                     const ValueDecl *D,
-                                     LValue lvalue,
-                                     bool capturedByInit) {
+void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
+                                     LValue lvalue, bool capturedByInit) {
   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
   if (!lifetime) {
     llvm::Value *value = EmitScalarExpr(init);
@@ -1089,6 +1090,7 @@
   if (emission.wasEmittedAsGlobal()) return;
 
   const VarDecl &D = *emission.Variable;
+  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
   QualType type = D.getType();
 
   // If this local has an initializer, emit it now.
@@ -1192,10 +1194,8 @@
 /// \param alignment the alignment of the address
 /// \param capturedByInit true if the variable is a __block variable
 ///   whose address is potentially changed by the initializer
-void CodeGenFunction::EmitExprAsInit(const Expr *init,
-                                     const ValueDecl *D,
-                                     LValue lvalue,
-                                     bool capturedByInit) {
+void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
+                                     LValue lvalue, bool capturedByInit) {
   QualType type = D->getType();
 
   if (type->isReferenceType()) {
diff --git a/lib/CodeGen/CGDeclCXX.cpp b/lib/CodeGen/CGDeclCXX.cpp
index e002cdf..9a4303e 100644
--- a/lib/CodeGen/CGDeclCXX.cpp
+++ b/lib/CodeGen/CGDeclCXX.cpp
@@ -141,7 +141,7 @@
 
   if (!T->isReferenceType()) {
     if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
-      (void)CGM.getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
+      (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
           &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
           PerformInit, this);
     if (PerformInit)
@@ -267,15 +267,7 @@
   addUsedGlobal(PtrArray);
 
   // If the GV is already in a comdat group, then we have to join it.
-  llvm::Comdat *C = GV->getComdat();
-
-  // LinkOnce and Weak linkage are lowered down to a single-member comdat group.
-  // Make an explicit group so we can join it.
-  if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) {
-    C = TheModule.getOrInsertComdat(GV->getName());
-    GV->setComdat(C);
-  }
-  if (C)
+  if (llvm::Comdat *C = GV->getComdat())
     PtrArray->setComdat(C);
 }
 
@@ -333,8 +325,9 @@
     AddGlobalCtor(Fn, 65535, COMDATKey);
     DelayedCXXInitPosition.erase(D);
   } else if (D->hasAttr<SelectAnyAttr>()) {
-    // SelectAny globals will be comdat-folded. Put the initializer into a COMDAT
-    // group associated with the global, so the initializers get folded too.
+    // SelectAny globals will be comdat-folded. Put the initializer into a
+    // COMDAT group associated with the global, so the initializers get folded
+    // too.
     AddGlobalCtor(Fn, 65535, COMDATKey);
     DelayedCXXInitPosition.erase(D);
   } else {
@@ -452,6 +445,8 @@
   if (D->hasAttr<NoDebugAttr>())
     DebugInfo = nullptr; // disable debug info indefinitely for this function
 
+  CurEHLocation = D->getLocStart();
+
   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
                 getTypes().arrangeNullaryFunction(),
                 FunctionArgList(), D->getLocation(),
@@ -474,11 +469,11 @@
                                            ArrayRef<llvm::Function *> Decls,
                                            llvm::GlobalVariable *Guard) {
   {
-    ArtificialLocation AL(*this, Builder);
+    auto NL = ApplyDebugLocation::CreateEmpty(*this);
     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
                   getTypes().arrangeNullaryFunction(), FunctionArgList());
     // Emit an artificial location for this function.
-    AL.Emit();
+    auto AL = ApplyDebugLocation::CreateArtificial(*this);
 
     llvm::BasicBlock *ExitBlock = nullptr;
     if (Guard) {
@@ -525,11 +520,11 @@
                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
                                                 &DtorsAndObjects) {
   {
-    ArtificialLocation AL(*this, Builder);
+    auto NL = ApplyDebugLocation::CreateEmpty(*this);
     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
                   getTypes().arrangeNullaryFunction(), FunctionArgList());
     // Emit an artificial location for this function.
-    AL.Emit();
+    auto AL = ApplyDebugLocation::CreateArtificial(*this);
 
     // Emit the dtors, in reverse order from construction.
     for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
@@ -561,6 +556,8 @@
   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
       FTy, "__cxx_global_array_dtor", VD->getLocation());
 
+  CurEHLocation = VD->getLocStart();
+
   StartFunction(VD, getContext().VoidTy, fn, FI, args);
 
   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
diff --git a/lib/CodeGen/CGException.cpp b/lib/CodeGen/CGException.cpp
index 8cd49d1..4e9eb32 100644
--- a/lib/CodeGen/CGException.cpp
+++ b/lib/CodeGen/CGException.cpp
@@ -12,9 +12,11 @@
 //===----------------------------------------------------------------------===//
 
 #include "CodeGenFunction.h"
+#include "CGCXXABI.h"
 #include "CGCleanup.h"
 #include "CGObjCRuntime.h"
 #include "TargetInfo.h"
+#include "clang/AST/Mangle.h"
 #include "clang/AST/StmtCXX.h"
 #include "clang/AST/StmtObjC.h"
 #include "llvm/IR/CallSite.h"
@@ -52,15 +54,6 @@
   return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
 }
 
-static llvm::Constant *getReThrowFn(CodeGenModule &CGM) {
-  // void __cxa_rethrow();
-
-  llvm::FunctionType *FTy =
-    llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
-
-  return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
-}
-
 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
   // void *__cxa_get_exception_ptr(void*);
 
@@ -71,6 +64,9 @@
 }
 
 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
+  if (CGM.getTarget().getCXXABI().isMicrosoft())
+    return CGM.getIntrinsic(llvm::Intrinsic::eh_begincatch);
+
   // void *__cxa_begin_catch(void*);
 
   llvm::FunctionType *FTy =
@@ -80,6 +76,9 @@
 }
 
 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
+  if (CGM.getTarget().getCXXABI().isMicrosoft())
+    return CGM.getIntrinsic(llvm::Intrinsic::eh_endcatch);
+
   // void __cxa_end_catch();
 
   llvm::FunctionType *FTy =
@@ -106,10 +105,14 @@
   StringRef name;
 
   // In C++, use std::terminate().
-  if (CGM.getLangOpts().CPlusPlus)
-    name = "_ZSt9terminatev"; // FIXME: mangling!
-  else if (CGM.getLangOpts().ObjC1 &&
-           CGM.getLangOpts().ObjCRuntime.hasTerminate())
+  if (CGM.getLangOpts().CPlusPlus &&
+      CGM.getTarget().getCXXABI().isItaniumFamily()) {
+    name = "_ZSt9terminatev";
+  } else if (CGM.getLangOpts().CPlusPlus &&
+             CGM.getTarget().getCXXABI().isMicrosoft()) {
+    name = "\01?terminate@@YAXXZ";
+  } else if (CGM.getLangOpts().ObjC1 &&
+             CGM.getLangOpts().ObjCRuntime.hasTerminate())
     name = "objc_terminate";
   else
     name = "abort";
@@ -134,7 +137,12 @@
     // This function must have prototype void(void*).
     const char *CatchallRethrowFn;
 
-    static const EHPersonality &get(CodeGenModule &CGM);
+    static const EHPersonality &get(CodeGenModule &CGM,
+                                    const FunctionDecl *FD);
+    static const EHPersonality &get(CodeGenFunction &CGF) {
+      return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
+    }
+
     static const EHPersonality GNU_C;
     static const EHPersonality GNU_C_SJLJ;
     static const EHPersonality GNU_C_SEH;
@@ -145,6 +153,9 @@
     static const EHPersonality GNU_CPlusPlus;
     static const EHPersonality GNU_CPlusPlus_SJLJ;
     static const EHPersonality GNU_CPlusPlus_SEH;
+    static const EHPersonality MSVC_except_handler;
+    static const EHPersonality MSVC_C_specific_handler;
+    static const EHPersonality MSVC_CxxFrameHandler3;
   };
 }
 
@@ -167,6 +178,12 @@
 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
 const EHPersonality
 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
+const EHPersonality
+EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
+const EHPersonality
+EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
+const EHPersonality
+EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
 
 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
 /// other platforms, unless the user asked for SjLj exceptions.
@@ -239,9 +256,29 @@
   llvm_unreachable("bad runtime kind");
 }
 
-const EHPersonality &EHPersonality::get(CodeGenModule &CGM) {
+static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
+  if (T.getArch() == llvm::Triple::x86)
+    return EHPersonality::MSVC_except_handler;
+  return EHPersonality::MSVC_C_specific_handler;
+}
+
+const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
+                                        const FunctionDecl *FD) {
   const llvm::Triple &T = CGM.getTarget().getTriple();
   const LangOptions &L = CGM.getLangOpts();
+
+  // Try to pick a personality function that is compatible with MSVC if we're
+  // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
+  // the GCC-style personality function.
+  if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
+    if (L.SjLjExceptions)
+      return EHPersonality::GNU_CPlusPlus_SJLJ;
+    else if (FD && FD->usesSEHTry())
+      return getSEHPersonalityMSVC(T);
+    else
+      return EHPersonality::MSVC_CxxFrameHandler3;
+  }
+
   if (L.CPlusPlus && L.ObjC1)
     return getObjCXXPersonality(T, L);
   else if (L.CPlusPlus)
@@ -326,7 +363,7 @@
   if (!LangOpts.ObjCRuntime.isNeXTFamily())
     return;
 
-  const EHPersonality &ObjCXX = EHPersonality::get(*this);
+  const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
   const EHPersonality &CXX =
       getCXXPersonality(getTarget().getTriple(), LangOpts);
   if (&ObjCXX == &CXX)
@@ -423,15 +460,30 @@
   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
 }
 
+llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
+  if (!AbnormalTerminationSlot)
+    AbnormalTerminationSlot =
+        CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
+  return AbnormalTerminationSlot;
+}
+
 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
                                        bool KeepInsertionPoint) {
-  if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
-    ErrorUnsupported(E, "throw expression");
+  if (!E->getSubExpr()) {
+    CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true);
+
+    // throw is an expression, and the expression emitters expect us
+    // to leave ourselves at a valid insertion point.
+    if (KeepInsertionPoint)
+      EmitBlock(createBasicBlock("throw.cont"));
+
     return;
   }
 
-  if (!E->getSubExpr()) {
-    EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM), None);
+  if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
+    // Call std::terminate().
+    llvm::CallInst *TermCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
+    TermCall->setDoesNotReturn();
 
     // throw is an expression, and the expression emitters expect us
     // to leave ourselves at a valid insertion point.
@@ -551,8 +603,9 @@
 
     llvm::Value *zero = CGF.Builder.getInt32(0);
     llvm::Value *failsFilter =
-      CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
-    CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
+        CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
+    CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
+                             CGF.getEHResumeBlock(false));
 
     CGF.EmitBlock(unexpectedBB);
   }
@@ -597,11 +650,6 @@
 }
 
 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
-  if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
-    ErrorUnsupported(&S, "try statement");
-    return;
-  }
-
   EnterCXXTryStmt(S);
   EmitStmt(S.getTryBlock());
   ExitCXXTryStmt(S);
@@ -703,8 +751,15 @@
   assert(EHStack.requiresLandingPad());
   assert(!EHStack.empty());
 
-  if (!CGM.getLangOpts().Exceptions)
-    return nullptr;
+  // If exceptions are disabled, there are usually no landingpads. However, when
+  // SEH is enabled, functions using SEH still get landingpads.
+  const LangOptions &LO = CGM.getLangOpts();
+  if (!LO.Exceptions) {
+    if (!LO.Borland && !LO.MicrosoftExt)
+      return nullptr;
+    if (!currentFunctionUsesSEHTry())
+      return nullptr;
+  }
 
   // Check the innermost scope for a cached landing pad.  If this is
   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
@@ -742,18 +797,16 @@
 
   // Save the current IR generation state.
   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
-  SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
-  if (CGDebugInfo *DI = getDebugInfo())
-    DI->EmitLocation(Builder, CurEHLocation);
+  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
 
-  const EHPersonality &personality = EHPersonality::get(CGM);
+  const EHPersonality &personality = EHPersonality::get(*this);
 
   // Create and configure the landing pad.
   llvm::BasicBlock *lpad = createBasicBlock("lpad");
   EmitBlock(lpad);
 
   llvm::LandingPadInst *LPadInst =
-    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
+    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
                              getOpaquePersonalityFn(CGM, personality), 0);
 
   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
@@ -772,8 +825,8 @@
   bool hasFilter = false;
   SmallVector<llvm::Value*, 4> filterTypes;
   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
-  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
-         I != E; ++I) {
+  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
+       ++I) {
 
     switch (I->getKind()) {
     case EHScope::Cleanup:
@@ -1281,7 +1334,7 @@
     // constructor function-try-block's catch handler (p14), so this
     // really only applies to destructors.
     if (doImplicitRethrow && HaveInsertPoint()) {
-      EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
+      CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
       Builder.CreateUnreachable();
       Builder.ClearInsertionPoint();
     }
@@ -1525,6 +1578,8 @@
     // we don't want it to turn into an exported symbol.
     fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
     fn->setVisibility(llvm::Function::HiddenVisibility);
+    if (CGM.supportsCOMDAT())
+      fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
 
     // Set up the function.
     llvm::BasicBlock *entry =
@@ -1563,9 +1618,9 @@
   Builder.SetInsertPoint(TerminateLandingPad);
 
   // Tell the backend that this is a landing pad.
-  const EHPersonality &Personality = EHPersonality::get(CGM);
+  const EHPersonality &Personality = EHPersonality::get(*this);
   llvm::LandingPadInst *LPadInst =
-    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
+    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
                              getOpaquePersonalityFn(CGM, Personality), 0);
   LPadInst->addClause(getCatchAllValue(*this));
 
@@ -1622,15 +1677,14 @@
   EHResumeBlock = createBasicBlock("eh.resume");
   Builder.SetInsertPoint(EHResumeBlock);
 
-  const EHPersonality &Personality = EHPersonality::get(CGM);
+  const EHPersonality &Personality = EHPersonality::get(*this);
 
   // This can always be a call because we necessarily didn't find
   // anything on the EH stack which needs our help.
   const char *RethrowName = Personality.CatchallRethrowFn;
   if (RethrowName != nullptr && !isCleanup) {
     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
-                    getExceptionFromSlot())
-      ->setDoesNotReturn();
+                    getExceptionFromSlot())->setDoesNotReturn();
     Builder.CreateUnreachable();
     Builder.restoreIP(SavedIP);
     return EHResumeBlock;
@@ -1641,7 +1695,7 @@
   llvm::Value *Sel = getSelectorFromSlot();
 
   llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
-                                               Sel->getType(), NULL);
+                                               Sel->getType(), nullptr);
   llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
   LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
   LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
@@ -1652,9 +1706,307 @@
 }
 
 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
-  CGM.ErrorUnsupported(&S, "SEH __try");
+  // FIXME: Implement SEH on other architectures.
+  const llvm::Triple &T = CGM.getTarget().getTriple();
+  if (T.getArch() != llvm::Triple::x86_64 ||
+      !T.isKnownWindowsMSVCEnvironment()) {
+    ErrorUnsupported(&S, "__try statement");
+    return;
+  }
+
+  SEHFinallyInfo FI;
+  EnterSEHTryStmt(S, FI);
+  {
+    JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
+
+    SEHTryEpilogueStack.push_back(&TryExit);
+    EmitStmt(S.getTryBlock());
+    SEHTryEpilogueStack.pop_back();
+
+    if (!TryExit.getBlock()->use_empty())
+      EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
+    else
+      delete TryExit.getBlock();
+  }
+  ExitSEHTryStmt(S, FI);
+}
+
+namespace {
+struct PerformSEHFinally : EHScopeStack::Cleanup  {
+  CodeGenFunction::SEHFinallyInfo *FI;
+  PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
+
+  void Emit(CodeGenFunction &CGF, Flags F) override {
+    // Cleanups are emitted at most twice: once for normal control flow and once
+    // for exception control flow. Branch into the finally block, and remember
+    // the continuation block so we can branch out later.
+    if (!FI->FinallyBB) {
+      FI->FinallyBB = CGF.createBasicBlock("__finally");
+      FI->FinallyBB->insertInto(CGF.CurFn);
+      FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
+    }
+
+    // Set the termination status and branch in.
+    CGF.Builder.CreateStore(
+        llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
+        CGF.getAbnormalTerminationSlot());
+    CGF.Builder.CreateBr(FI->FinallyBB);
+
+    // Create a continuation block for normal or exceptional control.
+    if (F.isForEHCleanup()) {
+      assert(!FI->ResumeBB && "double emission for EH");
+      FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
+      CGF.EmitBlock(FI->ResumeBB);
+    } else {
+      assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
+      FI->ContBB = CGF.createBasicBlock("__finally.cont");
+      CGF.EmitBlock(FI->ContBB);
+      // Try to keep source order.
+      FI->ContBB->moveAfter(FI->FinallyBB);
+    }
+  }
+};
+}
+
+/// Create a stub filter function that will ultimately hold the code of the
+/// filter expression. The EH preparation passes in LLVM will outline the code
+/// from the main function body into this stub.
+llvm::Function *
+CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
+                                           const SEHExceptStmt &Except) {
+  const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
+  llvm::Function *ParentFn = ParentCGF.CurFn;
+
+  Expr *FilterExpr = Except.getFilterExpr();
+
+  // Get the mangled function name.
+  SmallString<128> Name;
+  {
+    llvm::raw_svector_ostream OS(Name);
+    const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
+    assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
+    CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
+  }
+
+  // Arrange a function with the declaration:
+  // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
+  QualType RetTy = getContext().IntTy;
+  FunctionArgList Args;
+  SEHPointersDecl = ImplicitParamDecl::Create(
+      getContext(), nullptr, FilterExpr->getLocStart(),
+      &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
+  Args.push_back(SEHPointersDecl);
+  Args.push_back(ImplicitParamDecl::Create(
+      getContext(), nullptr, FilterExpr->getLocStart(),
+      &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
+  const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
+      RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
+  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
+  llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
+                                              Name.str(), &CGM.getModule());
+  // The filter is either in the same comdat as the function, or it's internal.
+  if (llvm::Comdat *C = ParentFn->getComdat()) {
+    Fn->setComdat(C);
+  } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
+    // FIXME: Unreachable with Rafael's changes?
+    llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
+    ParentFn->setComdat(C);
+    Fn->setComdat(C);
+  } else {
+    Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
+  }
+
+  StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
+                FilterExpr->getLocStart(), FilterExpr->getLocStart());
+
+  EmitSEHExceptionCodeSave();
+
+  // Insert dummy allocas for every local variable in scope. We'll initialize
+  // them and prune the unused ones after we find out which ones were
+  // referenced.
+  for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
+    const Decl *VD = DeclPtrs.first;
+    llvm::Value *Ptr = DeclPtrs.second;
+    auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
+    LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
+  }
+
+  // Emit the original filter expression, convert to i32, and return.
+  llvm::Value *R = EmitScalarExpr(FilterExpr);
+  R = Builder.CreateIntCast(R, CGM.IntTy,
+                            FilterExpr->getType()->isSignedIntegerType());
+  Builder.CreateStore(R, ReturnValue);
+
+  FinishFunction(FilterExpr->getLocEnd());
+
+  for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
+    const Decl *VD = DeclPtrs.first;
+    auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
+    if (Alloca->hasNUses(0)) {
+      Alloca->eraseFromParent();
+      continue;
+    }
+    ErrorUnsupported(FilterExpr,
+                     "SEH filter expression local variable capture");
+  }
+
+  return Fn;
+}
+
+void CodeGenFunction::EmitSEHExceptionCodeSave() {
+  // Save the exception code in the exception slot to unify exception access in
+  // the filter function and the landing pad.
+  // struct EXCEPTION_POINTERS {
+  //   EXCEPTION_RECORD *ExceptionRecord;
+  //   CONTEXT *ContextRecord;
+  // };
+  // void *exn.slot =
+  //     (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
+  llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
+  llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
+  llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
+  Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
+  llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
+  Rec = Builder.CreateLoad(Rec);
+  llvm::Value *Code = Builder.CreateLoad(Rec);
+  Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
+  // FIXME: Change landing pads to produce {i32, i32} and make the exception
+  // slot an i32.
+  Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
+  Builder.CreateStore(Code, getExceptionSlot());
+}
+
+llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
+  // Sema should diagnose calling this builtin outside of a filter context, but
+  // don't crash if we screw up.
+  if (!SEHPointersDecl)
+    return llvm::UndefValue::get(Int8PtrTy);
+  return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
+}
+
+llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
+  // If we're in a landing pad or filter function, the exception slot contains
+  // the code.
+  assert(ExceptionSlot);
+  llvm::Value *Code =
+      Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
+  return Builder.CreateTrunc(Code, CGM.Int32Ty);
+}
+
+llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
+  // Load from the abnormal termination slot. It will be uninitialized outside
+  // of __finally blocks, which we should warn or error on.
+  llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
+  return Builder.CreateZExt(IsEH, Int32Ty);
+}
+
+void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
+  if (S.getFinallyHandler()) {
+    // Push a cleanup for __finally blocks.
+    EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
+    return;
+  }
+
+  // Otherwise, we must have an __except block.
+  SEHExceptStmt *Except = S.getExceptHandler();
+  assert(Except);
+  EHCatchScope *CatchScope = EHStack.pushCatch(1);
+
+  // If the filter is known to evaluate to 1, then we can use the clause "catch
+  // i8* null".
+  llvm::Constant *C =
+      CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
+  if (C && C->isOneValue()) {
+    CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
+    return;
+  }
+
+  // In general, we have to emit an outlined filter function. Use the function
+  // in place of the RTTI typeinfo global that C++ EH uses.
+  CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
+  llvm::Function *FilterFunc =
+      FilterCGF.GenerateSEHFilterFunction(*this, *Except);
+  llvm::Constant *OpaqueFunc =
+      llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
+  CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
+}
+
+void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
+  // Just pop the cleanup if it's a __finally block.
+  if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
+    PopCleanupBlock();
+    assert(FI.ContBB && "did not emit normal cleanup");
+
+    // Emit the code into FinallyBB.
+    CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
+    Builder.SetInsertPoint(FI.FinallyBB);
+    EmitStmt(Finally->getBlock());
+
+    if (HaveInsertPoint()) {
+      if (FI.ResumeBB) {
+        llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
+                                               "abnormal.termination");
+        IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
+        Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
+      } else {
+        // There was nothing exceptional in the try body, so we only have normal
+        // control flow.
+        Builder.CreateBr(FI.ContBB);
+      }
+    }
+
+    Builder.restoreIP(SavedIP);
+
+    return;
+  }
+
+  // Otherwise, we must have an __except block.
+  const SEHExceptStmt *Except = S.getExceptHandler();
+  assert(Except && "__try must have __finally xor __except");
+  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
+
+  // Don't emit the __except block if the __try block lacked invokes.
+  // TODO: Model unwind edges from instructions, either with iload / istore or
+  // a try body function.
+  if (!CatchScope.hasEHBranches()) {
+    CatchScope.clearHandlerBlocks();
+    EHStack.popCatch();
+    return;
+  }
+
+  // The fall-through block.
+  llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
+
+  // We just emitted the body of the __try; jump to the continue block.
+  if (HaveInsertPoint())
+    Builder.CreateBr(ContBB);
+
+  // Check if our filter function returned true.
+  emitCatchDispatchBlock(*this, CatchScope);
+
+  // Grab the block before we pop the handler.
+  llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
+  EHStack.popCatch();
+
+  EmitBlockAfterUses(ExceptBB);
+
+  // Emit the __except body.
+  EmitStmt(Except->getBlock());
+
+  if (HaveInsertPoint())
+    Builder.CreateBr(ContBB);
+
+  EmitBlock(ContBB);
 }
 
 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
-  CGM.ErrorUnsupported(&S, "SEH __leave");
+  // If this code is reachable then emit a stop point (if generating
+  // debug info). We have to do this ourselves because we are on the
+  // "simple" statement path.
+  if (HaveInsertPoint())
+    EmitStopPoint(&S);
+
+  assert(!SEHTryEpilogueStack.empty() &&
+         "sema should have rejected this __leave");
+  EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
 }
diff --git a/lib/CodeGen/CGExpr.cpp b/lib/CodeGen/CGExpr.cpp
index 1a3a61a..78e80a1 100644
--- a/lib/CodeGen/CGExpr.cpp
+++ b/lib/CodeGen/CGExpr.cpp
@@ -21,8 +21,8 @@
 #include "CodeGenModule.h"
 #include "TargetInfo.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/DeclObjC.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/Frontend/CodeGenOptions.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/StringExtras.h"
@@ -807,6 +807,7 @@
 /// length type, this is not possible.
 ///
 LValue CodeGenFunction::EmitLValue(const Expr *E) {
+  ApplyDebugLocation DL(*this, E);
   switch (E->getStmtClass()) {
   default: return EmitUnsupportedLValue(E, "l-value expression");
 
@@ -819,10 +820,14 @@
     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
   case Expr::BinaryOperatorClass:
     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
-  case Expr::CompoundAssignOperatorClass:
-    if (!E->getType()->isAnyComplexType())
+  case Expr::CompoundAssignOperatorClass: {
+    QualType Ty = E->getType();
+    if (const AtomicType *AT = Ty->getAs<AtomicType>())
+      Ty = AT->getValueType();
+    if (!Ty->isAnyComplexType())
       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
+  }
   case Expr::CallExprClass:
   case Expr::CXXMemberCallExprClass:
   case Expr::CXXOperatorCallExprClass:
@@ -1135,7 +1140,7 @@
   }
 
   // Atomic operations have to be done on integral types.
-  if (Ty->isAtomicType()) {
+  if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
     LValue lvalue = LValue::MakeAddr(Addr, Ty,
                                      CharUnits::fromQuantity(Alignment),
                                      getContext(), TBAAInfo);
@@ -1254,7 +1259,8 @@
 
   Value = EmitToMemory(Value, Ty);
 
-  if (Ty->isAtomicType()) {
+  if (Ty->isAtomicType() ||
+      (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
     EmitAtomicStore(RValue::get(Value),
                     LValue::MakeAddr(Addr, Ty,
                                      CharUnits::fromQuantity(Alignment),
@@ -1415,8 +1421,8 @@
 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
          "Bad type for register variable");
-  llvm::MDNode *RegName = dyn_cast<llvm::MDNode>(LV.getGlobalReg());
-  assert(RegName && "Register LValue is not metadata");
+  llvm::MDNode *RegName = cast<llvm::MDNode>(
+      cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
 
   // We accept integer and pointer types only
   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
@@ -1426,7 +1432,8 @@
   llvm::Type *Types[] = { Ty };
 
   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
-  llvm::Value *Call = Builder.CreateCall(F, RegName);
+  llvm::Value *Call = Builder.CreateCall(
+      F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
   if (OrigTy->isPointerTy())
     Call = Builder.CreateIntToPtr(Call, OrigTy);
   return RValue::get(Call);
@@ -1676,7 +1683,8 @@
 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
          "Bad type for register variable");
-  llvm::MDNode *RegName = dyn_cast<llvm::MDNode>(Dst.getGlobalReg());
+  llvm::MDNode *RegName = cast<llvm::MDNode>(
+      cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
   assert(RegName && "Register LValue is not metadata");
 
   // We accept integer and pointer types only
@@ -1690,7 +1698,8 @@
   llvm::Value *Value = Src.getScalarVal();
   if (OrigTy->isPointerTy())
     Value = Builder.CreatePtrToInt(Value, Ty);
-  Builder.CreateCall2(F, RegName, Value);
+  Builder.CreateCall2(F, llvm::MetadataAsValue::get(Ty->getContext(), RegName),
+                      Value);
 }
 
 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
@@ -1804,7 +1813,7 @@
 static LValue EmitThreadPrivateVarDeclLValue(
     CodeGenFunction &CGF, const VarDecl *VD, QualType T, llvm::Value *V,
     llvm::Type *RealVarTy, CharUnits Alignment, SourceLocation Loc) {
-  V = CGF.CGM.getOpenMPRuntime().getOMPAddrOfThreadPrivate(CGF, VD, V, Loc);
+  V = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, V, Loc);
   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
   return CGF.MakeAddrLValue(V, T, Alignment);
 }
@@ -1885,10 +1894,12 @@
   if (M->getNumOperands() == 0) {
     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
                                               Asm->getLabel());
-    llvm::Value *Ops[] = { Str };
+    llvm::Metadata *Ops[] = {Str};
     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
   }
-  return LValue::MakeGlobalReg(M->getOperand(0), VD->getType(), Alignment);
+  return LValue::MakeGlobalReg(
+      llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)),
+      VD->getType(), Alignment);
 }
 
 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
@@ -1914,6 +1925,22 @@
       // FIXME: Eventually we will want to emit vector element references.
       return MakeAddrLValue(Val, T, Alignment);
     }
+
+    // Check for captured variables.
+    if (E->refersToEnclosingVariableOrCapture()) {
+      if (auto *FD = LambdaCaptureFields.lookup(VD))
+        return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
+      else if (CapturedStmtInfo) {
+        if (auto *V = LocalDeclMap.lookup(VD))
+          return MakeAddrLValue(V, T, Alignment);
+        else
+          return EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
+                                         CapturedStmtInfo->getContextValue());
+      }
+      assert(isa<BlockDecl>(CurCodeDecl));
+      return MakeAddrLValue(GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()),
+                            T, Alignment);
+    }
   }
 
   // FIXME: We should be able to assert this for FunctionDecls as well!
@@ -1947,21 +1974,6 @@
           *this, VD, T, V, getTypes().ConvertTypeForMem(VD->getType()),
           Alignment, E->getExprLoc());
 
-    // Use special handling for lambdas.
-    if (!V) {
-      if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
-        return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
-      } else if (CapturedStmtInfo) {
-        if (const FieldDecl *FD = CapturedStmtInfo->lookup(VD))
-          return EmitCapturedFieldLValue(*this, FD,
-                                         CapturedStmtInfo->getContextValue());
-      }
-
-      assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
-      return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
-                            T, Alignment);
-    }
-
     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
 
     if (isBlockVariable)
@@ -2201,9 +2213,10 @@
 namespace {
 /// \brief Specify under what conditions this check can be recovered
 enum class CheckRecoverableKind {
-  /// Always terminate program execution if this check fails
+  /// Always terminate program execution if this check fails.
   Unrecoverable,
-  /// Check supports recovering, allows user to specify which
+  /// Check supports recovering, runtime has both fatal (noreturn) and
+  /// non-fatal handlers for this check.
   Recoverable,
   /// Runtime conditionally aborts, always need to support recovery.
   AlwaysRecoverable
@@ -2222,42 +2235,95 @@
   }
 }
 
+static void emitCheckHandlerCall(CodeGenFunction &CGF,
+                                 llvm::FunctionType *FnType,
+                                 ArrayRef<llvm::Value *> FnArgs,
+                                 StringRef CheckName,
+                                 CheckRecoverableKind RecoverKind, bool IsFatal,
+                                 llvm::BasicBlock *ContBB) {
+  assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
+  bool NeedsAbortSuffix =
+      IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
+  std::string FnName = ("__ubsan_handle_" + CheckName +
+                        (NeedsAbortSuffix ? "_abort" : "")).str();
+  bool MayReturn =
+      !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
+
+  llvm::AttrBuilder B;
+  if (!MayReturn) {
+    B.addAttribute(llvm::Attribute::NoReturn)
+        .addAttribute(llvm::Attribute::NoUnwind);
+  }
+  B.addAttribute(llvm::Attribute::UWTable);
+
+  llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
+      FnType, FnName,
+      llvm::AttributeSet::get(CGF.getLLVMContext(),
+                              llvm::AttributeSet::FunctionIndex, B));
+  llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
+  if (!MayReturn) {
+    HandlerCall->setDoesNotReturn();
+    CGF.Builder.CreateUnreachable();
+  } else {
+    CGF.Builder.CreateBr(ContBB);
+  }
+}
+
 void CodeGenFunction::EmitCheck(
     ArrayRef<std::pair<llvm::Value *, SanitizerKind>> Checked,
     StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
     ArrayRef<llvm::Value *> DynamicArgs) {
   assert(IsSanitizerScope);
   assert(Checked.size() > 0);
-  llvm::Value *Cond = Checked[0].first;
+
+  llvm::Value *FatalCond = nullptr;
+  llvm::Value *RecoverableCond = nullptr;
+  for (int i = 0, n = Checked.size(); i < n; ++i) {
+    llvm::Value *Check = Checked[i].first;
+    llvm::Value *&Cond =
+        CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
+            ? RecoverableCond
+            : FatalCond;
+    Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
+  }
+
+  llvm::Value *JointCond;
+  if (FatalCond && RecoverableCond)
+    JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
+  else
+    JointCond = FatalCond ? FatalCond : RecoverableCond;
+  assert(JointCond);
+
   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
   assert(SanOpts.has(Checked[0].second));
+#ifndef NDEBUG
   for (int i = 1, n = Checked.size(); i < n; ++i) {
-    Cond = Builder.CreateAnd(Cond, Checked[i].first);
     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
            "All recoverable kinds in a single check must be same!");
     assert(SanOpts.has(Checked[i].second));
   }
+#endif
 
   if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
-    assert (RecoverKind != CheckRecoverableKind::AlwaysRecoverable &&
-            "Runtime call required for AlwaysRecoverable kind!");
-    return EmitTrapCheck(Cond);
+    assert(RecoverKind != CheckRecoverableKind::AlwaysRecoverable &&
+           "Runtime call required for AlwaysRecoverable kind!");
+    // Assume that -fsanitize-undefined-trap-on-error overrides
+    // -fsanitize-recover= options, as we can only print meaningful error
+    // message and recover if we have a runtime support.
+    return EmitTrapCheck(JointCond);
   }
 
   llvm::BasicBlock *Cont = createBasicBlock("cont");
-
-  llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
-
-  llvm::Instruction *Branch = Builder.CreateCondBr(Cond, Cont, Handler);
-
+  llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
+  llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
   // Give hint that we very much don't expect to execute the handler
   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
   llvm::MDBuilder MDHelper(getLLVMContext());
   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
+  EmitBlock(Handlers);
 
-  EmitBlock(Handler);
-
+  // Emit handler arguments and create handler function type.
   llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
   auto *InfoPtr =
       new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
@@ -2280,34 +2346,27 @@
     ArgTypes.push_back(IntPtrTy);
   }
 
-  bool Recover = RecoverKind == CheckRecoverableKind::AlwaysRecoverable ||
-                 (RecoverKind == CheckRecoverableKind::Recoverable &&
-                  CGM.getCodeGenOpts().SanitizeRecover);
-
   llvm::FunctionType *FnType =
     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
-  llvm::AttrBuilder B;
-  if (!Recover) {
-    B.addAttribute(llvm::Attribute::NoReturn)
-     .addAttribute(llvm::Attribute::NoUnwind);
-  }
-  B.addAttribute(llvm::Attribute::UWTable);
 
-  // Checks that have two variants use a suffix to differentiate them
-  bool NeedsAbortSuffix = RecoverKind != CheckRecoverableKind::Unrecoverable &&
-                          !CGM.getCodeGenOpts().SanitizeRecover;
-  std::string FunctionName = ("__ubsan_handle_" + CheckName +
-                              (NeedsAbortSuffix? "_abort" : "")).str();
-  llvm::Value *Fn = CGM.CreateRuntimeFunction(
-      FnType, FunctionName,
-      llvm::AttributeSet::get(getLLVMContext(),
-                              llvm::AttributeSet::FunctionIndex, B));
-  llvm::CallInst *HandlerCall = EmitNounwindRuntimeCall(Fn, Args);
-  if (Recover) {
-    Builder.CreateBr(Cont);
+  if (!FatalCond || !RecoverableCond) {
+    // Simple case: we need to generate a single handler call, either
+    // fatal, or non-fatal.
+    emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
+                         (FatalCond != nullptr), Cont);
   } else {
-    HandlerCall->setDoesNotReturn();
-    Builder.CreateUnreachable();
+    // Emit two handler calls: first one for set of unrecoverable checks,
+    // another one for recoverable.
+    llvm::BasicBlock *NonFatalHandlerBB =
+        createBasicBlock("non_fatal." + CheckName);
+    llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
+    Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
+    EmitBlock(FatalHandlerBB);
+    emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
+                         NonFatalHandlerBB);
+    EmitBlock(NonFatalHandlerBB);
+    emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
+                         Cont);
   }
 
   EmitBlock(Cont);
@@ -3006,19 +3065,6 @@
 
 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
                                      ReturnValueSlot ReturnValue) {
-  if (CGDebugInfo *DI = getDebugInfo()) {
-    SourceLocation Loc = E->getLocStart();
-    // Force column info to be generated so we can differentiate
-    // multiple call sites on the same line in the debug info.
-    // FIXME: This is insufficient. Two calls coming from the same macro
-    // expansion will still get the same line/column and break debug info. It's
-    // possible that LLVM can be fixed to not rely on this uniqueness, at which
-    // point this workaround can be removed.
-    const FunctionDecl* Callee = E->getDirectCallee();
-    bool ForceColumnInfo = Callee && Callee->isInlineSpecified();
-    DI->EmitLocation(Builder, Loc, ForceColumnInfo);
-  }
-
   // Builtins never have block type.
   if (E->getCallee()->getType()->isBlockPointerType())
     return EmitBlockCallExpr(E, ReturnValue);
@@ -3032,7 +3078,7 @@
   const Decl *TargetDecl = E->getCalleeDecl();
   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
     if (unsigned builtinID = FD->getBuiltinID())
-      return EmitBuiltinExpr(FD, builtinID, E);
+      return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
   }
 
   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
@@ -3152,7 +3198,7 @@
   if (!RV.isScalar())
     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
 
-  assert(E->getCallReturnType()->isReferenceType() &&
+  assert(E->getCallReturnType(getContext())->isReferenceType() &&
          "Can't have a scalar return unless the return type is a "
          "reference type!");
 
@@ -3267,7 +3313,7 @@
 
 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
                                  const CallExpr *E, ReturnValueSlot ReturnValue,
-                                 const Decl *TargetDecl) {
+                                 const Decl *TargetDecl, llvm::Value *Chain) {
   // Get the actual function type. The callee type will always be a pointer to
   // function type or a block pointer type.
   assert(CalleeType->isFunctionPointerType() &&
@@ -3278,16 +3324,6 @@
   const auto *FnType =
       cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
 
-  // Force column info to differentiate multiple inlined call sites on
-  // the same line, analoguous to EmitCallExpr.
-  // FIXME: This is insufficient. Two calls coming from the same macro expansion
-  // will still get the same line/column and break debug info. It's possible
-  // that LLVM can be fixed to not rely on this uniqueness, at which point this
-  // workaround can be removed.
-  bool ForceColumnInfo = false;
-  if (const FunctionDecl* FD = dyn_cast_or_null<const FunctionDecl>(TargetDecl))
-    ForceColumnInfo = FD->isInlineSpecified();
-
   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
     if (llvm::Constant *PrefixSig =
@@ -3332,12 +3368,14 @@
   }
 
   CallArgList Args;
+  if (Chain)
+    Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
+             CGM.getContext().VoidPtrTy);
   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arg_begin(),
-               E->arg_end(), E->getDirectCallee(), /*ParamsToSkip*/ 0,
-               ForceColumnInfo);
+               E->arg_end(), E->getDirectCallee(), /*ParamsToSkip*/ 0);
 
-  const CGFunctionInfo &FnInfo =
-    CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
+  const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
+      Args, FnType, /*isChainCall=*/Chain);
 
   // C99 6.5.2.2p6:
   //   If the expression that denotes the called function has a type
@@ -3356,7 +3394,10 @@
   // through an unprototyped function type works like a *non-variadic*
   // call.  The way we make this work is to cast to the exact type
   // of the promoted arguments.
-  if (isa<FunctionNoProtoType>(FnType)) {
+  //
+  // Chain calls use this same code path to add the invisible chain parameter
+  // to the function type.
+  if (isa<FunctionNoProtoType>(FnType) || Chain) {
     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
     CalleeTy = CalleeTy->getPointerTo();
     Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
diff --git a/lib/CodeGen/CGExprAgg.cpp b/lib/CodeGen/CGExprAgg.cpp
index 4cf94c0..5b0d9f0 100644
--- a/lib/CodeGen/CGExprAgg.cpp
+++ b/lib/CodeGen/CGExprAgg.cpp
@@ -98,6 +98,11 @@
   //                            Visitor Methods
   //===--------------------------------------------------------------------===//
 
+  void Visit(Expr *E) {
+    ApplyDebugLocation DL(CGF, E);
+    StmtVisitor<AggExprEmitter>::Visit(E);
+  }
+
   void VisitStmt(Stmt *S) {
     CGF.ErrorUnsupported(S, "aggregate expression");
   }
@@ -207,7 +212,7 @@
   LValue LV = CGF.EmitLValue(E);
 
   // If the type of the l-value is atomic, then do an atomic load.
-  if (LV.getType()->isAtomicType()) {
+  if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
     CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
     return;
   }
@@ -736,7 +741,7 @@
 }
 
 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
-  if (E->getCallReturnType()->isReferenceType()) {
+  if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
     EmitAggLoadOfLValue(E);
     return;
   }
@@ -860,7 +865,8 @@
     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
 
     // That copy is an atomic copy if the LHS is atomic.
-    if (LHS.getType()->isAtomicType()) {
+    if (LHS.getType()->isAtomicType() ||
+        CGF.LValueIsSuitableForInlineAtomic(LHS)) {
       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
       return;
     }
@@ -877,7 +883,8 @@
 
   // If we have an atomic type, evaluate into the destination and then
   // do an atomic copy.
-  if (LHS.getType()->isAtomicType()) {
+  if (LHS.getType()->isAtomicType() ||
+      CGF.LValueIsSuitableForInlineAtomic(LHS)) {
     EnsureDest(E->getRHS()->getType());
     Visit(E->getRHS());
     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
diff --git a/lib/CodeGen/CGExprCXX.cpp b/lib/CodeGen/CGExprCXX.cpp
index 39c77eb..425a968 100644
--- a/lib/CodeGen/CGExprCXX.cpp
+++ b/lib/CodeGen/CGExprCXX.cpp
@@ -120,9 +120,23 @@
                     ReturnValue);
   }
 
-  // Compute the object pointer.
+  bool HasQualifier = ME->hasQualifier();
+  NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
+  bool IsArrow = ME->isArrow();
   const Expr *Base = ME->getBase();
-  bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
+
+  return EmitCXXMemberOrOperatorMemberCallExpr(
+      CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
+}
+
+RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
+    const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
+    bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
+    const Expr *Base) {
+  assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
+
+  // Compute the object pointer.
+  bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
 
   const CXXMethodDecl *DevirtualizedMethod = nullptr;
   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
@@ -153,7 +167,7 @@
   }
 
   llvm::Value *This;
-  if (ME->isArrow())
+  if (IsArrow)
     This = EmitScalarExpr(Base);
   else
     This = EmitLValue(Base).getAddress();
@@ -165,32 +179,38 @@
         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
       return RValue::get(nullptr);
 
-    if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
-      // We don't like to generate the trivial copy/move assignment operator
-      // when it isn't necessary; just produce the proper effect here.
-      llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
-      EmitAggregateAssign(This, RHS, CE->getType());
-      return RValue::get(This);
-    }
+    if (!MD->getParent()->mayInsertExtraPadding()) {
+      if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
+        // We don't like to generate the trivial copy/move assignment operator
+        // when it isn't necessary; just produce the proper effect here.
+        // Special case: skip first argument of CXXOperatorCall (it is "this").
+        unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
+        llvm::Value *RHS =
+            EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
+        EmitAggregateAssign(This, RHS, CE->getType());
+        return RValue::get(This);
+      }
 
-    if (isa<CXXConstructorDecl>(MD) &&
-        cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
-      // Trivial move and copy ctor are the same.
-      assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
-      llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
-      EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
-      return RValue::get(This);
+      if (isa<CXXConstructorDecl>(MD) &&
+          cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
+        // Trivial move and copy ctor are the same.
+        assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
+        llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
+        EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
+        return RValue::get(This);
+      }
+      llvm_unreachable("unknown trivial member function");
     }
-    llvm_unreachable("unknown trivial member function");
   }
 
   // Compute the function type we're calling.
-  const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
+  const CXXMethodDecl *CalleeDecl =
+      DevirtualizedMethod ? DevirtualizedMethod : MD;
   const CGFunctionInfo *FInfo = nullptr;
-  if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
+  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
         Dtor, StructorType::Complete);
-  else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
+  else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
         Ctor, StructorType::Complete);
   else
@@ -212,13 +232,11 @@
            "Destructor shouldn't have explicit parameters");
     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
     if (UseVirtualCall) {
-      CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
-                                                This, CE);
+      CGM.getCXXABI().EmitVirtualDestructorCall(
+          *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
     } else {
-      if (getLangOpts().AppleKext &&
-          MD->isVirtual() &&
-          ME->hasQualifier())
-        Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
+      if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
+        Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
       else if (!DevirtualizedMethod)
         Callee =
             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
@@ -238,10 +256,8 @@
   } else if (UseVirtualCall) {
     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
   } else {
-    if (getLangOpts().AppleKext &&
-        MD->isVirtual() &&
-        ME->hasQualifier())
-      Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
+    if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
+      Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
     else if (!DevirtualizedMethod)
       Callee = CGM.GetAddrOfFunction(MD, Ty);
     else {
@@ -314,20 +330,9 @@
                                                ReturnValueSlot ReturnValue) {
   assert(MD->isInstance() &&
          "Trying to emit a member call expr on a static method!");
-  LValue LV = EmitLValue(E->getArg(0));
-  llvm::Value *This = LV.getAddress();
-
-  if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
-      MD->isTrivial() && !MD->getParent()->mayInsertExtraPadding()) {
-    llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
-    QualType Ty = E->getType();
-    EmitAggregateAssign(This, Src, Ty);
-    return RValue::get(This);
-  }
-
-  llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
-  return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
-                                     /*ImplicitParam=*/nullptr, QualType(), E);
+  return EmitCXXMemberOrOperatorMemberCallExpr(
+      E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
+      /*IsArrow=*/false, E->getArg(0));
 }
 
 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
@@ -752,9 +757,8 @@
   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
   switch (CGF.getEvaluationKind(AllocType)) {
   case TEK_Scalar:
-    CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
-                                                         Alignment),
-                       false);
+    CGF.EmitScalarInit(Init, nullptr,
+                       CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
     return;
   case TEK_Complex:
     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
@@ -1012,6 +1016,7 @@
                                llvm::Value *NewPtr,
                                llvm::Value *NumElements,
                                llvm::Value *AllocSizeWithoutCookie) {
+  ApplyDebugLocation DL(CGF, E);
   if (E->isArray())
     CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
                                 AllocSizeWithoutCookie);
@@ -1028,9 +1033,9 @@
   llvm::Instruction *CallOrInvoke;
   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
   RValue RV =
-      CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
-                   CalleeAddr, ReturnValueSlot(), Args,
-                   Callee, &CallOrInvoke);
+      CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
+                       Args, CalleeType, /*chainCall=*/false),
+                   CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
 
   /// C++1y [expr.new]p10:
   ///   [In a new-expression,] an implementation is allowed to omit a call
@@ -1274,10 +1279,9 @@
 
   // Emit a null check on the allocation result if the allocation
   // function is allowed to return null (because it has a non-throwing
-  // exception spec; for this part, we inline
-  // CXXNewExpr::shouldNullCheckAllocation()) and we have an
+  // exception spec or is the reserved placement new) and we have an
   // interesting initializer.
-  bool nullCheck = allocatorType->isNothrow(getContext()) &&
+  bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
     (!allocType.isPODType(getContext()) || E->hasInitializer());
 
   llvm::BasicBlock *nullCheckBB = nullptr;
@@ -1418,6 +1422,71 @@
                                         OperatorDelete, ElementType);
 }
 
+static void EmitDelete(CodeGenFunction &CGF,
+                              const CXXDeleteExpr *DE,
+                              llvm::Value *Ptr,
+                              QualType ElementType);
+
+static void EmitSizedDelete(CodeGenFunction &CGF,
+                            const CXXDeleteExpr *DE,
+                            llvm::Value *Ptr,
+                            QualType ElementType,
+                            FunctionDecl* UnsizedDealloc) {
+
+  if (CGF.getLangOpts().DefineSizedDeallocation) {
+    // The delete operator in use is fixed. So simply emit the delete expr.
+    EmitDelete(CGF, DE, Ptr, ElementType);
+    return;
+  }
+
+  assert(UnsizedDealloc && "We must be emiting a 'sized' delete expr");
+
+  // Branch off over the value of operator delete:
+  // Use the sized form if available, and default on the unsized form otherwise.
+  llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("if.then");
+  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("if.end");
+  llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("if.else");
+
+  // Emit the condition.
+  const FunctionDecl *OpDelFD = DE->getOperatorDelete();
+  llvm::Value *OpDelAddr = CGF.CGM.GetAddrOfFunction(OpDelFD);
+  //llvm::Function *OpDel = dyn_cast<llvm::Function>(OpDelAddr);
+  llvm::Value *SDE = CGF.Builder.CreateIsNotNull(OpDelAddr, "sized.del.exists");
+  CGF.Builder.CreateCondBr(SDE, ThenBlock, ElseBlock);
+
+  // Emit the 'then' code.
+  CGF.EmitBlock(ThenBlock);
+  EmitDelete(CGF, DE, Ptr, ElementType);
+  CGF.EmitBranch(ContBlock);
+
+  // Compute the 'unsized' delete expr.
+  CXXDeleteExpr * E = const_cast<CXXDeleteExpr*>(DE);
+  CXXDeleteExpr *UnsizedDE =
+  new (CGF.getContext()) CXXDeleteExpr(CGF.getContext().VoidTy,
+                                       E->isGlobalDelete(),
+                                       E->isArrayForm(),
+                                       E->isArrayFormAsWritten(),
+                                       E->doesUsualArrayDeleteWantSize(),
+                                       UnsizedDealloc,
+                                       E->getArgument(),
+                                       E->getLocStart());
+  // Emit the 'else' code.
+  {
+    // There is no need to emit line number for an unconditional branch.
+    auto NL = ApplyDebugLocation::CreateEmpty(CGF);
+    CGF.EmitBlock(ElseBlock);
+  }
+  EmitDelete(CGF, UnsizedDE, Ptr, ElementType);
+  {
+    // There is no need to emit line number for an unconditional branch.
+    auto NL = ApplyDebugLocation::CreateEmpty(CGF);
+    CGF.EmitBranch(ContBlock);
+  }
+
+  // Emit the continuation block for code after the if.
+  CGF.EmitBlock(ContBlock, true);
+}
+
 /// Emit the code for deleting a single object.
 static void EmitObjectDelete(CodeGenFunction &CGF,
                              const CXXDeleteExpr *DE,
@@ -1577,6 +1646,17 @@
   CGF.PopCleanupBlock();
 }
 
+static void EmitDelete(CodeGenFunction &CGF,
+                       const CXXDeleteExpr *DE,
+                       llvm::Value *Ptr,
+                       QualType ElementType) {
+  if (DE->isArrayForm()) {
+    EmitArrayDelete(CGF, DE, Ptr, ElementType);
+  } else {
+    EmitObjectDelete(CGF, DE, Ptr, ElementType);
+  }
+}
+
 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
   const Expr *Arg = E->getArgument();
   llvm::Value *Ptr = EmitScalarExpr(Arg);
@@ -1616,11 +1696,12 @@
   assert(ConvertTypeForMem(DeleteTy) ==
          cast<llvm::PointerType>(Ptr->getType())->getElementType());
 
-  if (E->isArrayForm()) {
-    EmitArrayDelete(*this, E, Ptr, DeleteTy);
-  } else {
-    EmitObjectDelete(*this, E, Ptr, DeleteTy);
-  }
+  const FunctionDecl *Dealloc = E->getOperatorDelete();
+  if (FunctionDecl* UnsizedDealloc =
+      Dealloc->getCorrespondingUnsizedGlobalDeallocationFunction())
+    EmitSizedDelete(*this, E, Ptr, DeleteTy, UnsizedDealloc);
+  else
+    EmitDelete(*this, E, Ptr, DeleteTy);
 
   EmitBlock(DeleteEnd);
 }
diff --git a/lib/CodeGen/CGExprComplex.cpp b/lib/CodeGen/CGExprComplex.cpp
index 4700c7e..b2228f0 100644
--- a/lib/CodeGen/CGExprComplex.cpp
+++ b/lib/CodeGen/CGExprComplex.cpp
@@ -95,6 +95,7 @@
   //===--------------------------------------------------------------------===//
 
   ComplexPairTy Visit(Expr *E) {
+    ApplyDebugLocation DL(CGF, E);
     return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
   }
 
@@ -333,10 +334,10 @@
 
 /// EmitStoreOfComplex - Store the specified real/imag parts into the
 /// specified value pointer.
-void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val,
-                                            LValue lvalue,
+void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
                                             bool isInit) {
-  if (lvalue.getType()->isAtomicType())
+  if (lvalue.getType()->isAtomicType() ||
+      (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
     return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
 
   llvm::Value *Ptr = lvalue.getAddress();
@@ -376,7 +377,7 @@
 
 
 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
-  if (E->getCallReturnType()->isReferenceType())
+  if (E->getCallReturnType(CGF.getContext())->isReferenceType())
     return EmitLoadOfLValue(E);
 
   return CGF.EmitCallExpr(E).getComplexVal();
@@ -582,13 +583,22 @@
            Op.Ty->castAs<ComplexType>()->getElementType());
 
   // We *must* use the full CG function call building logic here because the
-  // complex type has special ABI handling.
-  const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
-      Op.Ty, Args, FunctionType::ExtInfo(), RequiredArgs::All);
+  // complex type has special ABI handling. We also should not forget about
+  // special calling convention which may be used for compiler builtins.
+  const CGFunctionInfo &FuncInfo =
+    CGF.CGM.getTypes().arrangeFreeFunctionCall(
+      Op.Ty, Args, FunctionType::ExtInfo(/* No CC here - will be added later */),
+      RequiredArgs::All);
   llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
-  llvm::Constant *Func = CGF.CGM.CreateRuntimeFunction(FTy, LibCallName);
+  llvm::Constant *Func = CGF.CGM.CreateBuiltinFunction(FTy, LibCallName);
+  llvm::Instruction *Call;
 
-  return CGF.EmitCall(FuncInfo, Func, ReturnValueSlot(), Args).getComplexVal();
+  RValue Res = CGF.EmitCall(FuncInfo, Func, ReturnValueSlot(), Args,
+                            nullptr, &Call);
+  cast<llvm::CallInst>(Call)->setCallingConv(CGF.CGM.getBuiltinCC());
+  cast<llvm::CallInst>(Call)->setDoesNotThrow();
+
+  return Res.getComplexVal();
 }
 
 /// \brief Lookup the libcall name for a given floating point type complex
@@ -810,6 +820,8 @@
   TestAndClearIgnoreReal();
   TestAndClearIgnoreImag();
   QualType LHSTy = E->getLHS()->getType();
+  if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
+    LHSTy = AT->getValueType();
 
   BinOpInfo OpInfo;
 
@@ -1025,7 +1037,7 @@
          "Invalid complex expression to emit");
 
   return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
-    .Visit(const_cast<Expr*>(E));
+      .Visit(const_cast<Expr *>(E));
 }
 
 void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,
@@ -1077,8 +1089,8 @@
 }
 
 LValue CodeGenFunction::
-EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E,
-                                     llvm::Value *&Result) {
+EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
+                                    llvm::Value *&Result) {
   CompoundFunc Op = getComplexOp(E->getOpcode());
   RValue Val;
   LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
diff --git a/lib/CodeGen/CGExprConstant.cpp b/lib/CodeGen/CGExprConstant.cpp
index 088a5d0..54f7eee 100644
--- a/lib/CodeGen/CGExprConstant.cpp
+++ b/lib/CodeGen/CGExprConstant.cpp
@@ -750,6 +750,20 @@
     // initialise any elements that have not been initialised explicitly
     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
 
+    // Initialize remaining array elements.
+    // FIXME: This doesn't handle member pointers correctly!
+    llvm::Constant *fillC;
+    if (Expr *filler = ILE->getArrayFiller())
+      fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
+    else
+      fillC = llvm::Constant::getNullValue(ElemTy);
+    if (!fillC)
+      return nullptr;
+
+    // Try to use a ConstantAggregateZero if we can.
+    if (fillC->isNullValue() && !NumInitableElts)
+      return llvm::ConstantAggregateZero::get(AType);
+
     // Copy initializer elements.
     std::vector<llvm::Constant*> Elts;
     Elts.reserve(NumInitableElts + NumElements);
@@ -764,15 +778,6 @@
       Elts.push_back(C);
     }
 
-    // Initialize remaining array elements.
-    // FIXME: This doesn't handle member pointers correctly!
-    llvm::Constant *fillC;
-    if (Expr *filler = ILE->getArrayFiller())
-      fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
-    else
-      fillC = llvm::Constant::getNullValue(ElemTy);
-    if (!fillC)
-      return nullptr;
     RewriteType |= (fillC->getType() != ElemTy);
     Elts.resize(NumElements, fillC);
 
@@ -1143,7 +1148,7 @@
     // FIXME: the target may want to specify that this is packed.
     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
                                                   Complex[1]->getType(),
-                                                  NULL);
+                                                  nullptr);
     return llvm::ConstantStruct::get(STy, Complex);
   }
   case APValue::Float: {
@@ -1166,7 +1171,7 @@
     // FIXME: the target may want to specify that this is packed.
     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
                                                   Complex[1]->getType(),
-                                                  NULL);
+                                                  nullptr);
     return llvm::ConstantStruct::get(STy, Complex);
   }
   case APValue::Vector: {
@@ -1207,9 +1212,6 @@
     unsigned NumElements = Value.getArraySize();
     unsigned NumInitElts = Value.getArrayInitializedElts();
 
-    std::vector<llvm::Constant*> Elts;
-    Elts.reserve(NumElements);
-
     // Emit array filler, if there is one.
     llvm::Constant *Filler = nullptr;
     if (Value.hasArrayFiller())
@@ -1217,7 +1219,18 @@
                                           CAT->getElementType(), CGF);
 
     // Emit initializer elements.
-    llvm::Type *CommonElementType = nullptr;
+    llvm::Type *CommonElementType =
+        getTypes().ConvertType(CAT->getElementType());
+
+    // Try to use a ConstantAggregateZero if we can.
+    if (Filler && Filler->isNullValue() && !NumInitElts) {
+      llvm::ArrayType *AType =
+          llvm::ArrayType::get(CommonElementType, NumElements);
+      return llvm::ConstantAggregateZero::get(AType);
+    }
+
+    std::vector<llvm::Constant*> Elts;
+    Elts.reserve(NumElements);
     for (unsigned I = 0; I < NumElements; ++I) {
       llvm::Constant *C = Filler;
       if (I < NumInitElts)
diff --git a/lib/CodeGen/CGExprScalar.cpp b/lib/CodeGen/CGExprScalar.cpp
index 19d453d..dc12dd8 100644
--- a/lib/CodeGen/CGExprScalar.cpp
+++ b/lib/CodeGen/CGExprScalar.cpp
@@ -196,6 +196,7 @@
   //===--------------------------------------------------------------------===//
 
   Value *Visit(Expr *E) {
+    ApplyDebugLocation DL(CGF, E);
     return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
   }
 
@@ -319,7 +320,7 @@
   Value *VisitCastExpr(CastExpr *E);
 
   Value *VisitCallExpr(const CallExpr *E) {
-    if (E->getCallReturnType()->isReferenceType())
+    if (E->getCallReturnType(CGF.getContext())->isReferenceType())
       return EmitLoadOfLValue(E);
 
     Value *V = CGF.EmitCallExpr(E).getScalarVal();
@@ -1351,8 +1352,8 @@
     llvm::Type *DstTy = ConvertType(DestTy);
     if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
         SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
-      llvm::Type *MidTy = CGF.CGM.getDataLayout().getIntPtrType(SrcTy);
-      return Builder.CreateIntToPtr(Builder.CreatePtrToInt(Src, MidTy), DstTy);
+      llvm_unreachable("wrong cast for pointers in different address spaces"
+                       "(must be an address space cast)!");
     }
     return Builder.CreateBitCast(Src, DstTy);
   }
@@ -1411,8 +1412,11 @@
     // anything here.
     if (!E->getType()->isVariableArrayType()) {
       assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
-      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
-                                 ->getElementType()) &&
+      V = CGF.Builder.CreatePointerCast(
+          V, ConvertType(E->getType())->getPointerTo(
+            V->getType()->getPointerAddressSpace()));
+
+      assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
              "Expected pointer to array");
       V = Builder.CreateStructGEP(V, 0, "arraydecay");
     }
@@ -1789,11 +1793,11 @@
   if (atomicPHI) {
     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
-    llvm::Value *pair = Builder.CreateAtomicCmpXchg(
-        LV.getAddress(), atomicPHI, CGF.EmitToMemory(value, type),
-        llvm::SequentiallyConsistent, llvm::SequentiallyConsistent);
-    llvm::Value *old = Builder.CreateExtractValue(pair, 0);
-    llvm::Value *success = Builder.CreateExtractValue(pair, 1);
+    auto Pair = CGF.EmitAtomicCompareExchange(
+        LV, RValue::get(atomicPHI), RValue::get(CGF.EmitToMemory(value, type)),
+        E->getExprLoc());
+    llvm::Value *old = Pair.first.getScalarVal();
+    llvm::Value *success = Pair.second.getScalarVal();
     atomicPHI->addIncoming(old, opBB);
     Builder.CreateCondBr(success, contBB, opBB);
     Builder.SetInsertPoint(contBB);
@@ -2052,7 +2056,7 @@
   BinOpInfo OpInfo;
 
   if (E->getComputationResultType()->isAnyComplexType())
-    return CGF.EmitScalarCompooundAssignWithComplex(E, Result);
+    return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
 
   // Emit the RHS first.  __block variables need to have the rhs evaluated
   // first, plus this should improve codegen a little.
@@ -2133,11 +2137,11 @@
   if (atomicPHI) {
     llvm::BasicBlock *opBB = Builder.GetInsertBlock();
     llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
-    llvm::Value *pair = Builder.CreateAtomicCmpXchg(
-        LHSLV.getAddress(), atomicPHI, CGF.EmitToMemory(Result, LHSTy),
-        llvm::SequentiallyConsistent, llvm::SequentiallyConsistent);
-    llvm::Value *old = Builder.CreateExtractValue(pair, 0);
-    llvm::Value *success = Builder.CreateExtractValue(pair, 1);
+    auto Pair = CGF.EmitAtomicCompareExchange(
+        LHSLV, RValue::get(atomicPHI),
+        RValue::get(CGF.EmitToMemory(Result, LHSTy)), E->getExprLoc());
+    llvm::Value *old = Pair.first.getScalarVal();
+    llvm::Value *success = Pair.second.getScalarVal();
     atomicPHI->addIncoming(old, opBB);
     Builder.CreateCondBr(success, contBB, opBB);
     Builder.SetInsertPoint(contBB);
@@ -3039,7 +3043,7 @@
   // Emit an unconditional branch from this block to ContBlock.
   {
     // There is no need to emit line number for unconditional branch.
-    SuppressDebugLocation S(Builder);
+    auto NL = ApplyDebugLocation::CreateEmpty(CGF);
     CGF.EmitBlock(ContBlock);
   }
   // Insert an entry into the phi node for the edge with the value of RHSCond.
@@ -3312,8 +3316,12 @@
   llvm::Value *Val = Builder.CreateLoad(ArgPtr);
 
   // If EmitVAArg promoted the type, we must truncate it.
-  if (ArgTy != Val->getType())
-    Val = Builder.CreateTrunc(Val, ArgTy);
+  if (ArgTy != Val->getType()) {
+    if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
+      Val = Builder.CreateIntToPtr(Val, ArgTy);
+    else
+      Val = Builder.CreateTrunc(Val, ArgTy);
+  }
 
   return Val;
 }
@@ -3385,13 +3393,8 @@
   assert(E && hasScalarEvaluationKind(E->getType()) &&
          "Invalid scalar expression to emit");
 
-  if (isa<CXXDefaultArgExpr>(E))
-    disableDebugInfo();
-  Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
-    .Visit(const_cast<Expr*>(E));
-  if (isa<CXXDefaultArgExpr>(E))
-    enableDebugInfo();
-  return V;
+  return ScalarExprEmitter(*this, IgnoreResultAssign)
+      .Visit(const_cast<Expr *>(E));
 }
 
 /// EmitScalarConversion - Emit a conversion from the specified type to the
diff --git a/lib/CodeGen/CGLoopInfo.cpp b/lib/CodeGen/CGLoopInfo.cpp
index a273f1d..011ae7e 100644
--- a/lib/CodeGen/CGLoopInfo.cpp
+++ b/lib/CodeGen/CGLoopInfo.cpp
@@ -24,42 +24,40 @@
       Attrs.VectorizerEnable == LoopAttributes::VecUnspecified)
     return nullptr;
 
-  SmallVector<Value *, 4> Args;
+  SmallVector<Metadata *, 4> Args;
   // Reserve operand 0 for loop id self reference.
-  MDNode *TempNode = MDNode::getTemporary(Ctx, None);
-  Args.push_back(TempNode);
+  auto TempNode = MDNode::getTemporary(Ctx, None);
+  Args.push_back(TempNode.get());
 
   // Setting vectorizer.width
   if (Attrs.VectorizerWidth > 0) {
-    Value *Vals[] = { MDString::get(Ctx, "llvm.loop.vectorize.width"),
-                      ConstantInt::get(Type::getInt32Ty(Ctx),
-                                       Attrs.VectorizerWidth) };
+    Metadata *Vals[] = {MDString::get(Ctx, "llvm.loop.vectorize.width"),
+                        ConstantAsMetadata::get(ConstantInt::get(
+                            Type::getInt32Ty(Ctx), Attrs.VectorizerWidth))};
     Args.push_back(MDNode::get(Ctx, Vals));
   }
 
   // Setting vectorizer.unroll
   if (Attrs.VectorizerUnroll > 0) {
-    Value *Vals[] = { MDString::get(Ctx, "llvm.loop.interleave.count"),
-                      ConstantInt::get(Type::getInt32Ty(Ctx),
-                                       Attrs.VectorizerUnroll) };
+    Metadata *Vals[] = {MDString::get(Ctx, "llvm.loop.interleave.count"),
+                        ConstantAsMetadata::get(ConstantInt::get(
+                            Type::getInt32Ty(Ctx), Attrs.VectorizerUnroll))};
     Args.push_back(MDNode::get(Ctx, Vals));
   }
 
   // Setting vectorizer.enable
   if (Attrs.VectorizerEnable != LoopAttributes::VecUnspecified) {
-    Value *Vals[] = { MDString::get(Ctx, "llvm.loop.vectorize.enable"),
-                      ConstantInt::get(Type::getInt1Ty(Ctx),
-                                       (Attrs.VectorizerEnable ==
-                                        LoopAttributes::VecEnable)) };
+    Metadata *Vals[] = {
+        MDString::get(Ctx, "llvm.loop.vectorize.enable"),
+        ConstantAsMetadata::get(ConstantInt::get(
+            Type::getInt1Ty(Ctx),
+            (Attrs.VectorizerEnable == LoopAttributes::VecEnable)))};
     Args.push_back(MDNode::get(Ctx, Vals));
   }
 
-  MDNode *LoopID = MDNode::get(Ctx, Args);
-  assert(LoopID->use_empty() && "LoopID should not be used");
-
   // Set the first operand to itself.
+  MDNode *LoopID = MDNode::get(Ctx, Args);
   LoopID->replaceOperandWith(0, LoopID);
-  MDNode::deleteTemporary(TempNode);
   return LoopID;
 }
 
diff --git a/lib/CodeGen/CGLoopInfo.h b/lib/CodeGen/CGLoopInfo.h
index b169399..aee1621 100644
--- a/lib/CodeGen/CGLoopInfo.h
+++ b/lib/CodeGen/CGLoopInfo.h
@@ -78,8 +78,8 @@
 /// This stack can be used to prepare attributes which are applied when a loop
 /// is emitted.
 class LoopInfoStack {
-  LoopInfoStack(const LoopInfoStack &) LLVM_DELETED_FUNCTION;
-  void operator=(const LoopInfoStack &) LLVM_DELETED_FUNCTION;
+  LoopInfoStack(const LoopInfoStack &) = delete;
+  void operator=(const LoopInfoStack &) = delete;
 
 public:
   LoopInfoStack() {}
diff --git a/lib/CodeGen/CGObjC.cpp b/lib/CodeGen/CGObjC.cpp
index ca67c4b..19f5ca2 100644
--- a/lib/CodeGen/CGObjC.cpp
+++ b/lib/CodeGen/CGObjC.cpp
@@ -60,7 +60,6 @@
 llvm::Value *
 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
   // Generate the correct selector for this literal's concrete type.
-  const Expr *SubExpr = E->getSubExpr();
   // Get the method.
   const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
   assert(BoxingMethod && "BoxingMethod is null");
@@ -73,12 +72,9 @@
   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
   const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
   llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
-  
-  const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
-  QualType ArgQT = argDecl->getType().getUnqualifiedType();
-  RValue RV = EmitAnyExpr(SubExpr);
+
   CallArgList Args;
-  Args.add(RV, ArgQT);
+  EmitCallArgs(Args, BoxingMethod, E->arg_begin(), E->arg_end());
 
   RValue result = Runtime.GenerateMessageSend(
       *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
@@ -461,8 +457,8 @@
 /// the LLVM function and sets the other context used by
 /// CodeGenFunction.
 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
-                                      const ObjCContainerDecl *CD,
-                                      SourceLocation StartLoc) {
+                                      const ObjCContainerDecl *CD) {
+  SourceLocation StartLoc = OMD->getLocStart();
   FunctionArgList args;
   // Check if we should generate debug info for this method.
   if (OMD->hasAttr<NoDebugAttr>())
@@ -476,10 +472,10 @@
   args.push_back(OMD->getSelfDecl());
   args.push_back(OMD->getCmdDecl());
 
-  for (const auto *PI : OMD->params())
-    args.push_back(PI);
+  args.append(OMD->param_begin(), OMD->param_end());
 
   CurGD = OMD;
+  CurEHLocation = OMD->getLocEnd();
 
   StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
                 OMD->getLocation(), StartLoc);
@@ -501,15 +497,13 @@
 /// Generate an Objective-C method.  An Objective-C method is a C function with
 /// its pointer, name, and types registered in the class struture.
 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
-  StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
+  StartObjCMethod(OMD, OMD->getClassInterface());
   PGO.assignRegionCounters(OMD, CurFn);
   assert(isa<CompoundStmt>(OMD->getBody()));
   RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
   Cnt.beginRegion(Builder);
   EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
   FinishFunction(OMD->getBodyRBrace());
-  PGO.emitInstrumentationData();
-  PGO.destroyRegionCounters();
 }
 
 /// emitStructGetterCall - Call the runtime function to load a property
@@ -749,7 +743,7 @@
   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
   ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
   assert(OMD && "Invalid call to generate getter (empty method)");
-  StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
+  StartObjCMethod(OMD, IMP->getClassInterface());
 
   generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
 
@@ -1278,7 +1272,7 @@
   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
   assert(OMD && "Invalid call to generate setter (empty method)");
-  StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
+  StartObjCMethod(OMD, IMP->getClassInterface());
 
   generateObjCSetterBody(IMP, PID, AtomicHelperFn);
 
@@ -1356,7 +1350,7 @@
                                                  ObjCMethodDecl *MD,
                                                  bool ctor) {
   MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
-  StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
+  StartObjCMethod(MD, IMP->getClassInterface());
 
   // Emit .cxx_construct.
   if (ctor) {
@@ -1940,9 +1934,8 @@
       = cast<llvm::CallInst>(result->stripPointerCasts());
     assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
 
-    SmallVector<llvm::Value*,1> args;
     call->setMetadata("clang.arc.copy_on_escape",
-                      llvm::MDNode::get(Builder.getContext(), args));
+                      llvm::MDNode::get(Builder.getContext(), None));
   }
 
   return result;
@@ -1984,8 +1977,8 @@
                             "clang.arc.retainAutoreleasedReturnValueMarker");
       assert(metadata->getNumOperands() <= 1);
       if (metadata->getNumOperands() == 0) {
-        llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
-        metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
+        metadata->addOperand(llvm::MDNode::get(
+            getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
       }
     }
   }
@@ -2018,9 +2011,8 @@
   llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
 
   if (precise == ARCImpreciseLifetime) {
-    SmallVector<llvm::Value*,1> args;
     call->setMetadata("clang.imprecise_release",
-                      llvm::MDNode::get(Builder.getContext(), args));
+                      llvm::MDNode::get(Builder.getContext(), None));
   }
 }
 
diff --git a/lib/CodeGen/CGObjCGNU.cpp b/lib/CodeGen/CGObjCGNU.cpp
index 8d95369..da95260 100644
--- a/lib/CodeGen/CGObjCGNU.cpp
+++ b/lib/CodeGen/CGObjCGNU.cpp
@@ -1296,11 +1296,11 @@
   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
   imp = EnforceType(Builder, imp, MSI.MessengerType);
 
-  llvm::Value *impMD[] = {
+  llvm::Metadata *impMD[] = {
       llvm::MDString::get(VMContext, Sel.getAsString()),
       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
-      llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
-   };
+      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+          llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
 
   llvm::Instruction *call;
@@ -1371,12 +1371,11 @@
   cmd = EnforceType(Builder, cmd, SelectorTy);
   Receiver = EnforceType(Builder, Receiver, IdTy);
 
-  llvm::Value *impMD[] = {
-        llvm::MDString::get(VMContext, Sel.getAsString()),
-        llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
-        llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
-                               Class!=nullptr)
-   };
+  llvm::Metadata *impMD[] = {
+      llvm::MDString::get(VMContext, Sel.getAsString()),
+      llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
+      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+          llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
 
   CallArgList ActualArgs;
@@ -2367,7 +2366,7 @@
   std::vector<llvm::Constant*> Elements;
   llvm::Constant *Statics = NULLPtr;
   // Generate statics list:
-  if (ConstantStrings.size()) {
+  if (!ConstantStrings.empty()) {
     llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
         ConstantStrings.size() + 1);
     ConstantStrings.push_back(NULLPtr);
diff --git a/lib/CodeGen/CGObjCMac.cpp b/lib/CodeGen/CGObjCMac.cpp
index c05c226..b9fdf73 100644
--- a/lib/CodeGen/CGObjCMac.cpp
+++ b/lib/CodeGen/CGObjCMac.cpp
@@ -106,7 +106,7 @@
     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
     llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
     llvm::Type *resultType = 
-      llvm::StructType::get(longDoubleType, longDoubleType, NULL);
+      llvm::StructType::get(longDoubleType, longDoubleType, nullptr);
 
     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
                                                              params, true),
@@ -244,9 +244,9 @@
     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
     Params.push_back(Ctx.BoolTy);
     llvm::FunctionType *FTy =
-      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(IdType, false, Params,
-                                                          FunctionType::ExtInfo(),
-                                                          RequiredArgs::All));
+        Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
+            IdType, false, false, Params, FunctionType::ExtInfo(),
+            RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
   }
 
@@ -264,10 +264,9 @@
     Params.push_back(Ctx.BoolTy);
     Params.push_back(Ctx.BoolTy);
     llvm::FunctionType *FTy =
-      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
-                                                          Params,
-                                                          FunctionType::ExtInfo(),
-                                                          RequiredArgs::All));
+        Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
+            Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
+            RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
   }
 
@@ -291,10 +290,9 @@
     Params.push_back(IdType);
     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
     llvm::FunctionType *FTy =
-    Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
-                                                        Params,
-                                                        FunctionType::ExtInfo(),
-                                                        RequiredArgs::All));
+        Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
+            Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
+            RequiredArgs::All));
     const char *name;
     if (atomic && copy)
       name = "objc_setProperty_atomic_copy";
@@ -319,10 +317,9 @@
     Params.push_back(Ctx.BoolTy);
     Params.push_back(Ctx.BoolTy);
     llvm::FunctionType *FTy =
-      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
-                                                          Params,
-                                                          FunctionType::ExtInfo(),
-                                                          RequiredArgs::All));
+        Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
+            Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
+            RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
   }
   
@@ -339,7 +336,7 @@
     Params.push_back(Ctx.VoidPtrTy);
     Params.push_back(Ctx.VoidPtrTy);
     llvm::FunctionType *FTy =
-      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
+      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false, false,
                                                           Params,
                                                           FunctionType::ExtInfo(),
                                                           RequiredArgs::All));
@@ -353,10 +350,9 @@
     SmallVector<CanQualType,1> Params;
     Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
     llvm::FunctionType *FTy =
-      Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
-                                                          Params,
-                                                          FunctionType::ExtInfo(),
-                                                      RequiredArgs::All));
+        Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
+            Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
+            RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
   }
 
@@ -3814,15 +3810,16 @@
   // Enter a try block:
   //  - Call objc_exception_try_enter to push ExceptionData on top of
   //    the EH stack.
-  CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
+  CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
+                              ExceptionData);
 
   //  - Call setjmp on the exception data buffer.
   llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
   llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
   llvm::Value *SetJmpBuffer =
     CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
-  llvm::CallInst *SetJmpResult =
-    CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
+  llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
+      ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
   SetJmpResult->setCanReturnTwice();
 
   // If setjmp returned 0, enter the protected block; otherwise,
@@ -4278,11 +4275,10 @@
                         eImageInfo_GCOnly);
 
       // Require that GC be specified and set to eImageInfo_GarbageCollected.
-      llvm::Value *Ops[2] = {
-        llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
-        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
-                               eImageInfo_GarbageCollected)
-      };
+      llvm::Metadata *Ops[2] = {
+          llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
+          llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+              llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
       Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
                         llvm::MDNode::get(VMContext, Ops));
     }
@@ -5033,7 +5029,7 @@
   //   char *attributes;
   // }
   PropertyTy = llvm::StructType::create("struct._prop_t",
-                                        Int8PtrTy, Int8PtrTy, NULL);
+                                        Int8PtrTy, Int8PtrTy, nullptr);
 
   // struct _prop_list_t {
   //   uint32_t entsize;      // sizeof(struct _prop_t)
@@ -5042,7 +5038,7 @@
   // }
   PropertyListTy =
     llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
-                             llvm::ArrayType::get(PropertyTy, 0), NULL);
+                             llvm::ArrayType::get(PropertyTy, 0), nullptr);
   // struct _prop_list_t *
   PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
 
@@ -5053,7 +5049,7 @@
   // }
   MethodTy = llvm::StructType::create("struct._objc_method",
                                       SelectorPtrTy, Int8PtrTy, Int8PtrTy,
-                                      NULL);
+                                      nullptr);
 
   // struct _objc_cache *
   CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
@@ -5069,16 +5065,15 @@
   // }
   MethodDescriptionTy =
     llvm::StructType::create("struct._objc_method_description",
-                             SelectorPtrTy, Int8PtrTy, NULL);
+                             SelectorPtrTy, Int8PtrTy, nullptr);
 
   // struct _objc_method_description_list {
   //   int count;
   //   struct _objc_method_description[1];
   // }
-  MethodDescriptionListTy =
-    llvm::StructType::create("struct._objc_method_description_list",
-                             IntTy,
-                             llvm::ArrayType::get(MethodDescriptionTy, 0),NULL);
+  MethodDescriptionListTy = llvm::StructType::create(
+      "struct._objc_method_description_list", IntTy,
+      llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
 
   // struct _objc_method_description_list *
   MethodDescriptionListPtrTy =
@@ -5097,7 +5092,7 @@
     llvm::StructType::create("struct._objc_protocol_extension",
                              IntTy, MethodDescriptionListPtrTy,
                              MethodDescriptionListPtrTy, PropertyListPtrTy,
-                             Int8PtrPtrTy, NULL);
+                             Int8PtrPtrTy, nullptr);
 
   // struct _objc_protocol_extension *
   ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
@@ -5112,7 +5107,7 @@
   ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
                           LongTy,
                           llvm::ArrayType::get(ProtocolTy, 0),
-                          NULL);
+                          nullptr);
 
   // struct _objc_protocol {
   //   struct _objc_protocol_extension *isa;
@@ -5125,7 +5120,7 @@
                       llvm::PointerType::getUnqual(ProtocolListTy),
                       MethodDescriptionListPtrTy,
                       MethodDescriptionListPtrTy,
-                      NULL);
+                      nullptr);
 
   // struct _objc_protocol_list *
   ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
@@ -5140,7 +5135,7 @@
   //   int  ivar_offset;
   // }
   IvarTy = llvm::StructType::create("struct._objc_ivar",
-                                    Int8PtrTy, Int8PtrTy, IntTy, NULL);
+                                    Int8PtrTy, Int8PtrTy, IntTy, nullptr);
 
   // struct _objc_ivar_list *
   IvarListTy =
@@ -5155,7 +5150,7 @@
   // struct _objc_class_extension *
   ClassExtensionTy =
     llvm::StructType::create("struct._objc_class_extension",
-                             IntTy, Int8PtrTy, PropertyListPtrTy, NULL);
+                             IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
   ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
 
   ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
@@ -5186,7 +5181,7 @@
                    ProtocolListPtrTy,
                    Int8PtrTy,
                    ClassExtensionPtrTy,
-                   NULL);
+                   nullptr);
 
   ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
 
@@ -5202,7 +5197,7 @@
     llvm::StructType::create("struct._objc_category",
                              Int8PtrTy, Int8PtrTy, MethodListPtrTy,
                              MethodListPtrTy, ProtocolListPtrTy,
-                             IntTy, PropertyListPtrTy, NULL);
+                             IntTy, PropertyListPtrTy, nullptr);
 
   // Global metadata structures
 
@@ -5216,7 +5211,7 @@
   SymtabTy =
     llvm::StructType::create("struct._objc_symtab",
                              LongTy, SelectorPtrTy, ShortTy, ShortTy,
-                             llvm::ArrayType::get(Int8PtrTy, 0), NULL);
+                             llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
   SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
 
   // struct _objc_module {
@@ -5227,7 +5222,7 @@
   //  }
   ModuleTy =
     llvm::StructType::create("struct._objc_module",
-                             LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL);
+                             LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
 
 
   // FIXME: This is the size of the setjmp buffer and should be target
@@ -5240,7 +5235,7 @@
   ExceptionDataTy =
     llvm::StructType::create("struct._objc_exception_data",
                              llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
-                             StackPtrTy, NULL);
+                             StackPtrTy, nullptr);
 
 }
 
@@ -5253,7 +5248,7 @@
   // }
   MethodListnfABITy =
     llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
-                             llvm::ArrayType::get(MethodTy, 0), NULL);
+                             llvm::ArrayType::get(MethodTy, 0), nullptr);
   // struct method_list_t *
   MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
 
@@ -5281,7 +5276,7 @@
                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
                              PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
-                             NULL);
+                             nullptr);
 
   // struct _protocol_t*
   ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
@@ -5292,7 +5287,7 @@
   // }
   ProtocolListnfABITy->setBody(LongTy,
                                llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
-                               NULL);
+                               nullptr);
 
   // struct _objc_protocol_list*
   ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
@@ -5306,7 +5301,7 @@
   // }
   IvarnfABITy = llvm::StructType::create(
       "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
-      Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL);
+      Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
 
   // struct _ivar_list_t {
   //   uint32 entsize;  // sizeof(struct _ivar_t)
@@ -5315,7 +5310,7 @@
   // }
   IvarListnfABITy =
     llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
-                             llvm::ArrayType::get(IvarnfABITy, 0), NULL);
+                             llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
 
   IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
 
@@ -5339,7 +5334,8 @@
                                             Int8PtrTy, MethodListnfABIPtrTy,
                                             ProtocolListnfABIPtrTy,
                                             IvarListnfABIPtrTy,
-                                            Int8PtrTy, PropertyListPtrTy, NULL);
+                                            Int8PtrTy, PropertyListPtrTy,
+                                            nullptr);
 
   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
@@ -5360,7 +5356,7 @@
                         CachePtrTy,
                         llvm::PointerType::getUnqual(ImpnfABITy),
                         llvm::PointerType::getUnqual(ClassRonfABITy),
-                        NULL);
+                        nullptr);
 
   // LLVM for struct _class_t *
   ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
@@ -5379,7 +5375,7 @@
                                              MethodListnfABIPtrTy,
                                              ProtocolListnfABIPtrTy,
                                              PropertyListPtrTy,
-                                             NULL);
+                                             nullptr);
 
   // New types for nonfragile abi messaging.
   CodeGen::CodeGenTypes &Types = CGM.getTypes();
@@ -5418,7 +5414,7 @@
   // };
   SuperMessageRefTy =
     llvm::StructType::create("struct._super_message_ref_t",
-                             ImpnfABITy, SelectorPtrTy, NULL);
+                             ImpnfABITy, SelectorPtrTy, nullptr);
 
   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
   SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
@@ -5432,7 +5428,7 @@
   EHTypeTy =
     llvm::StructType::create("struct._objc_typeinfo",
                              llvm::PointerType::getUnqual(Int8PtrTy),
-                             Int8PtrTy, ClassnfABIPtrTy, NULL);
+                             Int8PtrTy, ClassnfABIPtrTy, nullptr);
   EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
 }
 
diff --git a/lib/CodeGen/CGOpenMPRuntime.cpp b/lib/CodeGen/CGOpenMPRuntime.cpp
index ecc844f..51865a6 100644
--- a/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -13,8 +13,8 @@
 
 #include "CGOpenMPRuntime.h"
 #include "CodeGenFunction.h"
-#include "clang/AST/StmtOpenMP.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/StmtOpenMP.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/IR/CallSite.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -27,30 +27,46 @@
 using namespace CodeGen;
 
 namespace {
-/// \brief API for captured statement code generation in OpenMP constructs.
+/// \brief Base class for handling code generation inside OpenMP regions.
 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
 public:
-  CGOpenMPRegionInfo(const OMPExecutableDirective &D, const CapturedStmt &CS,
-                     const VarDecl *ThreadIDVar)
-      : CGCapturedStmtInfo(CS, CR_OpenMP), ThreadIDVar(ThreadIDVar),
-        Directive(D) {
-    assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
-  }
+  CGOpenMPRegionInfo(const OMPExecutableDirective &D, const CapturedStmt &CS)
+      : CGCapturedStmtInfo(CS, CR_OpenMP), Directive(D) {}
 
-  /// \brief Gets a variable or parameter for storing global thread id
+  CGOpenMPRegionInfo(const OMPExecutableDirective &D)
+      : CGCapturedStmtInfo(CR_OpenMP), Directive(D) {}
+
+  /// \brief Get a variable or parameter for storing global thread id
   /// inside OpenMP construct.
-  const VarDecl *getThreadIDVariable() const { return ThreadIDVar; }
+  virtual const VarDecl *getThreadIDVariable() const = 0;
 
-  /// \brief Gets an LValue for the current ThreadID variable.
+  /// \brief Get an LValue for the current ThreadID variable.
   LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
 
+    /// \brief Emit the captured statement body.
+  virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
+
   static bool classof(const CGCapturedStmtInfo *Info) {
     return Info->getKind() == CR_OpenMP;
   }
+protected:
+  /// \brief OpenMP executable directive associated with the region.
+  const OMPExecutableDirective &Directive;
+};
 
-  /// \brief Emit the captured statement body.
-  void EmitBody(CodeGenFunction &CGF, Stmt *S) override;
-
+/// \brief API for captured statement code generation in OpenMP constructs.
+class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
+public:
+  CGOpenMPOutlinedRegionInfo(const OMPExecutableDirective &D,
+                             const CapturedStmt &CS, const VarDecl *ThreadIDVar)
+      : CGOpenMPRegionInfo(D, CS), ThreadIDVar(ThreadIDVar) {
+    assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
+  }
+  /// \brief Get a variable or parameter for storing global thread id
+  /// inside OpenMP construct.
+  virtual const VarDecl *getThreadIDVariable() const override {
+    return ThreadIDVar;
+  }
   /// \brief Get the name of the capture helper.
   StringRef getHelperName() const override { return ".omp_outlined."; }
 
@@ -58,29 +74,69 @@
   /// \brief A variable or parameter storing global thread id for OpenMP
   /// constructs.
   const VarDecl *ThreadIDVar;
-  /// \brief OpenMP executable directive associated with the region.
-  const OMPExecutableDirective &Directive;
+};
+
+/// \brief API for inlined captured statement code generation in OpenMP
+/// constructs.
+class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
+public:
+  CGOpenMPInlinedRegionInfo(const OMPExecutableDirective &D,
+                            CodeGenFunction::CGCapturedStmtInfo *OldCSI)
+      : CGOpenMPRegionInfo(D), OldCSI(OldCSI),
+        OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
+  // \brief Retrieve the value of the context parameter.
+  virtual llvm::Value *getContextValue() const override {
+    if (OuterRegionInfo)
+      return OuterRegionInfo->getContextValue();
+    llvm_unreachable("No context value for inlined OpenMP region");
+  }
+  /// \brief Lookup the captured field decl for a variable.
+  virtual const FieldDecl *lookup(const VarDecl *VD) const override {
+    if (OuterRegionInfo)
+      return OuterRegionInfo->lookup(VD);
+    llvm_unreachable("Trying to reference VarDecl that is neither local nor "
+                     "captured in outer OpenMP region");
+  }
+  virtual FieldDecl *getThisFieldDecl() const override {
+    if (OuterRegionInfo)
+      return OuterRegionInfo->getThisFieldDecl();
+    return nullptr;
+  }
+  /// \brief Get a variable or parameter for storing global thread id
+  /// inside OpenMP construct.
+  virtual const VarDecl *getThreadIDVariable() const override {
+    if (OuterRegionInfo)
+      return OuterRegionInfo->getThreadIDVariable();
+    return nullptr;
+  }
+  /// \brief Get the name of the capture helper.
+  virtual StringRef getHelperName() const override {
+    llvm_unreachable("No helper name for inlined OpenMP construct");
+  }
+
+  CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
+
+private:
+  /// \brief CodeGen info about outer OpenMP region.
+  CodeGenFunction::CGCapturedStmtInfo *OldCSI;
+  CGOpenMPRegionInfo *OuterRegionInfo;
 };
 } // namespace
 
 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
   return CGF.MakeNaturalAlignAddrLValue(
-      CGF.GetAddrOfLocalVar(ThreadIDVar),
-      CGF.getContext().getPointerType(ThreadIDVar->getType()));
+      CGF.GetAddrOfLocalVar(getThreadIDVariable()),
+      CGF.getContext().getPointerType(getThreadIDVariable()->getType()));
 }
 
-void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, Stmt *S) {
+void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) {
   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
   CGF.EmitOMPPrivateClause(Directive, PrivateScope);
   CGF.EmitOMPFirstprivateClause(Directive, PrivateScope);
-  if (PrivateScope.Privatize()) {
+  if (PrivateScope.Privatize())
     // Emit implicit barrier to synchronize threads and avoid data races.
-    auto Flags = static_cast<CGOpenMPRuntime::OpenMPLocationFlags>(
-        CGOpenMPRuntime::OMP_IDENT_KMPC |
-        CGOpenMPRuntime::OMP_IDENT_BARRIER_IMPL);
-    CGF.CGM.getOpenMPRuntime().EmitOMPBarrierCall(CGF, Directive.getLocStart(),
-                                                  Flags);
-  }
+    CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, Directive.getLocStart(),
+                                               /*IsExplicit=*/false);
   CGCapturedStmtInfo::EmitBody(CGF, S);
 }
 
@@ -98,17 +154,17 @@
 }
 
 llvm::Value *
-CGOpenMPRuntime::EmitOpenMPOutlinedFunction(const OMPExecutableDirective &D,
-                                            const VarDecl *ThreadIDVar) {
+CGOpenMPRuntime::emitOutlinedFunction(const OMPExecutableDirective &D,
+                                      const VarDecl *ThreadIDVar) {
   const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
   CodeGenFunction CGF(CGM, true);
-  CGOpenMPRegionInfo CGInfo(D, *CS, ThreadIDVar);
+  CGOpenMPOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar);
   CGF.CapturedStmtInfo = &CGInfo;
   return CGF.GenerateCapturedStmtFunction(*CS);
 }
 
 llvm::Value *
-CGOpenMPRuntime::GetOrCreateDefaultOpenMPLocation(OpenMPLocationFlags Flags) {
+CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
   llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
   if (!Entry) {
     if (!DefaultOpenMPPSource) {
@@ -138,20 +194,23 @@
   return Entry;
 }
 
-llvm::Value *CGOpenMPRuntime::EmitOpenMPUpdateLocation(
-    CodeGenFunction &CGF, SourceLocation Loc, OpenMPLocationFlags Flags) {
+llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
+                                                 SourceLocation Loc,
+                                                 OpenMPLocationFlags Flags) {
   // If no debug info is generated - return global default location.
   if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
       Loc.isInvalid())
-    return GetOrCreateDefaultOpenMPLocation(Flags);
+    return getOrCreateDefaultLocation(Flags);
 
   assert(CGF.CurFn && "No function in current CodeGenFunction.");
 
   llvm::Value *LocValue = nullptr;
-  OpenMPLocThreadIDMapTy::iterator I = OpenMPLocThreadIDMap.find(CGF.CurFn);
-  if (I != OpenMPLocThreadIDMap.end()) {
+  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
+  if (I != OpenMPLocThreadIDMap.end())
     LocValue = I->second.DebugLoc;
-  } else {
+  // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
+  // GetOpenMPThreadID was called before this routine.
+  if (LocValue == nullptr) {
     // Generate "ident_t .kmpc_loc.addr;"
     llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
     AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
@@ -161,13 +220,13 @@
 
     CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
     CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
-    CGF.Builder.CreateMemCpy(LocValue, GetOrCreateDefaultOpenMPLocation(Flags),
+    CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
                              llvm::ConstantExpr::getSizeOf(IdentTy),
                              CGM.PointerAlignInBytes);
   }
 
   // char **psource = &.kmpc_loc_<flags>.addr.psource;
-  llvm::Value *PSource =
+  auto *PSource =
       CGF.Builder.CreateConstInBoundsGEP2_32(LocValue, 0, IdentField_PSource);
 
   auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
@@ -191,51 +250,53 @@
   return LocValue;
 }
 
-llvm::Value *CGOpenMPRuntime::GetOpenMPThreadID(CodeGenFunction &CGF,
-                                                SourceLocation Loc) {
+llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
+                                          SourceLocation Loc) {
   assert(CGF.CurFn && "No function in current CodeGenFunction.");
 
   llvm::Value *ThreadID = nullptr;
   // Check whether we've already cached a load of the thread id in this
   // function.
-  OpenMPLocThreadIDMapTy::iterator I = OpenMPLocThreadIDMap.find(CGF.CurFn);
+  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
   if (I != OpenMPLocThreadIDMap.end()) {
     ThreadID = I->second.ThreadID;
     if (ThreadID != nullptr)
       return ThreadID;
   }
   if (auto OMPRegionInfo =
-                 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
-    // Check if this an outlined function with thread id passed as argument.
-    auto ThreadIDVar = OMPRegionInfo->getThreadIDVariable();
-    auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
-    auto RVal = CGF.EmitLoadOfLValue(LVal, Loc);
-    LVal = CGF.MakeNaturalAlignAddrLValue(RVal.getScalarVal(),
-                                          ThreadIDVar->getType());
-    ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
-    // If value loaded in entry block, cache it and use it everywhere in
-    // function.
-    if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
-      auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
-      Elem.second.ThreadID = ThreadID;
+          dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
+    if (auto ThreadIDVar = OMPRegionInfo->getThreadIDVariable()) {
+      // Check if this an outlined function with thread id passed as argument.
+      auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
+      auto RVal = CGF.EmitLoadOfLValue(LVal, Loc);
+      LVal = CGF.MakeNaturalAlignAddrLValue(RVal.getScalarVal(),
+                                            ThreadIDVar->getType());
+      ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
+      // If value loaded in entry block, cache it and use it everywhere in
+      // function.
+      if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
+        auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
+        Elem.second.ThreadID = ThreadID;
+      }
+      return ThreadID;
     }
-  } else {
-    // This is not an outlined function region - need to call __kmpc_int32
-    // kmpc_global_thread_num(ident_t *loc).
-    // Generate thread id value and cache this value for use across the
-    // function.
-    CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
-    CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
-    llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc)};
-    ThreadID = CGF.EmitRuntimeCall(
-        CreateRuntimeFunction(OMPRTL__kmpc_global_thread_num), Args);
-    auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
-    Elem.second.ThreadID = ThreadID;
   }
+
+  // This is not an outlined function region - need to call __kmpc_int32
+  // kmpc_global_thread_num(ident_t *loc).
+  // Generate thread id value and cache this value for use across the
+  // function.
+  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
+  CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
+  ThreadID =
+      CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
+                          emitUpdateLocation(CGF, Loc));
+  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
+  Elem.second.ThreadID = ThreadID;
   return ThreadID;
 }
 
-void CGOpenMPRuntime::FunctionFinished(CodeGenFunction &CGF) {
+void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
   assert(CGF.CurFn && "No function in current CodeGenFunction.");
   if (OpenMPLocThreadIDMap.count(CGF.CurFn))
     OpenMPLocThreadIDMap.erase(CGF.CurFn);
@@ -250,7 +311,7 @@
 }
 
 llvm::Constant *
-CGOpenMPRuntime::CreateRuntimeFunction(OpenMPRTLFunction Function) {
+CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
   llvm::Constant *RTLFn = nullptr;
   switch (Function) {
   case OMPRTL__kmpc_fork_call: {
@@ -327,12 +388,102 @@
     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
     break;
   }
-  case OMPRTL__kmpc_barrier: {
-    // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
+  case OMPRTL__kmpc_cancel_barrier: {
+    // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
+    // global_tid);
+    llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
+    break;
+  }
+  // Build __kmpc_for_static_init*(
+  //               ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
+  //               kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
+  //               kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
+  //               kmp_int[32|64] incr, kmp_int[32|64] chunk);
+  case OMPRTL__kmpc_for_static_init_4: {
+    auto ITy = CGM.Int32Ty;
+    auto PtrTy = llvm::PointerType::getUnqual(ITy);
+    llvm::Type *TypeParams[] = {
+        getIdentTyPointerTy(),                     // loc
+        CGM.Int32Ty,                               // tid
+        CGM.Int32Ty,                               // schedtype
+        llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
+        PtrTy,                                     // p_lower
+        PtrTy,                                     // p_upper
+        PtrTy,                                     // p_stride
+        ITy,                                       // incr
+        ITy                                        // chunk
+    };
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_4");
+    break;
+  }
+  case OMPRTL__kmpc_for_static_init_4u: {
+    auto ITy = CGM.Int32Ty;
+    auto PtrTy = llvm::PointerType::getUnqual(ITy);
+    llvm::Type *TypeParams[] = {
+        getIdentTyPointerTy(),                     // loc
+        CGM.Int32Ty,                               // tid
+        CGM.Int32Ty,                               // schedtype
+        llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
+        PtrTy,                                     // p_lower
+        PtrTy,                                     // p_upper
+        PtrTy,                                     // p_stride
+        ITy,                                       // incr
+        ITy                                        // chunk
+    };
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_4u");
+    break;
+  }
+  case OMPRTL__kmpc_for_static_init_8: {
+    auto ITy = CGM.Int64Ty;
+    auto PtrTy = llvm::PointerType::getUnqual(ITy);
+    llvm::Type *TypeParams[] = {
+        getIdentTyPointerTy(),                     // loc
+        CGM.Int32Ty,                               // tid
+        CGM.Int32Ty,                               // schedtype
+        llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
+        PtrTy,                                     // p_lower
+        PtrTy,                                     // p_upper
+        PtrTy,                                     // p_stride
+        ITy,                                       // incr
+        ITy                                        // chunk
+    };
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_8");
+    break;
+  }
+  case OMPRTL__kmpc_for_static_init_8u: {
+    auto ITy = CGM.Int64Ty;
+    auto PtrTy = llvm::PointerType::getUnqual(ITy);
+    llvm::Type *TypeParams[] = {
+        getIdentTyPointerTy(),                     // loc
+        CGM.Int32Ty,                               // tid
+        CGM.Int32Ty,                               // schedtype
+        llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
+        PtrTy,                                     // p_lower
+        PtrTy,                                     // p_upper
+        PtrTy,                                     // p_stride
+        ITy,                                       // incr
+        ITy                                        // chunk
+    };
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_8u");
+    break;
+  }
+  case OMPRTL__kmpc_for_static_fini: {
+    // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
     llvm::FunctionType *FnTy =
         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
-    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
     break;
   }
   case OMPRTL__kmpc_push_num_threads: {
@@ -364,13 +515,54 @@
     break;
   }
   case OMPRTL__kmpc_flush: {
-    // Build void __kmpc_flush(ident_t *loc, ...);
+    // Build void __kmpc_flush(ident_t *loc);
     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
     llvm::FunctionType *FnTy =
-        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
     break;
   }
+  case OMPRTL__kmpc_master: {
+    // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
+    llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
+    break;
+  }
+  case OMPRTL__kmpc_end_master: {
+    // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
+    llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
+    break;
+  }
+  case OMPRTL__kmpc_omp_taskyield: {
+    // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
+    // int end_part);
+    llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
+    break;
+  }
+  case OMPRTL__kmpc_single: {
+    // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
+    llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
+    break;
+  }
+  case OMPRTL__kmpc_end_single: {
+    // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
+    llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
+    llvm::FunctionType *FnTy =
+        llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
+    RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
+    break;
+  }
   }
   return RTLFn;
 }
@@ -378,43 +570,41 @@
 llvm::Constant *
 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
   // Lookup the entry, lazily creating it if necessary.
-  return GetOrCreateInternalVariable(CGM.Int8PtrPtrTy,
+  return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
                                      Twine(CGM.getMangledName(VD)) + ".cache.");
 }
 
-llvm::Value *CGOpenMPRuntime::getOMPAddrOfThreadPrivate(CodeGenFunction &CGF,
-                                                        const VarDecl *VD,
-                                                        llvm::Value *VDAddr,
-                                                        SourceLocation Loc) {
+llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
+                                                     const VarDecl *VD,
+                                                     llvm::Value *VDAddr,
+                                                     SourceLocation Loc) {
   auto VarTy = VDAddr->getType()->getPointerElementType();
-  llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc),
-                         GetOpenMPThreadID(CGF, Loc),
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
                          CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
                          CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
                          getOrCreateThreadPrivateCache(VD)};
   return CGF.EmitRuntimeCall(
-      CreateRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
+      createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
 }
 
-void CGOpenMPRuntime::EmitOMPThreadPrivateVarInit(
+void CGOpenMPRuntime::emitThreadPrivateVarInit(
     CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
     llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
   // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
   // library.
-  auto OMPLoc = EmitOpenMPUpdateLocation(CGF, Loc);
-  CGF.EmitRuntimeCall(CreateRuntimeFunction(OMPRTL__kmpc_global_thread_num),
+  auto OMPLoc = emitUpdateLocation(CGF, Loc);
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
                       OMPLoc);
   // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
   // to register constructor/destructor for variable.
   llvm::Value *Args[] = {OMPLoc,
                          CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
                          Ctor, CopyCtor, Dtor};
-  CGF.EmitRuntimeCall(CreateRuntimeFunction(
-                          CGOpenMPRuntime::OMPRTL__kmpc_threadprivate_register),
-                      Args);
+  CGF.EmitRuntimeCall(
+      createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
 }
 
-llvm::Function *CGOpenMPRuntime::EmitOMPThreadPrivateVarDefinition(
+llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
     const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
     bool PerformInit, CodeGenFunction *CGF) {
   VD = VD->getDefinition(CGM.getContext());
@@ -517,44 +707,41 @@
       InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
                             CGM.getTypes().arrangeNullaryFunction(), ArgList,
                             Loc);
-      EmitOMPThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
+      emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
       InitCGF.FinishFunction();
       return InitFunction;
     }
-    EmitOMPThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
+    emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
   }
   return nullptr;
 }
 
-void CGOpenMPRuntime::EmitOMPParallelCall(CodeGenFunction &CGF,
-                                          SourceLocation Loc,
-                                          llvm::Value *OutlinedFn,
-                                          llvm::Value *CapturedStruct) {
+void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
+                                       llvm::Value *OutlinedFn,
+                                       llvm::Value *CapturedStruct) {
   // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
   llvm::Value *Args[] = {
-      EmitOpenMPUpdateLocation(CGF, Loc),
+      emitUpdateLocation(CGF, Loc),
       CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
       // (there is only one additional argument - 'context')
       CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
       CGF.EmitCastToVoidPtr(CapturedStruct)};
-  auto RTLFn = CreateRuntimeFunction(CGOpenMPRuntime::OMPRTL__kmpc_fork_call);
+  auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
   CGF.EmitRuntimeCall(RTLFn, Args);
 }
 
-void CGOpenMPRuntime::EmitOMPSerialCall(CodeGenFunction &CGF,
-                                        SourceLocation Loc,
-                                        llvm::Value *OutlinedFn,
-                                        llvm::Value *CapturedStruct) {
-  auto ThreadID = GetOpenMPThreadID(CGF, Loc);
+void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
+                                     llvm::Value *OutlinedFn,
+                                     llvm::Value *CapturedStruct) {
+  auto ThreadID = getThreadID(CGF, Loc);
   // Build calls:
   // __kmpc_serialized_parallel(&Loc, GTid);
-  llvm::Value *SerArgs[] = {EmitOpenMPUpdateLocation(CGF, Loc), ThreadID};
-  auto RTLFn =
-      CreateRuntimeFunction(CGOpenMPRuntime::OMPRTL__kmpc_serialized_parallel);
-  CGF.EmitRuntimeCall(RTLFn, SerArgs);
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
+                      Args);
 
   // OutlinedFn(&GTid, &zero, CapturedStruct);
-  auto ThreadIDAddr = EmitThreadIDAddress(CGF, Loc);
+  auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
   auto Int32Ty =
       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
   auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
@@ -563,10 +750,9 @@
   CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
 
   // __kmpc_end_serialized_parallel(&Loc, GTid);
-  llvm::Value *EndSerArgs[] = {EmitOpenMPUpdateLocation(CGF, Loc), ThreadID};
-  RTLFn = CreateRuntimeFunction(
-      CGOpenMPRuntime::OMPRTL__kmpc_end_serialized_parallel);
-  CGF.EmitRuntimeCall(RTLFn, EndSerArgs);
+  llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
+  CGF.EmitRuntimeCall(
+      createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
 }
 
 // If we're inside an (outlined) parallel region, use the region info's
@@ -575,13 +761,15 @@
 // regular serial code region, get thread ID by calling kmp_int32
 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
 // return the address of that temp.
-llvm::Value *CGOpenMPRuntime::EmitThreadIDAddress(CodeGenFunction &CGF,
+llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
                                                   SourceLocation Loc) {
   if (auto OMPRegionInfo =
           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
-    return CGF.EmitLoadOfLValue(OMPRegionInfo->getThreadIDVariableLValue(CGF),
-                                SourceLocation()).getScalarVal();
-  auto ThreadID = GetOpenMPThreadID(CGF, Loc);
+    if (OMPRegionInfo->getThreadIDVariable())
+      return CGF.EmitLoadOfLValue(OMPRegionInfo->getThreadIDVariableLValue(CGF),
+                                  Loc).getScalarVal();
+
+  auto ThreadID = getThreadID(CGF, Loc);
   auto Int32Ty =
       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
   auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
@@ -592,7 +780,7 @@
 }
 
 llvm::Constant *
-CGOpenMPRuntime::GetOrCreateInternalVariable(llvm::Type *Ty,
+CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
                                              const llvm::Twine &Name) {
   SmallString<256> Buffer;
   llvm::raw_svector_ostream Out(Buffer);
@@ -611,62 +799,260 @@
              Elem.first());
 }
 
-llvm::Value *CGOpenMPRuntime::GetCriticalRegionLock(StringRef CriticalName) {
+llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
   llvm::Twine Name(".gomp_critical_user_", CriticalName);
-  return GetOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
+  return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
 }
 
-void CGOpenMPRuntime::EmitOMPCriticalRegionStart(CodeGenFunction &CGF,
-                                                 llvm::Value *RegionLock,
-                                                 SourceLocation Loc) {
-  // Prepare other arguments and build a call to __kmpc_critical
-  llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc),
-                         GetOpenMPThreadID(CGF, Loc), RegionLock};
-  auto RTLFn = CreateRuntimeFunction(CGOpenMPRuntime::OMPRTL__kmpc_critical);
-  CGF.EmitRuntimeCall(RTLFn, Args);
+void CGOpenMPRuntime::emitCriticalRegion(
+    CodeGenFunction &CGF, StringRef CriticalName,
+    const std::function<void()> &CriticalOpGen, SourceLocation Loc) {
+  auto RegionLock = getCriticalRegionLock(CriticalName);
+  // __kmpc_critical(ident_t *, gtid, Lock);
+  // CriticalOpGen();
+  // __kmpc_end_critical(ident_t *, gtid, Lock);
+  // Prepare arguments and build a call to __kmpc_critical
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
+                         RegionLock};
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
+  CriticalOpGen();
+  // Build a call to __kmpc_end_critical
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
 }
 
-void CGOpenMPRuntime::EmitOMPCriticalRegionEnd(CodeGenFunction &CGF,
-                                               llvm::Value *RegionLock,
-                                               SourceLocation Loc) {
-  // Prepare other arguments and build a call to __kmpc_end_critical
-  llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc),
-                         GetOpenMPThreadID(CGF, Loc), RegionLock};
-  auto RTLFn =
-      CreateRuntimeFunction(CGOpenMPRuntime::OMPRTL__kmpc_end_critical);
-  CGF.EmitRuntimeCall(RTLFn, Args);
+static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
+                       const std::function<void()> &BodyOpGen) {
+  llvm::Value *CallBool = CGF.EmitScalarConversion(
+      IfCond,
+      CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
+      CGF.getContext().BoolTy);
+
+  auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
+  auto *ContBlock = CGF.createBasicBlock("omp_if.end");
+  // Generate the branch (If-stmt)
+  CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
+  CGF.EmitBlock(ThenBlock);
+  BodyOpGen();
+  // Emit the rest of bblocks/branches
+  CGF.EmitBranch(ContBlock);
+  CGF.EmitBlock(ContBlock, true);
 }
 
-void CGOpenMPRuntime::EmitOMPBarrierCall(CodeGenFunction &CGF,
-                                         SourceLocation Loc,
-                                         OpenMPLocationFlags Flags) {
-  // Build call __kmpc_barrier(loc, thread_id)
-  llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc, Flags),
-                         GetOpenMPThreadID(CGF, Loc)};
-  auto RTLFn = CreateRuntimeFunction(CGOpenMPRuntime::OMPRTL__kmpc_barrier);
-  CGF.EmitRuntimeCall(RTLFn, Args);
+void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
+                                       const std::function<void()> &MasterOpGen,
+                                       SourceLocation Loc) {
+  // if(__kmpc_master(ident_t *, gtid)) {
+  //   MasterOpGen();
+  //   __kmpc_end_master(ident_t *, gtid);
+  // }
+  // Prepare arguments and build a call to __kmpc_master
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
+  auto *IsMaster =
+      CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
+  emitIfStmt(CGF, IsMaster, [&]() -> void {
+    MasterOpGen();
+    // Build a call to __kmpc_end_master.
+    // OpenMP [1.2.2 OpenMP Language Terminology]
+    // For C/C++, an executable statement, possibly compound, with a single
+    // entry at the top and a single exit at the bottom, or an OpenMP construct.
+    // * Access to the structured block must not be the result of a branch.
+    // * The point of exit cannot be a branch out of the structured block.
+    // * The point of entry must not be a call to setjmp().
+    // * longjmp() and throw() must not violate the entry/exit criteria.
+    // * An expression statement, iteration statement, selection statement, or
+    // try block is considered to be a structured block if the corresponding
+    // compound statement obtained by enclosing it in { and } would be a
+    // structured block.
+    // It is analyzed in Sema, so we can just call __kmpc_end_master() on
+    // fallthrough rather than pushing a normal cleanup for it.
+    CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_master), Args);
+  });
 }
 
-void CGOpenMPRuntime::EmitOMPNumThreadsClause(CodeGenFunction &CGF,
-                                              llvm::Value *NumThreads,
-                                              SourceLocation Loc) {
+void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
+                                        SourceLocation Loc) {
+  // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
+  llvm::Value *Args[] = {
+      emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
+      llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
+}
+
+void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
+                                       const std::function<void()> &SingleOpGen,
+                                       SourceLocation Loc) {
+  // if(__kmpc_single(ident_t *, gtid)) {
+  //   SingleOpGen();
+  //   __kmpc_end_single(ident_t *, gtid);
+  // }
+  // Prepare arguments and build a call to __kmpc_single
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
+  auto *IsSingle =
+      CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
+  emitIfStmt(CGF, IsSingle, [&]() -> void {
+    SingleOpGen();
+    // Build a call to __kmpc_end_single.
+    // OpenMP [1.2.2 OpenMP Language Terminology]
+    // For C/C++, an executable statement, possibly compound, with a single
+    // entry at the top and a single exit at the bottom, or an OpenMP construct.
+    // * Access to the structured block must not be the result of a branch.
+    // * The point of exit cannot be a branch out of the structured block.
+    // * The point of entry must not be a call to setjmp().
+    // * longjmp() and throw() must not violate the entry/exit criteria.
+    // * An expression statement, iteration statement, selection statement, or
+    // try block is considered to be a structured block if the corresponding
+    // compound statement obtained by enclosing it in { and } would be a
+    // structured block.
+    // It is analyzed in Sema, so we can just call __kmpc_end_single() on
+    // fallthrough rather than pushing a normal cleanup for it.
+    CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_single), Args);
+  });
+}
+
+void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
+                                      bool IsExplicit) {
+  // Build call __kmpc_cancel_barrier(loc, thread_id);
+  auto Flags = static_cast<OpenMPLocationFlags>(
+      OMP_IDENT_KMPC |
+      (IsExplicit ? OMP_IDENT_BARRIER_EXPL : OMP_IDENT_BARRIER_IMPL));
+  // Build call __kmpc_cancel_barrier(loc, thread_id);
+  // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
+  // one provides the same functionality and adds initial support for
+  // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
+  // is provided default by the runtime library so it safe to make such
+  // replacement.
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
+                         getThreadID(CGF, Loc)};
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
+}
+
+/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
+/// the enum sched_type in kmp.h).
+enum OpenMPSchedType {
+  /// \brief Lower bound for default (unordered) versions.
+  OMP_sch_lower = 32,
+  OMP_sch_static_chunked = 33,
+  OMP_sch_static = 34,
+  OMP_sch_dynamic_chunked = 35,
+  OMP_sch_guided_chunked = 36,
+  OMP_sch_runtime = 37,
+  OMP_sch_auto = 38,
+  /// \brief Lower bound for 'ordered' versions.
+  OMP_ord_lower = 64,
+  /// \brief Lower bound for 'nomerge' versions.
+  OMP_nm_lower = 160,
+};
+
+/// \brief Map the OpenMP loop schedule to the runtime enumeration.
+static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
+                                          bool Chunked) {
+  switch (ScheduleKind) {
+  case OMPC_SCHEDULE_static:
+    return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
+  case OMPC_SCHEDULE_dynamic:
+    return OMP_sch_dynamic_chunked;
+  case OMPC_SCHEDULE_guided:
+    return OMP_sch_guided_chunked;
+  case OMPC_SCHEDULE_auto:
+    return OMP_sch_auto;
+  case OMPC_SCHEDULE_runtime:
+    return OMP_sch_runtime;
+  case OMPC_SCHEDULE_unknown:
+    assert(!Chunked && "chunk was specified but schedule kind not known");
+    return OMP_sch_static;
+  }
+  llvm_unreachable("Unexpected runtime schedule");
+}
+
+bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
+                                         bool Chunked) const {
+  auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
+  return Schedule == OMP_sch_static;
+}
+
+bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
+  auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
+  assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
+  return Schedule != OMP_sch_static;
+}
+
+void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
+                                  OpenMPScheduleClauseKind ScheduleKind,
+                                  unsigned IVSize, bool IVSigned,
+                                  llvm::Value *IL, llvm::Value *LB,
+                                  llvm::Value *UB, llvm::Value *ST,
+                                  llvm::Value *Chunk) {
+  OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
+  // Call __kmpc_for_static_init(
+  //          ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
+  //          kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
+  //          kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
+  //          kmp_int[32|64] incr, kmp_int[32|64] chunk);
+  // TODO: Implement dynamic schedule.
+
+  // If the Chunk was not specified in the clause - use default value 1.
+  if (Chunk == nullptr)
+    Chunk = CGF.Builder.getIntN(IVSize, /*C*/ 1);
+
+  llvm::Value *Args[] = {
+      emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
+      CGF.Builder.getInt32(Schedule), // Schedule type
+      IL,                             // &isLastIter
+      LB,                             // &LB
+      UB,                             // &UB
+      ST,                             // &Stride
+      CGF.Builder.getIntN(IVSize, 1), // Incr
+      Chunk                           // Chunk
+  };
+  assert((IVSize == 32 || IVSize == 64) &&
+         "Index size is not compatible with the omp runtime");
+  auto F = IVSize == 32 ? (IVSigned ? OMPRTL__kmpc_for_static_init_4
+                                    : OMPRTL__kmpc_for_static_init_4u)
+                        : (IVSigned ? OMPRTL__kmpc_for_static_init_8
+                                    : OMPRTL__kmpc_for_static_init_8u);
+  CGF.EmitRuntimeCall(createRuntimeFunction(F), Args);
+}
+
+void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
+                                    OpenMPScheduleClauseKind ScheduleKind) {
+  assert((ScheduleKind == OMPC_SCHEDULE_static ||
+          ScheduleKind == OMPC_SCHEDULE_unknown) &&
+         "Non-static schedule kinds are not yet implemented");
+  // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
+  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
+                         getThreadID(CGF, Loc)};
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
+                      Args);
+}
+
+void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
+                                           llvm::Value *NumThreads,
+                                           SourceLocation Loc) {
   // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
   llvm::Value *Args[] = {
-      EmitOpenMPUpdateLocation(CGF, Loc), GetOpenMPThreadID(CGF, Loc),
+      emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
       CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
-  llvm::Constant *RTLFn = CGF.CGM.getOpenMPRuntime().CreateRuntimeFunction(
-      CGOpenMPRuntime::OMPRTL__kmpc_push_num_threads);
-  CGF.EmitRuntimeCall(RTLFn, Args);
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
+                      Args);
 }
 
-void CGOpenMPRuntime::EmitOMPFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
-                                   SourceLocation Loc) {
-  // Build call void __kmpc_flush(ident_t *loc, ...)
-  // FIXME: List of variables is ignored by libiomp5 runtime, no need to
-  // generate it, just request full memory fence.
-  llvm::Value *Args[] = {EmitOpenMPUpdateLocation(CGF, Loc),
-                         llvm::ConstantInt::get(CGM.Int32Ty, 0)};
-  auto *RTLFn = CGF.CGM.getOpenMPRuntime().CreateRuntimeFunction(
-      CGOpenMPRuntime::OMPRTL__kmpc_flush);
-  CGF.EmitRuntimeCall(RTLFn, Args);
+void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
+                                SourceLocation Loc) {
+  // Build call void __kmpc_flush(ident_t *loc)
+  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
+                      emitUpdateLocation(CGF, Loc));
 }
+
+InlinedOpenMPRegionRAII::InlinedOpenMPRegionRAII(
+    CodeGenFunction &CGF, const OMPExecutableDirective &D)
+    : CGF(CGF) {
+  CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(D, CGF.CapturedStmtInfo);
+}
+
+InlinedOpenMPRegionRAII::~InlinedOpenMPRegionRAII() {
+  auto *OldCSI =
+      cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
+  delete CGF.CapturedStmtInfo;
+  CGF.CapturedStmtInfo = OldCSI;
+}
+
diff --git a/lib/CodeGen/CGOpenMPRuntime.h b/lib/CodeGen/CGOpenMPRuntime.h
index b9c1a35..97aa5b8 100644
--- a/lib/CodeGen/CGOpenMPRuntime.h
+++ b/lib/CodeGen/CGOpenMPRuntime.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
 
+#include "clang/Basic/OpenMPKinds.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
@@ -42,7 +43,57 @@
 class CodeGenModule;
 
 class CGOpenMPRuntime {
-public:
+  enum OpenMPRTLFunction {
+    /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
+    /// kmpc_micro microtask, ...);
+    OMPRTL__kmpc_fork_call,
+    /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
+    /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
+    OMPRTL__kmpc_threadprivate_cached,
+    /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
+    /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
+    OMPRTL__kmpc_threadprivate_register,
+    // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
+    OMPRTL__kmpc_global_thread_num,
+    // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
+    // kmp_critical_name *crit);
+    OMPRTL__kmpc_critical,
+    // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
+    // kmp_critical_name *crit);
+    OMPRTL__kmpc_end_critical,
+    // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
+    // global_tid);
+    OMPRTL__kmpc_cancel_barrier,
+    // Calls for static scheduling 'omp for' loops.
+    OMPRTL__kmpc_for_static_init_4,
+    OMPRTL__kmpc_for_static_init_4u,
+    OMPRTL__kmpc_for_static_init_8,
+    OMPRTL__kmpc_for_static_init_8u,
+    OMPRTL__kmpc_for_static_fini,
+    // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
+    // global_tid);
+    OMPRTL__kmpc_serialized_parallel,
+    // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
+    // global_tid);
+    OMPRTL__kmpc_end_serialized_parallel,
+    // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
+    // kmp_int32 num_threads);
+    OMPRTL__kmpc_push_num_threads,
+    // Call to void __kmpc_flush(ident_t *loc);
+    OMPRTL__kmpc_flush,
+    // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
+    OMPRTL__kmpc_master,
+    // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
+    OMPRTL__kmpc_end_master,
+    // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
+    // int end_part);
+    OMPRTL__kmpc_omp_taskyield,
+    // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
+    OMPRTL__kmpc_single,
+    // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
+    OMPRTL__kmpc_end_single,
+  };
+
   /// \brief Values for bit flags used in the ident_t to describe the fields.
   /// All enumeric elements are named and described in accordance with the code
   /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
@@ -64,40 +115,6 @@
     /// \brief Implicit barrier in 'single' directive.
     OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
   };
-  enum OpenMPRTLFunction {
-    /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
-    /// kmpc_micro microtask, ...);
-    OMPRTL__kmpc_fork_call,
-    /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
-    /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
-    OMPRTL__kmpc_threadprivate_cached,
-    /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
-    /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
-    OMPRTL__kmpc_threadprivate_register,
-    // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
-    OMPRTL__kmpc_global_thread_num,
-    // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
-    // kmp_critical_name *crit);
-    OMPRTL__kmpc_critical,
-    // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
-    // kmp_critical_name *crit);
-    OMPRTL__kmpc_end_critical,
-    // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
-    OMPRTL__kmpc_barrier,
-    // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
-    // global_tid);
-    OMPRTL__kmpc_serialized_parallel,
-    // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
-    // global_tid);
-    OMPRTL__kmpc_end_serialized_parallel,
-    // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
-    // kmp_int32 num_threads);
-    OMPRTL__kmpc_push_num_threads,
-    // Call to void __kmpc_flush(ident_t *loc, ...);
-    OMPRTL__kmpc_flush
-  };
-
-private:
   CodeGenModule &CGM;
   /// \brief Default const ident_t object used for initialization of all other
   /// ident_t objects.
@@ -105,7 +122,7 @@
   /// \brief Map of flags and corresponding default locations.
   typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDefaultLocMapTy;
   OpenMPDefaultLocMapTy OpenMPDefaultLocMap;
-  llvm::Value *GetOrCreateDefaultOpenMPLocation(OpenMPLocationFlags Flags);
+  llvm::Value *getOrCreateDefaultLocation(OpenMPLocationFlags Flags);
   /// \brief Describes ident structure that describes a source location.
   /// All descriptions are taken from
   /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
@@ -177,9 +194,8 @@
   /// \brief Emits object of ident_t type with info for source location.
   /// \param Flags Flags for OpenMP location.
   ///
-  llvm::Value *
-  EmitOpenMPUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,
-                           OpenMPLocationFlags Flags = OMP_IDENT_KMPC);
+  llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,
+                                  OpenMPLocationFlags Flags = OMP_IDENT_KMPC);
 
   /// \brief Returns pointer to ident_t type.
   llvm::Type *getIdentTyPointerTy();
@@ -190,7 +206,7 @@
   /// \brief Returns specified OpenMP runtime function.
   /// \param Function OpenMP runtime function.
   /// \return Specified function.
-  llvm::Constant *CreateRuntimeFunction(OpenMPRTLFunction Function);
+  llvm::Constant *createRuntimeFunction(OpenMPRTLFunction Function);
 
   /// \brief If the specified mangled name is not in the module, create and
   /// return threadprivate cache object. This object is a pointer's worth of
@@ -201,12 +217,12 @@
 
   /// \brief Emits address of the word in a memory where current thread id is
   /// stored.
-  virtual llvm::Value *EmitThreadIDAddress(CodeGenFunction &CGF,
+  virtual llvm::Value *emitThreadIDAddress(CodeGenFunction &CGF,
                                            SourceLocation Loc);
 
   /// \brief Gets thread id value for the current thread.
   ///
-  llvm::Value *GetOpenMPThreadID(CodeGenFunction &CGF, SourceLocation Loc);
+  llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc);
 
   /// \brief Gets (if variable with the given name already exist) or creates
   /// internal global variable with the specified Name. The created variable has
@@ -214,7 +230,7 @@
   /// \param Ty Type of the global variable. If it is exist already the type
   /// must be the same.
   /// \param Name Name of the variable.
-  llvm::Constant *GetOrCreateInternalVariable(llvm::Type *Ty,
+  llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty,
                                               const llvm::Twine &Name);
 
   /// \brief Set of threadprivate variables with the generated initializer.
@@ -226,9 +242,16 @@
   /// \param CopyCtor Pointer to a global copy function for \a VD.
   /// \param Dtor Pointer to a global destructor function for \a VD.
   /// \param Loc Location of threadprivate declaration.
-  void EmitOMPThreadPrivateVarInit(CodeGenFunction &CGF, llvm::Value *VDAddr,
-                                   llvm::Value *Ctor, llvm::Value *CopyCtor,
-                                   llvm::Value *Dtor, SourceLocation Loc);
+  void emitThreadPrivateVarInit(CodeGenFunction &CGF, llvm::Value *VDAddr,
+                                llvm::Value *Ctor, llvm::Value *CopyCtor,
+                                llvm::Value *Dtor, SourceLocation Loc);
+
+  /// \brief Returns corresponding lock object for the specified critical region
+  /// name. If the lock object does not exist it is created, otherwise the
+  /// reference to the existing copy is returned.
+  /// \param CriticalName Name of the critical region.
+  ///
+  llvm::Value *getCriticalRegionLock(StringRef CriticalName);
 
 public:
   explicit CGOpenMPRuntime(CodeGenModule &CGM);
@@ -241,13 +264,12 @@
   /// \param D OpenMP directive.
   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
   ///
-  virtual llvm::Value *
-  EmitOpenMPOutlinedFunction(const OMPExecutableDirective &D,
-                             const VarDecl *ThreadIDVar);
+  virtual llvm::Value *emitOutlinedFunction(const OMPExecutableDirective &D,
+                                            const VarDecl *ThreadIDVar);
 
   /// \brief Cleans up references to the objects in finished function.
   ///
-  void FunctionFinished(CodeGenFunction &CGF);
+  void functionFinished(CodeGenFunction &CGF);
 
   /// \brief Emits code for parallel call of the \a OutlinedFn with variables
   /// captured in a record which address is stored in \a CapturedStruct.
@@ -256,9 +278,9 @@
   /// \param CapturedStruct A pointer to the record with the references to
   /// variables used in \a OutlinedFn function.
   ///
-  virtual void EmitOMPParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
-                                   llvm::Value *OutlinedFn,
-                                   llvm::Value *CapturedStruct);
+  virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
+                                llvm::Value *OutlinedFn,
+                                llvm::Value *CapturedStruct);
 
   /// \brief Emits code for serial call of the \a OutlinedFn with variables
   /// captured in a record which address is stored in \a CapturedStruct.
@@ -266,46 +288,101 @@
   /// \param CapturedStruct A pointer to the record with the references to
   /// variables used in \a OutlinedFn function.
   ///
-  virtual void EmitOMPSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
-                                 llvm::Value *OutlinedFn,
-                                 llvm::Value *CapturedStruct);
+  virtual void emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
+                              llvm::Value *OutlinedFn,
+                              llvm::Value *CapturedStruct);
 
-  /// \brief Returns corresponding lock object for the specified critical region
-  /// name. If the lock object does not exist it is created, otherwise the
-  /// reference to the existing copy is returned.
+  /// \brief Emits a critical region.
   /// \param CriticalName Name of the critical region.
+  /// \param CriticalOpGen Generator for the statement associated with the given
+  /// critical region.
+  virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
+                                  const std::function<void()> &CriticalOpGen,
+                                  SourceLocation Loc);
+
+  /// \brief Emits a master region.
+  /// \param MasterOpGen Generator for the statement associated with the given
+  /// master region.
+  virtual void emitMasterRegion(CodeGenFunction &CGF,
+                                const std::function<void()> &MasterOpGen,
+                                SourceLocation Loc);
+
+  /// \brief Emits code for a taskyield directive.
+  virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);
+
+  /// \brief Emits a single region.
+  /// \param SingleOpGen Generator for the statement associated with the given
+  /// single region.
+  virtual void emitSingleRegion(CodeGenFunction &CGF,
+                                const std::function<void()> &SingleOpGen,
+                                SourceLocation Loc);
+
+  /// \brief Emits explicit barrier for OpenMP threads.
+  /// \param IsExplicit true, if it is explicitly specified barrier.
   ///
-  llvm::Value *GetCriticalRegionLock(StringRef CriticalName);
+  virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
+                               bool IsExplicit = true);
 
-  /// \brief Emits start of the critical region by calling void
-  /// __kmpc_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name
-  /// * \a RegionLock)
-  /// \param RegionLock The lock object for critical region.
-  virtual void EmitOMPCriticalRegionStart(CodeGenFunction &CGF,
-                                          llvm::Value *RegionLock,
-                                          SourceLocation Loc);
-
-  /// \brief Emits end of the critical region by calling void
-  /// __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, kmp_critical_name
-  /// * \a RegionLock)
-  /// \param RegionLock The lock object for critical region.
-  virtual void EmitOMPCriticalRegionEnd(CodeGenFunction &CGF,
-                                        llvm::Value *RegionLock,
-                                        SourceLocation Loc);
-
-  /// \brief Emits a barrier for OpenMP threads.
-  /// \param Flags Flags for the barrier.
+  /// \brief Check if the specified \a ScheduleKind is static non-chunked.
+  /// This kind of worksharing directive is emitted without outer loop.
+  /// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
+  /// \param Chunked True if chunk is specified in the clause.
   ///
-  virtual void EmitOMPBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
-                                  OpenMPLocationFlags Flags);
+  virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
+                                  bool Chunked) const;
+
+  /// \brief Check if the specified \a ScheduleKind is dynamic.
+  /// This kind of worksharing directive is emitted without outer loop.
+  /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.
+  ///
+  virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const;
+
+  /// \brief Call the appropriate runtime routine to initialize it before start
+  /// of loop.
+  ///
+  /// Depending on the loop schedule, it is nesessary to call some runtime
+  /// routine before start of the OpenMP loop to get the loop upper / lower
+  /// bounds \a LB and \a UB and stride \a ST.
+  ///
+  /// \param CGF Reference to current CodeGenFunction.
+  /// \param Loc Clang source location.
+  /// \param SchedKind Schedule kind, specified by the 'schedule' clause.
+  /// \param IVSize Size of the iteration variable in bits.
+  /// \param IVSigned Sign of the interation variable.
+  /// \param IL Address of the output variable in which the flag of the
+  /// last iteration is returned.
+  /// \param LB Address of the output variable in which the lower iteration
+  /// number is returned.
+  /// \param UB Address of the output variable in which the upper iteration
+  /// number is returned.
+  /// \param ST Address of the output variable in which the stride value is
+  /// returned nesessary to generated the static_chunked scheduled loop.
+  /// \param Chunk Value of the chunk for the static_chunked scheduled loop.
+  /// For the default (nullptr) value, the chunk 1 will be used.
+  ///
+  virtual void emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
+                           OpenMPScheduleClauseKind SchedKind, unsigned IVSize,
+                           bool IVSigned, llvm::Value *IL, llvm::Value *LB,
+                           llvm::Value *UB, llvm::Value *ST,
+                           llvm::Value *Chunk = nullptr);
+
+  /// \brief Call the appropriate runtime routine to notify that we finished
+  /// all the work with current loop.
+  ///
+  /// \param CGF Reference to current CodeGenFunction.
+  /// \param Loc Clang source location.
+  /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
+  ///
+  virtual void emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
+                             OpenMPScheduleClauseKind ScheduleKind);
 
   /// \brief Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
   /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
   /// clause.
   /// \param NumThreads An integer value of threads.
-  virtual void EmitOMPNumThreadsClause(CodeGenFunction &CGF,
-                                       llvm::Value *NumThreads,
-                                       SourceLocation Loc);
+  virtual void emitNumThreadsClause(CodeGenFunction &CGF,
+                                    llvm::Value *NumThreads,
+                                    SourceLocation Loc);
 
   /// \brief Returns address of the threadprivate variable for the current
   /// thread.
@@ -313,10 +390,10 @@
   /// \param VDAddr Address of the global variable \a VD.
   /// \param Loc Location of the reference to threadprivate var.
   /// \return Address of the threadprivate variable for the current thread.
-  virtual llvm::Value *getOMPAddrOfThreadPrivate(CodeGenFunction &CGF,
-                                                 const VarDecl *VD,
-                                                 llvm::Value *VDAddr,
-                                                 SourceLocation Loc);
+  virtual llvm::Value *getAddrOfThreadPrivate(CodeGenFunction &CGF,
+                                              const VarDecl *VD,
+                                              llvm::Value *VDAddr,
+                                              SourceLocation Loc);
 
   /// \brief Emit a code for initialization of threadprivate variable. It emits
   /// a call to runtime library which adds initial value to the newly created
@@ -327,14 +404,24 @@
   /// \param Loc Location of threadprivate declaration.
   /// \param PerformInit true if initialization expression is not constant.
   virtual llvm::Function *
-  EmitOMPThreadPrivateVarDefinition(const VarDecl *VD, llvm::Value *VDAddr,
-                                    SourceLocation Loc, bool PerformInit,
-                                    CodeGenFunction *CGF = nullptr);
+  emitThreadPrivateVarDefinition(const VarDecl *VD, llvm::Value *VDAddr,
+                                 SourceLocation Loc, bool PerformInit,
+                                 CodeGenFunction *CGF = nullptr);
 
   /// \brief Emit flush of the variables specified in 'omp flush' directive.
   /// \param Vars List of variables to flush.
-  virtual void EmitOMPFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
-                            SourceLocation Loc);
+  virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
+                         SourceLocation Loc);
+};
+
+/// \brief RAII for emitting code of CapturedStmt without function outlining.
+class InlinedOpenMPRegionRAII {
+  CodeGenFunction &CGF;
+
+public:
+  InlinedOpenMPRegionRAII(CodeGenFunction &CGF,
+                          const OMPExecutableDirective &D);
+  ~InlinedOpenMPRegionRAII();
 };
 } // namespace CodeGen
 } // namespace clang
diff --git a/lib/CodeGen/CGRecordLayout.h b/lib/CodeGen/CGRecordLayout.h
index 2de0b2f..c15f9fd 100644
--- a/lib/CodeGen/CGRecordLayout.h
+++ b/lib/CodeGen/CGRecordLayout.h
@@ -109,8 +109,8 @@
 class CGRecordLayout {
   friend class CodeGenTypes;
 
-  CGRecordLayout(const CGRecordLayout &) LLVM_DELETED_FUNCTION;
-  void operator=(const CGRecordLayout &) LLVM_DELETED_FUNCTION;
+  CGRecordLayout(const CGRecordLayout &) = delete;
+  void operator=(const CGRecordLayout &) = delete;
 
 private:
   /// The LLVM type corresponding to this record layout; used when
diff --git a/lib/CodeGen/CGRecordLayoutBuilder.cpp b/lib/CodeGen/CGRecordLayoutBuilder.cpp
index 7ad394b..202ea97 100644
--- a/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ b/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -198,8 +198,8 @@
   bool IsZeroInitializableAsBase : 1;
   bool Packed : 1;
 private:
-  CGRecordLowering(const CGRecordLowering &) LLVM_DELETED_FUNCTION;
-  void operator =(const CGRecordLowering &) LLVM_DELETED_FUNCTION;
+  CGRecordLowering(const CGRecordLowering &) = delete;
+  void operator =(const CGRecordLowering &) = delete;
 };
 } // namespace {
 
diff --git a/lib/CodeGen/CGStmt.cpp b/lib/CodeGen/CGStmt.cpp
index f207a4f..0d160d3 100644
--- a/lib/CodeGen/CGStmt.cpp
+++ b/lib/CodeGen/CGStmt.cpp
@@ -88,6 +88,7 @@
   case Stmt::ContinueStmtClass:
   case Stmt::DefaultStmtClass:
   case Stmt::CaseStmtClass:
+  case Stmt::SEHLeaveStmtClass:
     llvm_unreachable("should have emitted these statements as simple");
 
 #define STMT(Type, Base)
@@ -173,9 +174,6 @@
   case Stmt::SEHTryStmtClass:
     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
     break;
-  case Stmt::SEHLeaveStmtClass:
-    EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S));
-    break;
   case Stmt::OMPParallelDirectiveClass:
     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
     break;
@@ -256,6 +254,7 @@
   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
+  case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
   }
 
   return true;
@@ -564,8 +563,8 @@
   // Emit the 'else' code if present.
   if (const Stmt *Else = S.getElse()) {
     {
-      // There is no need to emit line number for unconditional branch.
-      SuppressDebugLocation S(Builder);
+      // There is no need to emit line number for an unconditional branch.
+      auto NL = ApplyDebugLocation::CreateEmpty(*this);
       EmitBlock(ElseBlock);
     }
     {
@@ -573,8 +572,8 @@
       EmitStmt(Else);
     }
     {
-      // There is no need to emit line number for unconditional branch.
-      SuppressDebugLocation S(Builder);
+      // There is no need to emit line number for an unconditional branch.
+      auto NL = ApplyDebugLocation::CreateEmpty(*this);
       EmitBranch(ContBlock);
     }
   }
@@ -591,7 +590,9 @@
     return;
 
   // Add vectorize and unroll hints to the metadata on the conditional branch.
-  SmallVector<llvm::Value *, 2> Metadata(1);
+  //
+  // FIXME: Should this really start with a size of 1?
+  SmallVector<llvm::Metadata *, 2> Metadata(1);
   for (const auto *Attr : Attrs) {
     const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
 
@@ -629,7 +630,7 @@
       ValueInt = static_cast<int>(ValueAPS.getSExtValue());
     }
 
-    llvm::Value *Value;
+    llvm::Constant *Value;
     llvm::MDString *Name;
     switch (Option) {
     case LoopHintAttr::Vectorize:
@@ -656,15 +657,16 @@
       break;
     }
 
-    SmallVector<llvm::Value *, 2> OpValues;
+    SmallVector<llvm::Metadata *, 2> OpValues;
     OpValues.push_back(Name);
     if (Value)
-      OpValues.push_back(Value);
+      OpValues.push_back(llvm::ConstantAsMetadata::get(Value));
 
     // Set or overwrite metadata indicated by Name.
     Metadata.push_back(llvm::MDNode::get(Context, OpValues));
   }
 
+  // FIXME: This condition is never false.  Should it be an assert?
   if (!Metadata.empty()) {
     // Add llvm.loop MDNode to CondBr.
     llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
@@ -1656,6 +1658,12 @@
       while (Constraint[1] && Constraint[1] != ',')
         Constraint++;
       break;
+    case '&':
+    case '%':
+      Result += *Constraint;
+      while (Constraint[1] && Constraint[1] == *Constraint)
+        Constraint++;
+      break;
     case ',':
       Result += "|";
       break;
@@ -1687,7 +1695,7 @@
 static std::string
 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
                        const TargetInfo &Target, CodeGenModule &CGM,
-                       const AsmStmt &Stmt) {
+                       const AsmStmt &Stmt, const bool EarlyClobber) {
   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
   if (!AsmDeclRef)
     return Constraint;
@@ -1712,7 +1720,7 @@
   }
   // Canonicalize the register here before returning it.
   Register = Target.getNormalizedGCCRegisterName(Register);
-  return "{" + Register.str() + "}";
+  return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
 }
 
 llvm::Value*
@@ -1766,10 +1774,10 @@
 /// asm.
 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
                                       CodeGenFunction &CGF) {
-  SmallVector<llvm::Value *, 8> Locs;
+  SmallVector<llvm::Metadata *, 8> Locs;
   // Add the location of the first line to the MDNode.
-  Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
-                                        Str->getLocStart().getRawEncoding()));
+  Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+      CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
   StringRef StrVal = Str->getString();
   if (!StrVal.empty()) {
     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
@@ -1781,8 +1789,8 @@
       if (StrVal[i] != '\n') continue;
       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
                                                       CGF.getTarget());
-      Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
-                                            LineLoc.getRawEncoding()));
+      Locs.push_back(llvm::ConstantAsMetadata::get(
+          llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
     }
   }
 
@@ -1845,7 +1853,8 @@
     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
 
     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
-                                              getTarget(), CGM, S);
+                                              getTarget(), CGM, S,
+                                              Info.earlyClobber());
 
     LValue Dest = EmitLValue(OutExpr);
     if (!Constraints.empty())
@@ -1947,10 +1956,9 @@
     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
                                          &OutputConstraintInfos);
 
-    InputConstraint =
-      AddVariableConstraints(InputConstraint,
-                            *InputExpr->IgnoreParenNoopCasts(getContext()),
-                            getTarget(), CGM, S);
+    InputConstraint = AddVariableConstraints(
+        InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
+        getTarget(), CGM, S, false /* No EarlyClobber */);
 
     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
 
@@ -2052,7 +2060,9 @@
   } else {
     // At least put the line number on MS inline asm blobs.
     auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
-    Result->setMetadata("srcloc", llvm::MDNode::get(getLLVMContext(), Loc));
+    Result->setMetadata("srcloc",
+                        llvm::MDNode::get(getLLVMContext(),
+                                          llvm::ConstantAsMetadata::get(Loc)));
   }
 
   // Extract all of the register value results from the asm.
@@ -2208,8 +2218,6 @@
   PGO.assignRegionCounters(CD, F);
   CapturedStmtInfo->EmitBody(*this, CD->getBody());
   FinishFunction(CD->getBodyRBrace());
-  PGO.emitInstrumentationData();
-  PGO.destroyRegionCounters();
 
   return F;
 }
diff --git a/lib/CodeGen/CGStmtOpenMP.cpp b/lib/CodeGen/CGStmtOpenMP.cpp
index b160f17..daf5fcc 100644
--- a/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/lib/CodeGen/CGStmtOpenMP.cpp
@@ -14,9 +14,9 @@
 #include "CGOpenMPRuntime.h"
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
+#include "TargetInfo.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtOpenMP.h"
-#include "TargetInfo.h"
 using namespace clang;
 using namespace CodeGen;
 
@@ -57,13 +57,13 @@
   // Emit the 'else' code if present.
   {
     // There is no need to emit line number for unconditional branch.
-    SuppressDebugLocation SDL(CGF.Builder);
+    auto NL = ApplyDebugLocation::CreateEmpty(CGF);
     CGF.EmitBlock(ElseBlock);
   }
   CodeGen(/*ThenBlock*/ false);
   {
     // There is no need to emit line number for unconditional branch.
-    SuppressDebugLocation SDL(CGF.Builder);
+    auto NL = ApplyDebugLocation::CreateEmpty(CGF);
     CGF.EmitBranch(ContBlock);
   }
   // Emit the continuation block for code after the if.
@@ -220,17 +220,17 @@
     auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
     auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
                                          /*IgnoreResultAssign*/ true);
-    CGF.CGM.getOpenMPRuntime().EmitOMPNumThreadsClause(
+    CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
         CGF, NumThreads, NumThreadsClause->getLocStart());
   }
-  CGF.CGM.getOpenMPRuntime().EmitOMPParallelCall(CGF, S.getLocStart(),
-                                                 OutlinedFn, CapturedStruct);
+  CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
+                                              CapturedStruct);
 }
 
 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
   auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
-  auto OutlinedFn = CGM.getOpenMPRuntime().EmitOpenMPOutlinedFunction(
+  auto OutlinedFn = CGM.getOpenMPRuntime().emitOutlinedFunction(
       S, *CS->getCapturedDecl()->param_begin());
   if (auto C = S.getSingleClause(/*K*/ OMPC_if)) {
     auto Cond = cast<OMPIfClause>(C)->getCondition();
@@ -238,8 +238,8 @@
       if (ThenBlock)
         EmitOMPParallelCall(*this, S, OutlinedFn, CapturedStruct);
       else
-        CGM.getOpenMPRuntime().EmitOMPSerialCall(*this, S.getLocStart(),
-                                                 OutlinedFn, CapturedStruct);
+        CGM.getOpenMPRuntime().emitSerialCall(*this, S.getLocStart(),
+                                              OutlinedFn, CapturedStruct);
     });
   } else
     EmitOMPParallelCall(*this, S, OutlinedFn, CapturedStruct);
@@ -417,6 +417,7 @@
     }
   }
 
+  InlinedOpenMPRegionRAII Region(*this, S);
   RunCleanupsScope DirectiveScope(*this);
 
   CGDebugInfo *DI = getDebugInfo();
@@ -470,8 +471,199 @@
     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
 }
 
-void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &) {
-  llvm_unreachable("CodeGen for 'omp for' is not supported yet.");
+void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
+                                          const OMPLoopDirective &S,
+                                          OMPPrivateScope &LoopScope,
+                                          llvm::Value *LB, llvm::Value *UB,
+                                          llvm::Value *ST, llvm::Value *IL,
+                                          llvm::Value *Chunk) {
+  auto &RT = CGM.getOpenMPRuntime();
+  assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
+         "static non-chunked schedule does not need outer loop");
+  if (RT.isDynamic(ScheduleKind)) {
+    ErrorUnsupported(&S, "OpenMP loop with dynamic schedule");
+    return;
+  }
+
+  // Emit outer loop.
+  //
+  // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
+  // When schedule(static, chunk_size) is specified, iterations are divided into
+  // chunks of size chunk_size, and the chunks are assigned to the threads in
+  // the team in a round-robin fashion in the order of the thread number.
+  //
+  // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
+  //   while (idx <= UB) { BODY; ++idx; } // inner loop
+  //   LB = LB + ST;
+  //   UB = UB + ST;
+  // }
+  //
+  const Expr *IVExpr = S.getIterationVariable();
+  const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
+  const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
+
+  RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
+                 UB, ST, Chunk);
+  auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
+
+  // Start the loop with a block that tests the condition.
+  auto CondBlock = createBasicBlock("omp.dispatch.cond");
+  EmitBlock(CondBlock);
+  LoopStack.push(CondBlock);
+
+  llvm::Value *BoolCondVal = nullptr;
+  // UB = min(UB, GlobalUB)
+  EmitIgnoredExpr(S.getEnsureUpperBound());
+  // IV = LB
+  EmitIgnoredExpr(S.getInit());
+  // IV < UB
+  BoolCondVal = EvaluateExprAsBool(S.getCond(false));
+
+  // If there are any cleanups between here and the loop-exit scope,
+  // create a block to stage a loop exit along.
+  auto ExitBlock = LoopExit.getBlock();
+  if (LoopScope.requiresCleanups())
+    ExitBlock = createBasicBlock("omp.dispatch.cleanup");
+
+  auto LoopBody = createBasicBlock("omp.dispatch.body");
+  Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
+  if (ExitBlock != LoopExit.getBlock()) {
+    EmitBlock(ExitBlock);
+    EmitBranchThroughCleanup(LoopExit);
+  }
+  EmitBlock(LoopBody);
+
+  // Create a block for the increment.
+  auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
+  BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
+
+  EmitOMPInnerLoop(S, LoopScope);
+
+  EmitBlock(Continue.getBlock());
+  BreakContinueStack.pop_back();
+  // Emit "LB = LB + Stride", "UB = UB + Stride".
+  EmitIgnoredExpr(S.getNextLowerBound());
+  EmitIgnoredExpr(S.getNextUpperBound());
+
+  EmitBranch(CondBlock);
+  LoopStack.pop();
+  // Emit the fall-through block.
+  EmitBlock(LoopExit.getBlock());
+
+  // Tell the runtime we are done.
+  RT.emitForFinish(*this, S.getLocStart(), ScheduleKind);
+}
+
+/// \brief Emit a helper variable and return corresponding lvalue.
+static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
+                               const DeclRefExpr *Helper) {
+  auto VDecl = cast<VarDecl>(Helper->getDecl());
+  CGF.EmitVarDecl(*VDecl);
+  return CGF.EmitLValue(Helper);
+}
+
+void CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
+  // Emit the loop iteration variable.
+  auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
+  auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
+  EmitVarDecl(*IVDecl);
+
+  // Emit the iterations count variable.
+  // If it is not a variable, Sema decided to calculate iterations count on each
+  // iteration (e.g., it is foldable into a constant).
+  if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
+    EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
+    // Emit calculation of the iterations count.
+    EmitIgnoredExpr(S.getCalcLastIteration());
+  }
+
+  auto &RT = CGM.getOpenMPRuntime();
+
+  // Check pre-condition.
+  {
+    // Skip the entire loop if we don't meet the precondition.
+    RegionCounter Cnt = getPGORegionCounter(&S);
+    auto ThenBlock = createBasicBlock("omp.precond.then");
+    auto ContBlock = createBasicBlock("omp.precond.end");
+    EmitBranchOnBoolExpr(S.getPreCond(), ThenBlock, ContBlock, Cnt.getCount());
+    EmitBlock(ThenBlock);
+    Cnt.beginRegion(Builder);
+    // Emit 'then' code.
+    {
+      // Emit helper vars inits.
+      LValue LB =
+          EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
+      LValue UB =
+          EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
+      LValue ST =
+          EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
+      LValue IL =
+          EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
+
+      OMPPrivateScope LoopScope(*this);
+      EmitPrivateLoopCounters(*this, LoopScope, S.counters());
+
+      // Detect the loop schedule kind and chunk.
+      auto ScheduleKind = OMPC_SCHEDULE_unknown;
+      llvm::Value *Chunk = nullptr;
+      if (auto C = cast_or_null<OMPScheduleClause>(
+              S.getSingleClause(OMPC_schedule))) {
+        ScheduleKind = C->getScheduleKind();
+        if (auto Ch = C->getChunkSize()) {
+          Chunk = EmitScalarExpr(Ch);
+          Chunk = EmitScalarConversion(Chunk, Ch->getType(),
+                                       S.getIterationVariable()->getType());
+        }
+      }
+      const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
+      const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
+      if (RT.isStaticNonchunked(ScheduleKind,
+                                /* Chunked */ Chunk != nullptr)) {
+        // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
+        // When no chunk_size is specified, the iteration space is divided into
+        // chunks that are approximately equal in size, and at most one chunk is
+        // distributed to each thread. Note that the size of the chunks is
+        // unspecified in this case.
+        RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
+                       IL.getAddress(), LB.getAddress(), UB.getAddress(),
+                       ST.getAddress());
+        // UB = min(UB, GlobalUB);
+        EmitIgnoredExpr(S.getEnsureUpperBound());
+        // IV = LB;
+        EmitIgnoredExpr(S.getInit());
+        // while (idx <= UB) { BODY; ++idx; }
+        EmitOMPInnerLoop(S, LoopScope);
+        // Tell the runtime we are done.
+        RT.emitForFinish(*this, S.getLocStart(), ScheduleKind);
+      } else {
+        // Emit the outer loop, which requests its work chunk [LB..UB] from
+        // runtime and runs the inner loop to process it.
+        EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
+                            UB.getAddress(), ST.getAddress(), IL.getAddress(),
+                            Chunk);
+      }
+    }
+    // We're now done with the loop, so jump to the continuation block.
+    EmitBranch(ContBlock);
+    EmitBlock(ContBlock, true);
+  }
+}
+
+void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
+  InlinedOpenMPRegionRAII Region(*this, S);
+  RunCleanupsScope DirectiveScope(*this);
+
+  CGDebugInfo *DI = getDebugInfo();
+  if (DI)
+    DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
+
+  EmitOMPWorksharingLoop(S);
+
+  // Emit an implicit barrier at the end.
+  CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
+                                         /*IsExplicit*/ false);
+  if (DI)
+    DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
 }
 
 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
@@ -486,30 +678,32 @@
   llvm_unreachable("CodeGen for 'omp section' is not supported yet.");
 }
 
-void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &) {
-  llvm_unreachable("CodeGen for 'omp single' is not supported yet.");
-}
-
-void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &) {
-  llvm_unreachable("CodeGen for 'omp master' is not supported yet.");
-}
-
-void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
-  // __kmpc_critical();
-  // <captured_body>
-  // __kmpc_end_critical();
-  //
-
-  auto Lock = CGM.getOpenMPRuntime().GetCriticalRegionLock(
-      S.getDirectiveName().getAsString());
-  CGM.getOpenMPRuntime().EmitOMPCriticalRegionStart(*this, Lock,
-                                                    S.getLocStart());
-  {
+void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
+  CGM.getOpenMPRuntime().emitSingleRegion(*this, [&]() -> void {
+    InlinedOpenMPRegionRAII Region(*this, S);
     RunCleanupsScope Scope(*this);
     EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
     EnsureInsertPoint();
-  }
-  CGM.getOpenMPRuntime().EmitOMPCriticalRegionEnd(*this, Lock, S.getLocEnd());
+  }, S.getLocStart());
+}
+
+void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
+  CGM.getOpenMPRuntime().emitMasterRegion(*this, [&]() -> void {
+    InlinedOpenMPRegionRAII Region(*this, S);
+    RunCleanupsScope Scope(*this);
+    EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
+    EnsureInsertPoint();
+  }, S.getLocStart());
+}
+
+void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
+  CGM.getOpenMPRuntime().emitCriticalRegion(
+      *this, S.getDirectiveName().getAsString(), [&]() -> void {
+        InlinedOpenMPRegionRAII Region(*this, S);
+        RunCleanupsScope Scope(*this);
+        EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
+        EnsureInsertPoint();
+      }, S.getLocStart());
 }
 
 void
@@ -531,12 +725,13 @@
   llvm_unreachable("CodeGen for 'omp task' is not supported yet.");
 }
 
-void CodeGenFunction::EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &) {
-  llvm_unreachable("CodeGen for 'omp taskyield' is not supported yet.");
+void CodeGenFunction::EmitOMPTaskyieldDirective(
+    const OMPTaskyieldDirective &S) {
+  CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
 }
 
-void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &) {
-  llvm_unreachable("CodeGen for 'omp barrier' is not supported yet.");
+void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
+  CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart());
 }
 
 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &) {
@@ -544,24 +739,142 @@
 }
 
 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
-  CGM.getOpenMPRuntime().EmitOMPFlush(
-      *this, [&]() -> ArrayRef<const Expr *> {
-               if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
-                 auto FlushClause = cast<OMPFlushClause>(C);
-                 return llvm::makeArrayRef(FlushClause->varlist_begin(),
-                                           FlushClause->varlist_end());
-               }
-               return llvm::None;
-             }(),
-      S.getLocStart());
+  CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
+    if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
+      auto FlushClause = cast<OMPFlushClause>(C);
+      return llvm::makeArrayRef(FlushClause->varlist_begin(),
+                                FlushClause->varlist_end());
+    }
+    return llvm::None;
+  }(), S.getLocStart());
 }
 
 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &) {
   llvm_unreachable("CodeGen for 'omp ordered' is not supported yet.");
 }
 
-void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &) {
-  llvm_unreachable("CodeGen for 'omp atomic' is not supported yet.");
+static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
+                                         QualType SrcType, QualType DestType) {
+  assert(CGF.hasScalarEvaluationKind(DestType) &&
+         "DestType must have scalar evaluation kind.");
+  assert(!Val.isAggregate() && "Must be a scalar or complex.");
+  return Val.isScalar()
+             ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
+             : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
+                                                 DestType);
+}
+
+static CodeGenFunction::ComplexPairTy
+convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
+                      QualType DestType) {
+  assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
+         "DestType must have complex evaluation kind.");
+  CodeGenFunction::ComplexPairTy ComplexVal;
+  if (Val.isScalar()) {
+    // Convert the input element to the element type of the complex.
+    auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
+    auto ScalarVal =
+        CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
+    ComplexVal = CodeGenFunction::ComplexPairTy(
+        ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
+  } else {
+    assert(Val.isComplex() && "Must be a scalar or complex.");
+    auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
+    auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
+    ComplexVal.first = CGF.EmitScalarConversion(
+        Val.getComplexVal().first, SrcElementType, DestElementType);
+    ComplexVal.second = CGF.EmitScalarConversion(
+        Val.getComplexVal().second, SrcElementType, DestElementType);
+  }
+  return ComplexVal;
+}
+
+static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
+                                  const Expr *X, const Expr *V,
+                                  SourceLocation Loc) {
+  // v = x;
+  assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
+  assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
+  LValue XLValue = CGF.EmitLValue(X);
+  LValue VLValue = CGF.EmitLValue(V);
+  RValue Res = XLValue.isGlobalReg()
+                   ? CGF.EmitLoadOfLValue(XLValue, Loc)
+                   : CGF.EmitAtomicLoad(XLValue, Loc,
+                                        IsSeqCst ? llvm::SequentiallyConsistent
+                                                 : llvm::Monotonic);
+  // OpenMP, 2.12.6, atomic Construct
+  // Any atomic construct with a seq_cst clause forces the atomically
+  // performed operation to include an implicit flush operation without a
+  // list.
+  if (IsSeqCst)
+    CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
+  switch (CGF.getEvaluationKind(V->getType())) {
+  case TEK_Scalar:
+    CGF.EmitStoreOfScalar(
+        convertToScalarValue(CGF, Res, X->getType(), V->getType()), VLValue);
+    break;
+  case TEK_Complex:
+    CGF.EmitStoreOfComplex(
+        convertToComplexValue(CGF, Res, X->getType(), V->getType()), VLValue,
+        /*isInit=*/false);
+    break;
+  case TEK_Aggregate:
+    llvm_unreachable("Must be a scalar or complex.");
+  }
+}
+
+static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
+                              bool IsSeqCst, const Expr *X, const Expr *V,
+                              const Expr *, SourceLocation Loc) {
+  switch (Kind) {
+  case OMPC_read:
+    EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
+    break;
+  case OMPC_write:
+  case OMPC_update:
+  case OMPC_capture:
+    llvm_unreachable("CodeGen for 'omp atomic clause' is not supported yet.");
+  case OMPC_if:
+  case OMPC_final:
+  case OMPC_num_threads:
+  case OMPC_private:
+  case OMPC_firstprivate:
+  case OMPC_lastprivate:
+  case OMPC_reduction:
+  case OMPC_safelen:
+  case OMPC_collapse:
+  case OMPC_default:
+  case OMPC_seq_cst:
+  case OMPC_shared:
+  case OMPC_linear:
+  case OMPC_aligned:
+  case OMPC_copyin:
+  case OMPC_copyprivate:
+  case OMPC_flush:
+  case OMPC_proc_bind:
+  case OMPC_schedule:
+  case OMPC_ordered:
+  case OMPC_nowait:
+  case OMPC_untied:
+  case OMPC_threadprivate:
+  case OMPC_mergeable:
+  case OMPC_unknown:
+    llvm_unreachable("Clause is not allowed in 'omp atomic'.");
+  }
+}
+
+void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
+  bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
+  OpenMPClauseKind Kind = OMPC_unknown;
+  for (auto *C : S.clauses()) {
+    // Find first clause (skip seq_cst clause, if it is first).
+    if (C->getClauseKind() != OMPC_seq_cst) {
+      Kind = C->getClauseKind();
+      break;
+    }
+  }
+  EmitOMPAtomicExpr(*this, Kind, IsSeqCst, S.getX(), S.getV(), S.getExpr(),
+                    S.getLocStart());
 }
 
 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
diff --git a/lib/CodeGen/CGVTT.cpp b/lib/CodeGen/CGVTT.cpp
index bd280ea..81bd651 100644
--- a/lib/CodeGen/CGVTT.cpp
+++ b/lib/CodeGen/CGVTT.cpp
@@ -94,6 +94,9 @@
   // Set the correct linkage.
   VTT->setLinkage(Linkage);
 
+  if (CGM.supportsCOMDAT() && VTT->isWeakForLinker())
+    VTT->setComdat(CGM.getModule().getOrInsertComdat(VTT->getName()));
+
   // Set the right visibility.
   CGM.setGlobalVisibility(VTT, RD);
 }
diff --git a/lib/CodeGen/CGVTables.cpp b/lib/CodeGen/CGVTables.cpp
index 48a93ba..2e8471e 100644
--- a/lib/CodeGen/CGVTables.cpp
+++ b/lib/CodeGen/CGVTables.cpp
@@ -159,14 +159,10 @@
   // with "this".
   llvm::Value *ThisPtr = &*AI;
   llvm::BasicBlock *EntryBB = Fn->begin();
-  llvm::Instruction *ThisStore = nullptr;
-  for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
-       I != E; I++) {
-    if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
-      ThisStore = cast<llvm::StoreInst>(I);
-      break;
-    }
-  }
+  llvm::Instruction *ThisStore =
+      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);
@@ -218,7 +214,7 @@
 
   // Start defining the function.
   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
-                MD->getLocation(), SourceLocation());
+                MD->getLocation(), MD->getLocation());
 
   // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
@@ -381,7 +377,10 @@
 
   // Set the right linkage.
   CGM.setFunctionLinkage(GD, Fn);
-  
+
+  if (CGM.supportsCOMDAT() && Fn->isWeakForLinker())
+    Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
+
   // Set the right visibility.
   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
   setThunkVisibility(CGM, MD, Thunk, Fn);
@@ -670,6 +669,8 @@
       VTLayout->getNumVTableThunks(), RTTI);
   VTable->setInitializer(Init);
   
+  CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
+
   return VTable;
 }
 
@@ -751,19 +752,13 @@
   llvm_unreachable("Invalid TemplateSpecializationKind!");
 }
 
-/// This is a callback from Sema to tell us that it believes that a
-/// particular v-table is required to be emitted in this translation
-/// unit.
+/// This is a callback from Sema to tell us that that a particular v-table is
+/// required to be emitted in this translation unit.
 ///
-/// The reason we don't simply trust this callback is because Sema
-/// will happily report that something is used even when it's used
-/// only in code that we don't actually have to emit.
-///
-/// \param isRequired - if true, the v-table is mandatory, e.g.
-///   because the translation unit defines the key function
-void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
-  if (!isRequired) return;
-
+/// This is only called for vtables that _must_ be emitted (mainly due to key
+/// functions).  For weak vtables, CodeGen tracks when they are needed and
+/// emits them as-needed.
+void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
   VTables.GenerateClassData(theClass);
 }
 
@@ -844,3 +839,65 @@
          "deferred extra v-tables during v-table emission?");
   DeferredVTables.clear();
 }
+
+void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
+                                            const VTableLayout &VTLayout) {
+  if (!LangOpts.Sanitize.has(SanitizerKind::CFIVptr))
+    return;
+
+  llvm::Metadata *VTableMD = llvm::ConstantAsMetadata::get(VTable);
+
+  std::vector<llvm::MDTuple *> BitsetEntries;
+  // Create a bit set entry for each address point.
+  for (auto &&AP : VTLayout.getAddressPoints()) {
+    // FIXME: Add blacklisting scheme.
+    if (AP.first.getBase()->isInStdNamespace())
+      continue;
+
+    std::string OutName;
+    llvm::raw_string_ostream Out(OutName);
+    getCXXABI().getMangleContext().mangleCXXVTableBitSet(AP.first.getBase(),
+                                                         Out);
+
+    CharUnits PointerWidth =
+        Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
+    uint64_t AddrPointOffset = AP.second * PointerWidth.getQuantity();
+
+    llvm::Metadata *BitsetOps[] = {
+        llvm::MDString::get(getLLVMContext(), Out.str()),
+        VTableMD,
+        llvm::ConstantAsMetadata::get(
+            llvm::ConstantInt::get(Int64Ty, AddrPointOffset))};
+    llvm::MDTuple *BitsetEntry =
+        llvm::MDTuple::get(getLLVMContext(), BitsetOps);
+    BitsetEntries.push_back(BitsetEntry);
+  }
+
+  // Sort the bit set entries for determinism.
+  std::sort(BitsetEntries.begin(), BitsetEntries.end(), [](llvm::MDTuple *T1,
+                                                           llvm::MDTuple *T2) {
+    if (T1 == T2)
+      return false;
+
+    StringRef S1 = cast<llvm::MDString>(T1->getOperand(0))->getString();
+    StringRef S2 = cast<llvm::MDString>(T2->getOperand(0))->getString();
+    if (S1 < S2)
+      return true;
+    if (S1 != S2)
+      return false;
+
+    uint64_t Offset1 = cast<llvm::ConstantInt>(
+                           cast<llvm::ConstantAsMetadata>(T1->getOperand(2))
+                               ->getValue())->getZExtValue();
+    uint64_t Offset2 = cast<llvm::ConstantInt>(
+                           cast<llvm::ConstantAsMetadata>(T2->getOperand(2))
+                               ->getValue())->getZExtValue();
+    assert(Offset1 != Offset2);
+    return Offset1 < Offset2;
+  });
+
+  llvm::NamedMDNode *BitsetsMD =
+      getModule().getOrInsertNamedMetadata("llvm.bitsets");
+  for (auto BitsetEntry : BitsetEntries)
+    BitsetsMD->addOperand(BitsetEntry);
+}
diff --git a/lib/CodeGen/CMakeLists.txt b/lib/CodeGen/CMakeLists.txt
index 10c2409..18f505d 100644
--- a/lib/CodeGen/CMakeLists.txt
+++ b/lib/CodeGen/CMakeLists.txt
@@ -1,4 +1,5 @@
 set(LLVM_LINK_COMPONENTS
+  Analysis
   BitReader
   BitWriter
   Core
@@ -12,7 +13,6 @@
   ProfileData
   ScalarOpts
   Support
-  Target
   TransformUtils
   )
 
diff --git a/lib/CodeGen/CodeGenABITypes.cpp b/lib/CodeGen/CodeGenABITypes.cpp
index f455e70..12189ae 100644
--- a/lib/CodeGen/CodeGenABITypes.cpp
+++ b/lib/CodeGen/CodeGenABITypes.cpp
@@ -67,5 +67,6 @@
                                          FunctionType::ExtInfo info,
                                          RequiredArgs args) {
   return CGM->getTypes().arrangeLLVMFunctionInfo(
-      returnType, /*IsInstanceMethod=*/false, argTypes, info, args);
+      returnType, /*IsInstanceMethod=*/false, /*IsChainCall=*/false, argTypes,
+      info, args);
 }
diff --git a/lib/CodeGen/CodeGenAction.cpp b/lib/CodeGen/CodeGenAction.cpp
index 1eb59bd..b5ed12a 100644
--- a/lib/CodeGen/CodeGenAction.cpp
+++ b/lib/CodeGen/CodeGenAction.cpp
@@ -8,19 +8,19 @@
 //===----------------------------------------------------------------------===//
 
 #include "CoverageMappingGen.h"
-#include "clang/CodeGen/CodeGenAction.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/DeclGroup.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclGroup.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
-#include "clang/Lex/Preprocessor.h"
 #include "clang/CodeGen/BackendUtil.h"
+#include "clang/CodeGen/CodeGenAction.h"
 #include "clang/CodeGen/ModuleBuilder.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/IR/DebugInfo.h"
@@ -65,9 +65,8 @@
                     CoverageSourceInfo *CoverageInfo = nullptr)
         : Diags(_Diags), Action(action), CodeGenOpts(compopts),
           TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
-          Context(), LLVMIRGeneration("LLVM IR Generation Time"),
-          Gen(CreateLLVMCodeGen(Diags, infile, compopts,
-                                targetopts, C, CoverageInfo)),
+          Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
+          Gen(CreateLLVMCodeGen(Diags, infile, compopts, C, CoverageInfo)),
           LinkModule(LinkModule) {
       llvm::TimePassesIsEnabled = TimePasses;
     }
@@ -196,8 +195,8 @@
       Gen->CompleteTentativeDefinition(D);
     }
 
-    void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
-      Gen->HandleVTable(RD, DefinitionRequired);
+    void HandleVTable(CXXRecordDecl *RD) override {
+      Gen->HandleVTable(RD);
     }
 
     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
@@ -668,6 +667,12 @@
   return std::move(Result);
 }
 
+static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
+                                         void *Context,
+                                         unsigned LocCookie) {
+  SM.print(nullptr, llvm::errs());
+}
+
 void CodeGenAction::ExecuteAction() {
   // If this is an IR file, we have to treat it specially.
   if (getCurrentFileKind() == IK_LLVM_IR) {
@@ -710,14 +715,14 @@
     }
     const TargetOptions &TargetOpts = CI.getTargetOpts();
     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
-      unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
-          DiagnosticsEngine::Warning,
-          "overriding the module target triple with %0");
-
-      CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
+      CI.getDiagnostics().Report(SourceLocation(),
+                                 diag::warn_fe_override_module)
+          << TargetOpts.Triple;
       TheModule->setTargetTriple(TargetOpts.Triple);
     }
 
+    LLVMContext &Ctx = TheModule->getContext();
+    Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
                       CI.getLangOpts(), CI.getTarget().getTargetDescription(),
                       TheModule.get(), BA, OS);
diff --git a/lib/CodeGen/CodeGenFunction.cpp b/lib/CodeGen/CodeGenFunction.cpp
index 05c98fc..7d510d6 100644
--- a/lib/CodeGen/CodeGenFunction.cpp
+++ b/lib/CodeGen/CodeGenFunction.cpp
@@ -44,6 +44,7 @@
       LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
       NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
       ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
+      AbnormalTerminationSlot(nullptr), SEHPointersDecl(nullptr),
       DebugInfo(CGM.getModuleDebugInfo()), DisableDebugInfo(false),
       DidCallStackSave(false), IndirectBranch(nullptr), PGO(cgm),
       SwitchInsn(nullptr), SwitchWeights(nullptr), CaseRangeBlock(nullptr),
@@ -63,6 +64,12 @@
     FMF.setNoNaNs();
     FMF.setNoInfs();
   }
+  if (CGM.getCodeGenOpts().NoNaNsFPMath) {
+    FMF.setNoNaNs();
+  }
+  if (CGM.getCodeGenOpts().NoSignedZeros) {
+    FMF.setNoSignedZeros();
+  }
   Builder.SetFastMathFlags(FMF);
 }
 
@@ -76,7 +83,7 @@
     destroyBlockInfos(FirstBlockInfo);
 
   if (getLangOpts().OpenMP) {
-    CGM.getOpenMPRuntime().FunctionFinished(*this);
+    CGM.getOpenMPRuntime().functionFinished(*this);
   }
 }
 
@@ -152,7 +159,7 @@
   }
 }
 
-void CodeGenFunction::EmitReturnBlock() {
+llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
   // For cleanliness, we try to avoid emitting the return block for
   // simple cases.
   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
@@ -167,7 +174,7 @@
       delete ReturnBlock.getBlock();
     } else
       EmitBlock(ReturnBlock.getBlock());
-    return;
+    return llvm::DebugLoc();
   }
 
   // Otherwise, if the return block is the target of a single direct
@@ -178,15 +185,13 @@
       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
     if (BI && BI->isUnconditional() &&
         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
-      // Reset insertion point, including debug location, and delete the
-      // branch.  This is really subtle and only works because the next change
-      // in location will hit the caching in CGDebugInfo::EmitLocation and not
-      // override this.
-      Builder.SetCurrentDebugLocation(BI->getDebugLoc());
+      // Record/return the DebugLoc of the simple 'return' expression to be used
+      // later by the actual 'ret' instruction.
+      llvm::DebugLoc Loc = BI->getDebugLoc();
       Builder.SetInsertPoint(BI->getParent());
       BI->eraseFromParent();
       delete ReturnBlock.getBlock();
-      return;
+      return Loc;
     }
   }
 
@@ -195,6 +200,7 @@
   // region.end for now.
 
   EmitBlock(ReturnBlock.getBlock());
+  return llvm::DebugLoc();
 }
 
 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
@@ -236,8 +242,6 @@
   // edges will be *really* confused.
   bool EmitRetDbgLoc = true;
   if (EHStack.stable_begin() != PrologueCleanupDepth) {
-    PopCleanupBlocks(PrologueCleanupDepth);
-
     // Make sure the line table doesn't jump back into the body for
     // the ret after it's been at EndLoc.
     EmitRetDbgLoc = false;
@@ -245,19 +249,23 @@
     if (CGDebugInfo *DI = getDebugInfo())
       if (OnlySimpleReturnStmts)
         DI->EmitLocation(Builder, EndLoc);
+
+    PopCleanupBlocks(PrologueCleanupDepth);
   }
 
   // Emit function epilog (to return).
-  EmitReturnBlock();
+  llvm::DebugLoc Loc = EmitReturnBlock();
 
   if (ShouldInstrumentFunction())
     EmitFunctionInstrumentation("__cyg_profile_func_exit");
 
   // Emit debug descriptor for function end.
-  if (CGDebugInfo *DI = getDebugInfo()) {
+  if (CGDebugInfo *DI = getDebugInfo())
     DI->EmitFunctionEnd(Builder);
-  }
 
+  // Reset the debug location to that of the simple 'return' expression, if any
+  // rather than that of the end of the function's scope '}'.
+  ApplyDebugLocation AL(*this, Loc);
   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
   EmitEndEHSpec(CurCodeDecl);
 
@@ -349,9 +357,9 @@
 // information in the program executable. The argument information stored
 // includes the argument name, its type, the address and access qualifiers used.
 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
-                                 CodeGenModule &CGM,llvm::LLVMContext &Context,
-                                 SmallVector <llvm::Value*, 5> &kernelMDArgs,
-                                 CGBuilderTy& Builder, ASTContext &ASTCtx) {
+                                 CodeGenModule &CGM, llvm::LLVMContext &Context,
+                                 SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
+                                 CGBuilderTy &Builder, ASTContext &ASTCtx) {
   // Create MDNodes that represent the kernel arg metadata.
   // Each MDNode is a list in the form of "key", N number of values which is
   // the same number of values as their are kernel arguments.
@@ -359,28 +367,28 @@
   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
 
   // MDNode for the kernel argument address space qualifiers.
-  SmallVector<llvm::Value*, 8> addressQuals;
+  SmallVector<llvm::Metadata *, 8> addressQuals;
   addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
 
   // MDNode for the kernel argument access qualifiers (images only).
-  SmallVector<llvm::Value*, 8> accessQuals;
+  SmallVector<llvm::Metadata *, 8> accessQuals;
   accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
 
   // MDNode for the kernel argument type names.
-  SmallVector<llvm::Value*, 8> argTypeNames;
+  SmallVector<llvm::Metadata *, 8> argTypeNames;
   argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
 
   // MDNode for the kernel argument base type names.
-  SmallVector<llvm::Value*, 8> argBaseTypeNames;
+  SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
   argBaseTypeNames.push_back(
       llvm::MDString::get(Context, "kernel_arg_base_type"));
 
   // MDNode for the kernel argument type qualifiers.
-  SmallVector<llvm::Value*, 8> argTypeQuals;
+  SmallVector<llvm::Metadata *, 8> argTypeQuals;
   argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
 
   // MDNode for the kernel argument names.
-  SmallVector<llvm::Value*, 8> argNames;
+  SmallVector<llvm::Metadata *, 8> argNames;
   argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
 
   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
@@ -392,8 +400,8 @@
       QualType pointeeTy = ty->getPointeeType();
 
       // Get address qualifier.
-      addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
-        pointeeTy.getAddressSpace())));
+      addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
+          ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
 
       // Get argument type name.
       std::string typeName =
@@ -432,7 +440,8 @@
         AddrSpc =
           CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
 
-      addressQuals.push_back(Builder.getInt32(AddrSpc));
+      addressQuals.push_back(
+          llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
 
       // Get argument type name.
       std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
@@ -483,7 +492,8 @@
   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
   kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
-  kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
+  if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
+    kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
 }
 
 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
@@ -494,12 +504,11 @@
 
   llvm::LLVMContext &Context = getLLVMContext();
 
-  SmallVector <llvm::Value*, 5> kernelMDArgs;
-  kernelMDArgs.push_back(Fn);
+  SmallVector<llvm::Metadata *, 5> kernelMDArgs;
+  kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
 
-  if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
-    GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
-                         Builder, getContext());
+  GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
+                       getContext());
 
   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
     QualType hintQTy = A->getTypeHint();
@@ -507,33 +516,31 @@
     bool isSignedInteger =
         hintQTy->isSignedIntegerType() ||
         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
-    llvm::Value *attrMDArgs[] = {
-      llvm::MDString::get(Context, "vec_type_hint"),
-      llvm::UndefValue::get(CGM.getTypes().ConvertType(A->getTypeHint())),
-      llvm::ConstantInt::get(
-          llvm::IntegerType::get(Context, 32),
-          llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
-    };
+    llvm::Metadata *attrMDArgs[] = {
+        llvm::MDString::get(Context, "vec_type_hint"),
+        llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
+            CGM.getTypes().ConvertType(A->getTypeHint()))),
+        llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+            llvm::IntegerType::get(Context, 32),
+            llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
   }
 
   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
-    llvm::Value *attrMDArgs[] = {
-      llvm::MDString::get(Context, "work_group_size_hint"),
-      Builder.getInt32(A->getXDim()),
-      Builder.getInt32(A->getYDim()),
-      Builder.getInt32(A->getZDim())
-    };
+    llvm::Metadata *attrMDArgs[] = {
+        llvm::MDString::get(Context, "work_group_size_hint"),
+        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
+        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
+        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
   }
 
   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
-    llvm::Value *attrMDArgs[] = {
-      llvm::MDString::get(Context, "reqd_work_group_size"),
-      Builder.getInt32(A->getXDim()),
-      Builder.getInt32(A->getYDim()),
-      Builder.getInt32(A->getZDim())
-    };
+    llvm::Metadata *attrMDArgs[] = {
+        llvm::MDString::get(Context, "reqd_work_group_size"),
+        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
+        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
+        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
   }
 
@@ -603,17 +610,17 @@
   }
 
   // If we are checking function types, emit a function type signature as
-  // prefix data.
+  // prologue data.
   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
-      if (llvm::Constant *PrefixSig =
+      if (llvm::Constant *PrologueSig =
               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
         llvm::Constant *FTRTTIConst =
             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
-        llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
-        llvm::Constant *PrefixStructConst =
-            llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
-        Fn->setPrefixData(PrefixStructConst);
+        llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
+        llvm::Constant *PrologueStructConst =
+            llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
+        Fn->setPrologueData(PrologueStructConst);
       }
     }
   }
@@ -799,6 +806,9 @@
                                           const FunctionDecl *UnsizedDealloc) {
   // This is a weak discardable definition of the sized deallocation function.
   CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
+  if (CGF.CGM.supportsCOMDAT())
+    CGF.CurFn->setComdat(
+        CGF.CGM.getModule().getOrInsertComdat(CGF.CurFn->getName()));
 
   // Call the unsized deallocation function and forward the first argument
   // unchanged.
@@ -884,8 +894,11 @@
   } else if (FunctionDecl *UnsizedDealloc =
                  FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
     // Global sized deallocation functions get an implicit weak definition if
-    // they don't have an explicit definition.
+    // they don't have an explicit definition, if allowed.
+    assert(getLangOpts().DefineSizedDeallocation &&
+           "Can't emit unallowed definition.");
     EmitSizedDeallocationFunction(*this, UnsizedDealloc);
+
   } else
     llvm_unreachable("no definition for emitted function");
 
@@ -916,9 +929,6 @@
   // a quick pass now to see if we can.
   if (!CurFn->doesNotThrow())
     TryMarkNoThrow(CurFn);
-
-  PGO.emitInstrumentationData();
-  PGO.destroyRegionCounters();
 }
 
 /// ContainsLabel - Return true if the statement contains a label in it.  If
@@ -1055,8 +1065,11 @@
       uint64_t RHSCount = Cnt.getCount();
 
       ConditionalEvaluation eval(*this);
-      EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
-      EmitBlock(LHSTrue);
+      {
+        ApplyDebugLocation DL(*this, Cond);
+        EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
+        EmitBlock(LHSTrue);
+      }
 
       // Any temporaries created here are conditional.
       Cnt.beginRegion(Builder);
@@ -1100,8 +1113,11 @@
       uint64_t RHSCount = TrueCount - LHSCount;
 
       ConditionalEvaluation eval(*this);
-      EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
-      EmitBlock(LHSFalse);
+      {
+        ApplyDebugLocation DL(*this, Cond);
+        EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
+        EmitBlock(LHSFalse);
+      }
 
       // Any temporaries created here are conditional.
       Cnt.beginRegion(Builder);
@@ -1148,8 +1164,11 @@
     cond.begin(*this);
     EmitBlock(LHSBlock);
     Cnt.beginRegion(Builder);
-    EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
-                         LHSScaledTrueCount);
+    {
+      ApplyDebugLocation DL(*this, Cond);
+      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
+                           LHSScaledTrueCount);
+    }
     cond.end(*this);
 
     cond.begin(*this);
@@ -1178,7 +1197,11 @@
                                                   CurrentCount - TrueCount);
 
   // Emit the code with the fully general case.
-  llvm::Value *CondV = EvaluateExprAsBool(Cond);
+  llvm::Value *CondV;
+  {
+    ApplyDebugLocation DL(*this, Cond);
+    CondV = EvaluateExprAsBool(Cond);
+  }
   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
 }
 
diff --git a/lib/CodeGen/CodeGenFunction.h b/lib/CodeGen/CodeGenFunction.h
index 4575e31..c0368aa 100644
--- a/lib/CodeGen/CodeGenFunction.h
+++ b/lib/CodeGen/CodeGenFunction.h
@@ -27,6 +27,7 @@
 #include "clang/AST/Type.h"
 #include "clang/Basic/ABI.h"
 #include "clang/Basic/CapturedStmt.h"
+#include "clang/Basic/OpenMPKinds.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Frontend/CodeGenOptions.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -93,24 +94,11 @@
   TEK_Aggregate
 };
 
-class SuppressDebugLocation {
-  llvm::DebugLoc CurLoc;
-  llvm::IRBuilderBase &Builder;
-public:
-  SuppressDebugLocation(llvm::IRBuilderBase &Builder)
-      : CurLoc(Builder.getCurrentDebugLocation()), Builder(Builder) {
-    Builder.SetCurrentDebugLocation(llvm::DebugLoc());
-  }
-  ~SuppressDebugLocation() {
-    Builder.SetCurrentDebugLocation(CurLoc);
-  }
-};
-
 /// CodeGenFunction - This class organizes the per-function state that is used
 /// while generating LLVM code.
 class CodeGenFunction : public CodeGenTypeCache {
-  CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
-  void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
+  CodeGenFunction(const CodeGenFunction &) = delete;
+  void operator=(const CodeGenFunction &) = delete;
 
   friend class CGCXXABI;
 public:
@@ -182,6 +170,8 @@
   /// \brief API for captured statement code generation.
   class CGCapturedStmtInfo {
   public:
+    explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
+        : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
     explicit CGCapturedStmtInfo(const CapturedStmt &S,
                                 CapturedRegionKind K = CR_Default)
       : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
@@ -204,22 +194,22 @@
 
     void setContextValue(llvm::Value *V) { ThisValue = V; }
     // \brief Retrieve the value of the context parameter.
-    llvm::Value *getContextValue() const { return ThisValue; }
+    virtual llvm::Value *getContextValue() const { return ThisValue; }
 
     /// \brief Lookup the captured field decl for a variable.
-    const FieldDecl *lookup(const VarDecl *VD) const {
+    virtual const FieldDecl *lookup(const VarDecl *VD) const {
       return CaptureFields.lookup(VD);
     }
 
-    bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != nullptr; }
-    FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
+    bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
+    virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
 
     static bool classof(const CGCapturedStmtInfo *) {
       return true;
     }
 
     /// \brief Emit the captured statement body.
-    virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) {
+    virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
       RegionCounter Cnt = CGF.getPGORegionCounter(S);
       Cnt.beginRegion(CGF.Builder);
       CGF.EmitStmt(S);
@@ -285,6 +275,7 @@
 
   EHScopeStack EHStack;
   llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
+  llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
 
   /// Header for data within LifetimeExtendedCleanupStack.
   struct LifetimeExtendedCleanupHeader {
@@ -316,6 +307,12 @@
   /// write the current selector value into this alloca.
   llvm::AllocaInst *EHSelectorSlot;
 
+  llvm::AllocaInst *AbnormalTerminationSlot;
+
+  /// The implicit parameter to SEH filter functions of type
+  /// 'EXCEPTION_POINTERS*'.
+  ImplicitParamDecl *SEHPointersDecl;
+
   /// Emits a landing pad for the current EH stack.
   llvm::BasicBlock *EmitLandingPad();
 
@@ -354,6 +351,20 @@
     void exit(CodeGenFunction &CGF);
   };
 
+  /// Cleanups can be emitted for two reasons: normal control leaving a region
+  /// exceptional control flow leaving a region.
+  struct SEHFinallyInfo {
+    SEHFinallyInfo()
+        : FinallyBB(nullptr), ContBB(nullptr), ResumeBB(nullptr) {}
+
+    llvm::BasicBlock *FinallyBB;
+    llvm::BasicBlock *ContBB;
+    llvm::BasicBlock *ResumeBB;
+  };
+
+  /// Returns true inside SEH __try blocks.
+  bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
+
   /// pushFullExprCleanup - Push a cleanup to be run at the end of the
   /// current full-expression.  Safe against the possibility that
   /// we're currently inside a conditionally-evaluated expression.
@@ -499,8 +510,8 @@
     bool PerformCleanup;
   private:
 
-    RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
-    void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
+    RunCleanupsScope(const RunCleanupsScope &) = delete;
+    void operator=(const RunCleanupsScope &) = delete;
 
   protected:
     CodeGenFunction& CGF;
@@ -548,8 +559,8 @@
     SmallVector<const LabelDecl*, 4> Labels;
     LexicalScope *ParentScope;
 
-    LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION;
-    void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION;
+    LexicalScope(const LexicalScope &) = delete;
+    void operator=(const LexicalScope &) = delete;
 
   public:
     /// \brief Enter a new cleanup scope.
@@ -573,7 +584,10 @@
 
       // If we should perform a cleanup, force them now.  Note that
       // this ends the cleanup scope before rescoping any labels.
-      if (PerformCleanup) ForceCleanup();
+      if (PerformCleanup) {
+        ApplyDebugLocation DL(CGF, Range.getEnd());
+        ForceCleanup();
+      }
     }
 
     /// \brief Force the emission of cleanups now, instead of waiting
@@ -598,8 +612,8 @@
     VarDeclMapTy SavedPrivates;
 
   private:
-    OMPPrivateScope(const OMPPrivateScope &) LLVM_DELETED_FUNCTION;
-    void operator=(const OMPPrivateScope &) LLVM_DELETED_FUNCTION;
+    OMPPrivateScope(const OMPPrivateScope &) = delete;
+    void operator=(const OMPPrivateScope &) = delete;
 
   public:
     /// \brief Enter a new OpenMP private scope.
@@ -614,7 +628,6 @@
     addPrivate(const VarDecl *LocalVD,
                const std::function<llvm::Value *()> &PrivateGen) {
       assert(PerformCleanup && "adding private to dead scope");
-      assert(LocalVD->isLocalVarDecl() && "privatizing non-local variable");
       if (SavedLocals.count(LocalVD) > 0) return false;
       SavedLocals[LocalVD] = CGF.LocalDeclMap.lookup(LocalVD);
       CGF.LocalDeclMap.erase(LocalVD);
@@ -1089,6 +1102,10 @@
   llvm::Value *getExceptionSlot();
   llvm::Value *getEHSelectorSlot();
 
+  /// Stack slot that contains whether a __finally block is being executed as an
+  /// EH cleanup or as a normal cleanup.
+  llvm::Value *getAbnormalTerminationSlot();
+
   /// Returns the contents of the function's exception object and selector
   /// slots.
   llvm::Value *getExceptionFromSlot();
@@ -1109,6 +1126,11 @@
     return getInvokeDestImpl();
   }
 
+  bool currentFunctionUsesSEHTry() const {
+    const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
+    return FD && FD->usesSEHTry();
+  }
+
   const TargetInfo &getTarget() const { return Target; }
   llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
 
@@ -1178,9 +1200,7 @@
 
   void GenerateObjCMethod(const ObjCMethodDecl *OMD);
 
-  void StartObjCMethod(const ObjCMethodDecl *MD,
-                       const ObjCContainerDecl *CD,
-                       SourceLocation StartLoc);
+  void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
 
   /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
   void GenerateObjCGetter(ObjCImplementationDecl *IMP,
@@ -1272,15 +1292,18 @@
   void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
   void EmitAsanPrologueOrEpilogue(bool Prologue);
 
-  /// EmitReturnBlock - Emit the unified return block, trying to avoid its
-  /// emission when possible.
-  void EmitReturnBlock();
+  /// \brief Emit the unified return block, trying to avoid its emission when
+  /// possible.
+  /// \return The debug location of the user written return statement if the
+  /// return block is is avoided.
+  llvm::DebugLoc EmitReturnBlock();
 
   /// FinishFunction - Complete IR generation of the current function. It is
   /// legal to call this function even if there is no current insertion point.
   void FinishFunction(SourceLocation EndLoc=SourceLocation());
 
-  void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo);
+  void StartThunk(llvm::Function *Fn, GlobalDecl GD,
+                  const CGFunctionInfo &FnInfo);
 
   void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
 
@@ -1323,6 +1346,9 @@
   /// to by This.
   llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
 
+  /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
+  /// If vptr CFI is enabled, emit a check that VTable is valid.
+  void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable);
 
   /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
   /// expr can be devirtualized.
@@ -1543,8 +1569,8 @@
 
   /// EmitExprAsInit - Emits the code necessary to initialize a
   /// location in memory with the given initializer.
-  void EmitExprAsInit(const Expr *init, const ValueDecl *D,
-                      LValue lvalue, bool capturedByInit);
+  void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
+                      bool capturedByInit);
 
   /// hasVolatileMember - returns true if aggregate type has a volatile
   /// member.
@@ -1566,6 +1592,15 @@
                       true);
   }
 
+  void EmitAggregateCopyCtor(llvm::Value *DestPtr, llvm::Value *SrcPtr,
+                           QualType DestTy, QualType SrcTy) {
+    CharUnits DestTypeAlign = getContext().getTypeAlignInChars(DestTy);
+    CharUnits SrcTypeAlign = getContext().getTypeAlignInChars(SrcTy);
+    EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
+                      std::min(DestTypeAlign, SrcTypeAlign),
+                      /*IsAssignment=*/false);
+  }
+
   /// EmitAggregateCopy - Emit an aggregate copy.
   ///
   /// \param isVolatile - True iff either the source or the destination is
@@ -1830,8 +1865,8 @@
   /// This function can be called with a null (unreachable) insert point.
   void EmitVarDecl(const VarDecl &D);
 
-  void EmitScalarInit(const Expr *init, const ValueDecl *D,
-                      LValue lvalue, bool capturedByInit);
+  void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
+                      bool capturedByInit);
   void EmitScalarInit(llvm::Value *init, LValue lvalue);
 
   typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
@@ -2002,6 +2037,17 @@
   void EmitCXXTryStmt(const CXXTryStmt &S);
   void EmitSEHTryStmt(const SEHTryStmt &S);
   void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
+  void EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI);
+  void ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI);
+
+  llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
+                                            const SEHExceptStmt &Except);
+
+  void EmitSEHExceptionCodeSave();
+  llvm::Value *EmitSEHExceptionCode();
+  llvm::Value *EmitSEHExceptionInfo();
+  llvm::Value *EmitSEHAbnormalTermination();
+
   void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
                            ArrayRef<const Attr *> Attrs = None);
 
@@ -2041,12 +2087,22 @@
   void EmitOMPTargetDirective(const OMPTargetDirective &S);
   void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
 
-  /// Helpers for 'omp simd' directive.
+private:
+
+  /// Helpers for the OpenMP loop directives.
   void EmitOMPLoopBody(const OMPLoopDirective &Directive,
                        bool SeparateIter = false);
   void EmitOMPInnerLoop(const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
                         bool SeparateIter = false);
   void EmitOMPSimdFinal(const OMPLoopDirective &S);
+  void EmitOMPWorksharingLoop(const OMPLoopDirective &S);
+  void EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
+                           const OMPLoopDirective &S,
+                           OMPPrivateScope &LoopScope, llvm::Value *LB,
+                           llvm::Value *UB, llvm::Value *ST, llvm::Value *IL,
+                           llvm::Value *Chunk);
+
+public:
 
   //===--------------------------------------------------------------------===//
   //                         LValue Expression Emission
@@ -2094,11 +2150,27 @@
 
   void EmitAtomicInit(Expr *E, LValue lvalue);
 
+  bool LValueIsSuitableForInlineAtomic(LValue Src);
+  bool typeIsSuitableForInlineAtomic(QualType Ty, bool IsVolatile) const;
+
+  RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
+                        AggValueSlot Slot = AggValueSlot::ignored());
+
   RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
+                        llvm::AtomicOrdering AO, bool IsVolatile = false,
                         AggValueSlot slot = AggValueSlot::ignored());
 
   void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
 
+  void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
+                       bool IsVolatile, bool isInit);
+
+  std::pair<RValue, RValue> EmitAtomicCompareExchange(
+      LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
+      llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
+      llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
+      bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
+
   /// EmitToMemory - Change a scalar value from its value
   /// representation to its in-memory representation.
   llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
@@ -2150,7 +2222,7 @@
   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
   /// lvalue, where both are guaranteed to the have the same type, and that type
   /// is 'Ty'.
-  void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false);
+  void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
   void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
 
@@ -2166,8 +2238,8 @@
   /// Emit an l-value for an assignment (simple or compound) of complex type.
   LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
   LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
-  LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E,
-                                              llvm::Value *&Result);
+  LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
+                                             llvm::Value *&Result);
 
   // Note: only available for agg return types
   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
@@ -2211,7 +2283,7 @@
       return ConstantEmission(C, false);
     }
 
-    LLVM_EXPLICIT operator bool() const {
+    explicit operator bool() const {
       return ValueAndIsReference.getOpaqueValue() != nullptr;
     }
 
@@ -2281,7 +2353,8 @@
 
   RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
                   ReturnValueSlot ReturnValue,
-                  const Decl *TargetDecl = nullptr);
+                  const Decl *TargetDecl = nullptr,
+                  llvm::Value *Chain = nullptr);
   RValue EmitCallExpr(const CallExpr *E,
                       ReturnValueSlot ReturnValue = ReturnValueSlot());
 
@@ -2329,12 +2402,16 @@
                              StructorType Type);
   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
                                ReturnValueSlot ReturnValue);
+  RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
+                                               const CXXMethodDecl *MD,
+                                               ReturnValueSlot ReturnValue,
+                                               bool HasQualifier,
+                                               NestedNameSpecifier *Qualifier,
+                                               bool IsArrow, const Expr *Base);
+  // Compute the object pointer.
   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
                                       ReturnValueSlot ReturnValue);
 
-  llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
-                                           const CXXMethodDecl *MD,
-                                           llvm::Value *This);
   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
                                        const CXXMethodDecl *MD,
                                        ReturnValueSlot ReturnValue);
@@ -2344,7 +2421,8 @@
 
 
   RValue EmitBuiltinExpr(const FunctionDecl *FD,
-                         unsigned BuiltinID, const CallExpr *E);
+                         unsigned BuiltinID, const CallExpr *E,
+                         ReturnValueSlot ReturnValue);
 
   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
 
@@ -2711,7 +2789,7 @@
                     CallExpr::const_arg_iterator ArgBeg,
                     CallExpr::const_arg_iterator ArgEnd,
                     const FunctionDecl *CalleeDecl = nullptr,
-                    unsigned ParamsToSkip = 0, bool ForceColumnInfo = false) {
+                    unsigned ParamsToSkip = 0) {
     SmallVector<QualType, 16> ArgTypes;
     CallExpr::const_arg_iterator Arg = ArgBeg;
 
@@ -2723,28 +2801,13 @@
                 E = CallArgTypeInfo->param_type_end();
            I != E; ++I, ++Arg) {
         assert(Arg != ArgEnd && "Running over edge of argument list!");
-#ifndef NDEBUG
-        QualType ArgType = *I;
-        QualType ActualArgType = Arg->getType();
-        if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
-          QualType ActualBaseType =
-              ActualArgType->getAs<PointerType>()->getPointeeType();
-          QualType ArgBaseType =
-              ArgType->getAs<PointerType>()->getPointeeType();
-          if (ArgBaseType->isVariableArrayType()) {
-            if (const VariableArrayType *VAT =
-                    getContext().getAsVariableArrayType(ActualBaseType)) {
-              if (!VAT->getSizeExpr())
-                ActualArgType = ArgType;
-            }
-          }
-        }
-        assert(getContext()
-                       .getCanonicalType(ArgType.getNonReferenceType())
-                       .getTypePtr() ==
-                   getContext().getCanonicalType(ActualArgType).getTypePtr() &&
-               "type mismatch in call argument!");
-#endif
+        assert(
+            ((*I)->isVariablyModifiedType() ||
+             getContext()
+                     .getCanonicalType((*I).getNonReferenceType())
+                     .getTypePtr() ==
+                 getContext().getCanonicalType(Arg->getType()).getTypePtr()) &&
+            "type mismatch in call argument!");
         ArgTypes.push_back(*I);
       }
     }
@@ -2759,15 +2822,14 @@
     for (; Arg != ArgEnd; ++Arg)
       ArgTypes.push_back(getVarArgType(*Arg));
 
-    EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip,
-                 ForceColumnInfo);
+    EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip);
   }
 
   void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
                     CallExpr::const_arg_iterator ArgBeg,
                     CallExpr::const_arg_iterator ArgEnd,
                     const FunctionDecl *CalleeDecl = nullptr,
-                    unsigned ParamsToSkip = 0, bool ForceColumnInfo = false);
+                    unsigned ParamsToSkip = 0);
 
 private:
   QualType getVarArgType(const Expr *Arg);
@@ -2787,6 +2849,8 @@
   /// GetPointeeAlignment - Given an expression with a pointer type, emit the
   /// value and compute our best estimate of the alignment of the pointee.
   std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
+
+  llvm::Value *GetValueForARMHint(unsigned BuiltinID);
 };
 
 /// Helper class with most of the code for saving a value for a
diff --git a/lib/CodeGen/CodeGenModule.cpp b/lib/CodeGen/CodeGenModule.cpp
index b35e81c..1b6439b 100644
--- a/lib/CodeGen/CodeGenModule.cpp
+++ b/lib/CodeGen/CodeGenModule.cpp
@@ -21,8 +21,8 @@
 #include "CGOpenMPRuntime.h"
 #include "CodeGenFunction.h"
 #include "CodeGenPGO.h"
-#include "CoverageMappingGen.h"
 #include "CodeGenTBAA.h"
+#include "CoverageMappingGen.h"
 #include "TargetInfo.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/CharUnits.h"
@@ -64,6 +64,7 @@
   case TargetCXXABI::GenericARM:
   case TargetCXXABI::iOS:
   case TargetCXXABI::iOS64:
+  case TargetCXXABI::GenericMIPS:
   case TargetCXXABI::GenericItanium:
     return CreateItaniumCXXABI(CGM);
   case TargetCXXABI::Microsoft:
@@ -109,6 +110,7 @@
   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
 
   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
+  BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
 
   if (LangOpts.ObjC1)
     createObjCRuntime();
@@ -139,12 +141,14 @@
   RRData = new RREntrypoints();
 
   if (!CodeGenOpts.InstrProfileInput.empty()) {
-    if (std::error_code EC = llvm::IndexedInstrProfReader::create(
-            CodeGenOpts.InstrProfileInput, PGOReader)) {
+    auto ReaderOrErr =
+        llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
+    if (std::error_code EC = ReaderOrErr.getError()) {
       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
                                               "Could not read profile: %0");
       getDiags().Report(DiagID) << EC.message();
     }
+    PGOReader = std::move(ReaderOrErr.get());
   }
 
   // If coverage mapping generation is enabled, create the
@@ -344,9 +348,6 @@
   if (ObjCRuntime)
     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
       AddGlobalCtor(ObjCInitFunction);
-  if (getCodeGenOpts().ProfileInstrGenerate)
-    if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
-      AddGlobalCtor(PGOInit, 0);
   if (PGOReader && PGOStats.hasDiagnostics())
     PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
   EmitCtorList(GlobalCtors, "llvm.global_ctors");
@@ -624,7 +625,7 @@
 
   // Get the type of a ctor entry, { i32, void ()*, i8* }.
   llvm::StructType *CtorStructTy = llvm::StructType::get(
-      Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL);
+      Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
 
   // Construct the constructor and destructor arrays.
   SmallVector<llvm::Constant*, 8> Ctors;
@@ -715,10 +716,6 @@
     // Naked implies noinline: we should not be inlining such functions.
     B.addAttribute(llvm::Attribute::Naked);
     B.addAttribute(llvm::Attribute::NoInline);
-  } else if (D->hasAttr<OptimizeNoneAttr>()) {
-    // OptimizeNone implies noinline; we should not be inlining such functions.
-    B.addAttribute(llvm::Attribute::OptimizeNone);
-    B.addAttribute(llvm::Attribute::NoInline);
   } else if (D->hasAttr<NoDuplicateAttr>()) {
     B.addAttribute(llvm::Attribute::NoDuplicate);
   } else if (D->hasAttr<NoInlineAttr>()) {
@@ -731,19 +728,14 @@
   }
 
   if (D->hasAttr<ColdAttr>()) {
-    B.addAttribute(llvm::Attribute::OptimizeForSize);
+    if (!D->hasAttr<OptimizeNoneAttr>())
+      B.addAttribute(llvm::Attribute::OptimizeForSize);
     B.addAttribute(llvm::Attribute::Cold);
   }
 
   if (D->hasAttr<MinSizeAttr>())
     B.addAttribute(llvm::Attribute::MinSize);
 
-  if (D->hasAttr<OptimizeNoneAttr>()) {
-    // OptimizeNone wins over OptimizeForSize and MinSize.
-    B.removeAttribute(llvm::Attribute::OptimizeForSize);
-    B.removeAttribute(llvm::Attribute::MinSize);
-  }
-
   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
     B.addAttribute(llvm::Attribute::StackProtect);
   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
@@ -772,6 +764,24 @@
                    llvm::AttributeSet::get(
                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
 
+  if (D->hasAttr<OptimizeNoneAttr>()) {
+    // OptimizeNone implies noinline; we should not be inlining such functions.
+    F->addFnAttr(llvm::Attribute::OptimizeNone);
+    F->addFnAttr(llvm::Attribute::NoInline);
+
+    // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
+    assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
+           "OptimizeNone and OptimizeForSize on same function!");
+    assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
+           "OptimizeNone and MinSize on same function!");
+    assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
+           "OptimizeNone and AlwaysInline on same function!");
+
+    // Attribute 'inlinehint' has no effect on 'optnone' functions.
+    // Explicitly remove it from the set of function attributes.
+    F->removeFnAttr(llvm::Attribute::InlineHint);
+  }
+
   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
     F->setUnnamedAddr(true);
   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
@@ -928,8 +938,8 @@
   UsedArray.resize(List.size());
   for (unsigned i = 0, e = List.size(); i != e; ++i) {
     UsedArray[i] =
-     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
-                                    CGM.Int8PtrTy);
+        llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
+            cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
   }
 
   if (UsedArray.empty())
@@ -949,29 +959,28 @@
 }
 
 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
-  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
+  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
 }
 
 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
   llvm::SmallString<32> Opt;
   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
-  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
+  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
 }
 
 void CodeGenModule::AddDependentLib(StringRef Lib) {
   llvm::SmallString<24> Opt;
   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
-  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
+  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
 }
 
 /// \brief Add link options implied by the given module, including modules
 /// it depends on, using a postorder walk.
-static void addLinkOptionsPostorder(CodeGenModule &CGM,
-                                    Module *Mod,
-                                    SmallVectorImpl<llvm::Value *> &Metadata,
+static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
+                                    SmallVectorImpl<llvm::Metadata *> &Metadata,
                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
   // Import this module's parent.
   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
@@ -991,10 +1000,9 @@
     // Link against a framework.  Frameworks are currently Darwin only, so we
     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
     if (Mod->LinkLibraries[I-1].IsFramework) {
-      llvm::Value *Args[2] = {
-        llvm::MDString::get(Context, "-framework"),
-        llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
-      };
+      llvm::Metadata *Args[2] = {
+          llvm::MDString::get(Context, "-framework"),
+          llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
 
       Metadata.push_back(llvm::MDNode::get(Context, Args));
       continue;
@@ -1004,7 +1012,7 @@
     llvm::SmallString<24> Opt;
     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
       Mod->LinkLibraries[I-1].Library, Opt);
-    llvm::Value *OptString = llvm::MDString::get(Context, Opt);
+    auto *OptString = llvm::MDString::get(Context, Opt);
     Metadata.push_back(llvm::MDNode::get(Context, OptString));
   }
 }
@@ -1057,7 +1065,7 @@
   // Add link options for all of the imported modules in reverse topological
   // order.  We don't do anything to try to order import link flags with respect
   // to linker options inserted by things like #pragma comment().
-  SmallVector<llvm::Value *, 16> MetadataArgs;
+  SmallVector<llvm::Metadata *, 16> MetadataArgs;
   Visited.clear();
   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
                                                MEnd = LinkModules.end();
@@ -1079,36 +1087,52 @@
   // previously unused static decl may become used during the generation of code
   // for a static function, iterate until no changes are made.
 
-  while (true) {
-    if (!DeferredVTables.empty()) {
-      EmitDeferredVTables();
+  if (!DeferredVTables.empty()) {
+    EmitDeferredVTables();
 
-      // Emitting a v-table doesn't directly cause more v-tables to
-      // become deferred, although it can cause functions to be
-      // emitted that then need those v-tables.
-      assert(DeferredVTables.empty());
-    }
+    // Emitting a v-table doesn't directly cause more v-tables to
+    // become deferred, although it can cause functions to be
+    // emitted that then need those v-tables.
+    assert(DeferredVTables.empty());
+  }
 
-    // Stop if we're out of both deferred v-tables and deferred declarations.
-    if (DeferredDeclsToEmit.empty()) break;
+  // Stop if we're out of both deferred v-tables and deferred declarations.
+  if (DeferredDeclsToEmit.empty())
+    return;
 
-    DeferredGlobal &G = DeferredDeclsToEmit.back();
+  // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
+  // work, it will not interfere with this.
+  std::vector<DeferredGlobal> CurDeclsToEmit;
+  CurDeclsToEmit.swap(DeferredDeclsToEmit);
+
+  for (DeferredGlobal &G : CurDeclsToEmit) {
     GlobalDecl D = G.GD;
     llvm::GlobalValue *GV = G.GV;
-    DeferredDeclsToEmit.pop_back();
+    G.GV = nullptr;
 
-    assert(GV == GetGlobalValue(getMangledName(D)));
+    assert(!GV || GV == GetGlobalValue(getMangledName(D)));
+    if (!GV)
+      GV = GetGlobalValue(getMangledName(D));
+
     // Check to see if we've already emitted this.  This is necessary
     // for a couple of reasons: first, decls can end up in the
     // deferred-decls queue multiple times, and second, decls can end
     // up with definitions in unusual ways (e.g. by an extern inline
     // function acquiring a strong function redefinition).  Just
     // ignore these cases.
-    if(!GV->isDeclaration())
+    if (GV && !GV->isDeclaration())
       continue;
 
     // Otherwise, emit the definition and move on to the next one.
     EmitGlobalDefinition(D, GV);
+
+    // If we found out that we need to emit more decls, do that recursively.
+    // This has the advantage that the decls are emitted in a DFS and related
+    // ones are close together, which is convenient for testing.
+    if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
+      EmitDeferred();
+      assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
+    }
   }
 }
 
@@ -1229,12 +1253,22 @@
   return false;
 }
 
-bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
+bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
   // Never defer when EmitAllDecls is specified.
   if (LangOpts.EmitAllDecls)
-    return false;
+    return true;
 
-  return !getContext().DeclMustBeEmitted(Global);
+  return getContext().DeclMustBeEmitted(Global);
+}
+
+bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
+  if (const auto *FD = dyn_cast<FunctionDecl>(Global))
+    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
+      // Implicit template instantiations may change linkage if they are later
+      // explicitly instantiated, so they should not be emitted eagerly.
+      return false;
+
+  return true;
 }
 
 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
@@ -1255,6 +1289,8 @@
   auto *GV = new llvm::GlobalVariable(
       getModule(), Init->getType(),
       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
+  if (supportsCOMDAT())
+    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
   return GV;
 }
 
@@ -1343,9 +1379,10 @@
       return;
   }
 
-  // Defer code generation when possible if this is a static definition, inline
-  // function etc.  These we only want to emit if they are used.
-  if (!MayDeferGeneration(Global)) {
+  // Defer code generation to first use when possible, e.g. if this is an inline
+  // function. If the global must always be emitted, do it eagerly if possible
+  // to benefit from cache locality.
+  if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
     // Emit the definition if it can't be deferred.
     EmitGlobalDefinition(GD);
     return;
@@ -1358,13 +1395,16 @@
     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
     CXXGlobalInits.push_back(nullptr);
   }
-  
-  // If the value has already been used, add it directly to the
-  // DeferredDeclsToEmit list.
+
   StringRef MangledName = getMangledName(GD);
-  if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
+  if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
+    // The value has already been used and should therefore be emitted.
     addDeferredDeclToEmit(GV, GD);
-  else {
+  } else if (MustBeEmitted(Global)) {
+    // The value must be emitted, but cannot be emitted eagerly.
+    assert(!MayBeEmittedEagerly(Global));
+    addDeferredDeclToEmit(/*GV=*/nullptr, GD);
+  } else {
     // Otherwise, remember that we saw a deferred decl with this name.  The
     // first use of the mangled name will cause it to move into
     // DeferredDeclsToEmit.
@@ -1578,12 +1618,15 @@
       // don't need it anymore).
       addDeferredDeclToEmit(F, DDI->second);
       DeferredDecls.erase(DDI);
-
+      
       // Otherwise, if this is a sized deallocation function, emit a weak
-      // definition
-      // for it at the end of the translation unit.
-    } else if (D && cast<FunctionDecl>(D)
-                        ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
+      // definition for it at the end of the translation unit (if allowed),
+      // unless the sized deallocation function is aliased.
+    } else if (D &&
+               cast<FunctionDecl>(D)
+                  ->getCorrespondingUnsizedGlobalDeallocationFunction() &&
+               getLangOpts().DefineSizedDeallocation &&
+               !D->hasAttr<AliasAttr>()) {
       addDeferredDeclToEmit(F, GD);
 
       // Otherwise, there are cases we have to worry about where we're
@@ -1651,6 +1694,21 @@
   return C;
 }
 
+/// CreateBuiltinFunction - Create a new builtin function with the specified
+/// type and name.
+llvm::Constant *
+CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
+                                     StringRef Name,
+                                     llvm::AttributeSet ExtraAttrs) {
+  llvm::Constant *C =
+      GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
+                              /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
+  if (auto *F = dyn_cast<llvm::Function>(C))
+    if (F->empty())
+      F->setCallingConv(getBuiltinCC());
+  return C;
+}
+
 /// isTypeConstant - Determine whether an object of this type can be emitted
 /// as a constant.
 ///
@@ -1790,7 +1848,10 @@
     
     OldGV->eraseFromParent();
   }
-  
+
+  if (supportsCOMDAT() && GV->isWeakForLinker())
+    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
+
   return GV;
 }
 
@@ -1823,7 +1884,7 @@
 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
   assert(!D->getInit() && "Cannot emit definite definitions here!");
 
-  if (MayDeferGeneration(D)) {
+  if (!MustBeEmitted(D)) {
     // If we have not seen a reference to this variable yet, place it
     // into the deferred declarations table to be emitted if needed
     // later.
@@ -1890,6 +1951,38 @@
     R.first->second = nullptr;
 }
 
+static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
+  if (!CGM.supportsCOMDAT())
+    return false;
+
+  if (D.hasAttr<SelectAnyAttr>())
+    return true;
+
+  GVALinkage Linkage;
+  if (auto *VD = dyn_cast<VarDecl>(&D))
+    Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
+  else
+    Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
+
+  switch (Linkage) {
+  case GVA_Internal:
+  case GVA_AvailableExternally:
+  case GVA_StrongExternal:
+    return false;
+  case GVA_DiscardableODR:
+  case GVA_StrongODR:
+    return true;
+  }
+  llvm_unreachable("No such linkage");
+}
+
+void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
+                                          llvm::GlobalObject &GO) {
+  if (!shouldBeInCOMDAT(*this, D))
+    return;
+  GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
+}
+
 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
   llvm::Constant *Init = nullptr;
   QualType ASTTy = D->getType();
@@ -2033,6 +2126,8 @@
     setTLSMode(GV, *D);
   }
 
+  maybeSetTrivialComdat(*D, *GV);
+
   // Emit the initializer function if necessary.
   if (NeedsGlobalCtor || NeedsGlobalDtor)
     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
@@ -2073,9 +2168,25 @@
 
   // Declarations with a required alignment do not have common linakge in MSVC
   // mode.
-  if (Context.getLangOpts().MSVCCompat &&
-      (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>()))
-    return true;
+  if (Context.getLangOpts().MSVCCompat) {
+    if (D->hasAttr<AlignedAttr>())
+      return true;
+    QualType VarType = D->getType();
+    if (Context.isAlignmentRequired(VarType))
+      return true;
+
+    if (const auto *RT = VarType->getAs<RecordType>()) {
+      const RecordDecl *RD = RT->getDecl();
+      for (const FieldDecl *FD : RD->fields()) {
+        if (FD->isBitField())
+          continue;
+        if (FD->hasAttr<AlignedAttr>())
+          return true;
+        if (Context.isAlignmentRequired(FD->getType()))
+          return true;
+      }
+    }
+  }
 
   return false;
 }
@@ -2367,6 +2478,8 @@
 
   MaybeHandleStaticInExternC(D, Fn);
 
+  maybeSetTrivialComdat(*D, *Fn);
+
   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
 
   setFunctionDefinitionAttributes(D, Fn);
@@ -2799,12 +2912,18 @@
   if (CGM.getLangOpts().OpenCL)
     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
 
+  llvm::Module &M = CGM.getModule();
   // Create a global variable for this string
   auto *GV = new llvm::GlobalVariable(
-      CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C,
-      GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
+      M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
+      nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
   GV->setAlignment(Alignment);
   GV->setUnnamedAddr(true);
+  if (GV->isWeakForLinker()) {
+    assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
+    GV->setComdat(M.getOrInsertComdat(GV->getName()));
+  }
+
   return GV;
 }
 
@@ -2963,10 +3082,19 @@
   // Create a global variable for this lifetime-extended temporary.
   llvm::GlobalValue::LinkageTypes Linkage =
       getLLVMLinkageVarDefinition(VD, Constant);
-  // There is no need for this temporary to have global linkage if the global
-  // variable has external linkage.
-  if (Linkage == llvm::GlobalVariable::ExternalLinkage)
-    Linkage = llvm::GlobalVariable::PrivateLinkage;
+  if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
+    const VarDecl *InitVD;
+    if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
+        isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
+      // Temporaries defined inside a class get linkonce_odr linkage because the
+      // class can be defined in multipe translation units.
+      Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
+    } else {
+      // There is no need for this temporary to have external linkage if the
+      // VarDecl has external linkage.
+      Linkage = llvm::GlobalVariable::InternalLinkage;
+    }
+  }
   unsigned AddrSpace = GetGlobalVarAddressSpace(
       VD, getContext().getTargetAddressSpace(MaterializedType));
   auto *GV = new llvm::GlobalVariable(
@@ -2976,6 +3104,8 @@
   setGlobalVisibility(GV, VD);
   GV->setAlignment(
       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
+  if (supportsCOMDAT() && GV->isWeakForLinker())
+    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
   if (VD->getTLSKind())
     setTLSMode(GV, *VD);
   Slot = GV;
@@ -3263,8 +3393,10 @@
   case Decl::ClassTemplateSpecialization: {
     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
     if (DebugInfo &&
-        Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
+        Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
+        Spec->hasDefinition())
       DebugInfo->completeTemplateDefinition(*Spec);
+    break;
   }
 
   default:
@@ -3272,6 +3404,7 @@
     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
     // function. Need to recode Decl::Kind to do that easily.
     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
+    break;
   }
 }
 
@@ -3376,10 +3509,9 @@
       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
 
   // TODO: should we report variant information for ctors/dtors?
-  llvm::Value *Ops[] = {
-    Addr,
-    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
-  };
+  llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
+                           llvm::ConstantAsMetadata::get(GetPointerConstant(
+                               CGM.getLLVMContext(), D.getDecl()))};
   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
 }
 
@@ -3442,7 +3574,9 @@
     llvm::Value *Addr = I.second;
     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
-      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
+      Alloca->setMetadata(
+          DeclPtrKind, llvm::MDNode::get(
+                           Context, llvm::ValueAsMetadata::getConstant(DAddr)));
     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
@@ -3456,9 +3590,7 @@
   std::string Version = getClangFullVersion();
   llvm::LLVMContext &Ctx = TheModule.getContext();
 
-  llvm::Value *IdentNode[] = {
-    llvm::MDString::get(Ctx, Version)
-  };
+  llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
 }
 
@@ -3486,9 +3618,8 @@
           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
         llvm::MDNode *CU = CUNode->getOperand(i);
-        llvm::Value *node[] = { CoverageFile, CU };
-        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
-        GCov->addOperand(N);
+        llvm::Metadata *Elts[] = {CoverageFile, CU};
+        GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
       }
     }
   }
@@ -3543,10 +3674,8 @@
         VD->getAnyInitializer() &&
         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
                                                         /*ForRef=*/false);
-    if (auto InitFunction =
-            getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
-                VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(),
-                PerformInit))
+    if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
+            VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
       CXXGlobalInits.push_back(InitFunction);
   }
 }
diff --git a/lib/CodeGen/CodeGenModule.h b/lib/CodeGen/CodeGenModule.h
index a20d66c..6902d19 100644
--- a/lib/CodeGen/CodeGenModule.h
+++ b/lib/CodeGen/CodeGenModule.h
@@ -150,6 +150,8 @@
 
   llvm::CallingConv::ID RuntimeCC;
   llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
+  llvm::CallingConv::ID BuiltinCC;
+  llvm::CallingConv::ID getBuiltinCC() const { return BuiltinCC; }
 };
 
 struct RREntrypoints {
@@ -256,9 +258,10 @@
 /// This class organizes the cross-function state that is used while generating
 /// LLVM code.
 class CodeGenModule : public CodeGenTypeCache {
-  CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION;
-  void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION;
+  CodeGenModule(const CodeGenModule &) = delete;
+  void operator=(const CodeGenModule &) = delete;
 
+public:
   struct Structor {
     Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
     Structor(int Priority, llvm::Constant *Initializer,
@@ -272,6 +275,7 @@
 
   typedef std::vector<Structor> CtorList;
 
+private:
   ASTContext &Context;
   const LangOptions &LangOpts;
   const CodeGenOptions &CodeGenOpts;
@@ -320,7 +324,7 @@
   /// referenced. These get code generated when the module is done.
   struct DeferredGlobal {
     DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
-    llvm::AssertingVH<llvm::GlobalValue> GV;
+    llvm::TrackingVH<llvm::GlobalValue> GV;
     GlobalDecl GD;
   };
   std::vector<DeferredGlobal> DeferredDeclsToEmit;
@@ -419,7 +423,7 @@
   llvm::SetVector<clang::Module *> ImportedModules;
 
   /// \brief A vector of metadata strings.
-  SmallVector<llvm::Value *, 16> LinkerOptionsMetadata;
+  SmallVector<llvm::Metadata *, 16> LinkerOptionsMetadata;
 
   /// @name Cache for Objective-C runtime types
   /// @{
@@ -589,9 +593,7 @@
 
   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
     if (!NoObjCARCExceptionsMetadata)
-      NoObjCARCExceptionsMetadata =
-        llvm::MDNode::get(getLLVMContext(),
-                          SmallVector<llvm::Value*,1>());
+      NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
     return NoObjCARCExceptionsMetadata;
   }
 
@@ -604,6 +606,7 @@
   const TargetInfo &getTarget() const { return Target; }
   const llvm::Triple &getTriple() const;
   bool supportsCOMDAT() const;
+  void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
 
   CGCXXABI &getCXXABI() const { return *ABI; }
   llvm::LLVMContext &getLLVMContext() { return VMContext; }
@@ -624,6 +627,9 @@
     return VTables.getMicrosoftVTableContext();
   }
 
+  CtorList &getGlobalCtors() { return GlobalCtors; }
+  CtorList &getGlobalDtors() { return GlobalDtors; }
+
   llvm::MDNode *getTBAAInfo(QualType QTy);
   llvm::MDNode *getTBAAInfoForVTablePtr();
   llvm::MDNode *getTBAAStructInfo(QualType QTy);
@@ -874,6 +880,11 @@
                                         StringRef Name,
                                         llvm::AttributeSet ExtraAttrs =
                                           llvm::AttributeSet());
+  /// Create a new compiler builtin function with the specified type and name.
+  llvm::Constant *CreateBuiltinFunction(llvm::FunctionType *Ty,
+                                        StringRef Name,
+                                        llvm::AttributeSet ExtraAttrs =
+                                          llvm::AttributeSet());
   /// Create a new runtime global variable with the specified type and name.
   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
                                         StringRef Name);
@@ -983,7 +994,7 @@
 
   void EmitTentativeDefinition(const VarDecl *D);
 
-  void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
+  void EmitVTable(CXXRecordDecl *Class);
 
   /// Emit the RTTI descriptors for the builtin types.
   void EmitFundamentalRTTIDescriptors();
@@ -1092,6 +1103,11 @@
   /// \param D Threadprivate declaration.
   void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
 
+  /// Emit bit set entries for the given vtable using the given layout if
+  /// vptr CFI is enabled.
+  void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
+                               const VTableLayout &VTLayout);
+
 private:
   llvm::Constant *
   GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
@@ -1190,9 +1206,15 @@
   /// Emits the initializer for a uuidof string.
   llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
 
-  /// Determine if the given decl can be emitted lazily; this is only relevant
-  /// for definitions. The given decl must be either a function or var decl.
-  bool MayDeferGeneration(const ValueDecl *D);
+  /// Determine whether the definition must be emitted; if this returns \c
+  /// false, the definition can be emitted lazily if it's used.
+  bool MustBeEmitted(const ValueDecl *D);
+
+  /// Determine whether the definition can be emitted eagerly, or should be
+  /// delayed until the end of the translation unit. This is relevant for
+  /// definitions whose linkage can change, e.g. implicit function instantions
+  /// which may later be explicitly instantiated.
+  bool MayBeEmittedEagerly(const ValueDecl *D);
 
   /// Check whether we can use a "simpler", more core exceptions personality
   /// function.
diff --git a/lib/CodeGen/CodeGenPGO.cpp b/lib/CodeGen/CodeGenPGO.cpp
index 2f1f211..a88335d 100644
--- a/lib/CodeGen/CodeGenPGO.cpp
+++ b/lib/CodeGen/CodeGenPGO.cpp
@@ -16,6 +16,7 @@
 #include "CoverageMappingGen.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
+#include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
 #include "llvm/ProfileData/InstrProfReader.h"
 #include "llvm/Support/Endian.h"
@@ -27,7 +28,7 @@
 
 void CodeGenPGO::setFuncName(StringRef Name,
                              llvm::GlobalValue::LinkageTypes Linkage) {
-  RawFuncName = Name;
+  StringRef RawFuncName = Name;
 
   // Function names may be prefixed with a binary '1' to indicate
   // that the backend should not modify the symbols due to any platform
@@ -35,204 +36,44 @@
   if (RawFuncName[0] == '\1')
     RawFuncName = RawFuncName.substr(1);
 
-  if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
-    PrefixedFuncName.reset(new std::string(RawFuncName));
-    return;
+  FuncName = RawFuncName;
+  if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
+    // For local symbols, prepend the main file name to distinguish them.
+    // Do not include the full path in the file name since there's no guarantee
+    // that it will stay the same, e.g., if the files are checked out from
+    // version control in different locations.
+    if (CGM.getCodeGenOpts().MainFileName.empty())
+      FuncName = FuncName.insert(0, "<unknown>:");
+    else
+      FuncName = FuncName.insert(0, CGM.getCodeGenOpts().MainFileName + ":");
   }
 
-  // For local symbols, prepend the main file name to distinguish them.
-  // Do not include the full path in the file name since there's no guarantee
-  // that it will stay the same, e.g., if the files are checked out from
-  // version control in different locations.
-  PrefixedFuncName.reset(new std::string(CGM.getCodeGenOpts().MainFileName));
-  if (PrefixedFuncName->empty())
-    PrefixedFuncName->assign("<unknown>");
-  PrefixedFuncName->append(":");
-  PrefixedFuncName->append(RawFuncName);
+  // If we're generating a profile, create a variable for the name.
+  if (CGM.getCodeGenOpts().ProfileInstrGenerate)
+    createFuncNameVar(Linkage);
 }
 
 void CodeGenPGO::setFuncName(llvm::Function *Fn) {
   setFuncName(Fn->getName(), Fn->getLinkage());
 }
 
-void CodeGenPGO::setVarLinkage(llvm::GlobalValue::LinkageTypes Linkage) {
-  // Set the linkage for variables based on the function linkage.  Usually, we
-  // want to match it, but available_externally and extern_weak both have the
-  // wrong semantics.
-  VarLinkage = Linkage;
-  switch (VarLinkage) {
-  case llvm::GlobalValue::ExternalWeakLinkage:
-    VarLinkage = llvm::GlobalValue::LinkOnceAnyLinkage;
-    break;
-  case llvm::GlobalValue::AvailableExternallyLinkage:
-    VarLinkage = llvm::GlobalValue::LinkOnceODRLinkage;
-    break;
-  default:
-    break;
-  }
-}
+void CodeGenPGO::createFuncNameVar(llvm::GlobalValue::LinkageTypes Linkage) {
+  // Usually, we want to match the function's linkage, but
+  // available_externally and extern_weak both have the wrong semantics.
+  if (Linkage == llvm::GlobalValue::ExternalWeakLinkage)
+    Linkage = llvm::GlobalValue::LinkOnceAnyLinkage;
+  else if (Linkage == llvm::GlobalValue::AvailableExternallyLinkage)
+    Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
 
-static llvm::Function *getRegisterFunc(CodeGenModule &CGM) {
-  return CGM.getModule().getFunction("__llvm_profile_register_functions");
-}
+  auto *Value =
+      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), FuncName, false);
+  FuncNameVar =
+      new llvm::GlobalVariable(CGM.getModule(), Value->getType(), true, Linkage,
+                               Value, "__llvm_profile_name_" + FuncName);
 
-static llvm::BasicBlock *getOrInsertRegisterBB(CodeGenModule &CGM) {
-  // Don't do this for Darwin.  compiler-rt uses linker magic.
-  if (CGM.getTarget().getTriple().isOSDarwin())
-    return nullptr;
-
-  // Only need to insert this once per module.
-  if (llvm::Function *RegisterF = getRegisterFunc(CGM))
-    return &RegisterF->getEntryBlock();
-
-  // Construct the function.
-  auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
-  auto *RegisterFTy = llvm::FunctionType::get(VoidTy, false);
-  auto *RegisterF = llvm::Function::Create(RegisterFTy,
-                                           llvm::GlobalValue::InternalLinkage,
-                                           "__llvm_profile_register_functions",
-                                           &CGM.getModule());
-  RegisterF->setUnnamedAddr(true);
-  if (CGM.getCodeGenOpts().DisableRedZone)
-    RegisterF->addFnAttr(llvm::Attribute::NoRedZone);
-
-  // Construct and return the entry block.
-  auto *BB = llvm::BasicBlock::Create(CGM.getLLVMContext(), "", RegisterF);
-  CGBuilderTy Builder(BB);
-  Builder.CreateRetVoid();
-  return BB;
-}
-
-static llvm::Constant *getOrInsertRuntimeRegister(CodeGenModule &CGM) {
-  auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
-  auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
-  auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
-  return CGM.getModule().getOrInsertFunction("__llvm_profile_register_function",
-                                             RuntimeRegisterTy);
-}
-
-static bool isMachO(const CodeGenModule &CGM) {
-  return CGM.getTarget().getTriple().isOSBinFormatMachO();
-}
-
-static StringRef getCountersSection(const CodeGenModule &CGM) {
-  return isMachO(CGM) ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
-}
-
-static StringRef getNameSection(const CodeGenModule &CGM) {
-  return isMachO(CGM) ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
-}
-
-static StringRef getDataSection(const CodeGenModule &CGM) {
-  return isMachO(CGM) ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
-}
-
-llvm::GlobalVariable *CodeGenPGO::buildDataVar() {
-  // Create name variable.
-  llvm::LLVMContext &Ctx = CGM.getLLVMContext();
-  auto *VarName = llvm::ConstantDataArray::getString(Ctx, getFuncName(),
-                                                     false);
-  auto *Name = new llvm::GlobalVariable(CGM.getModule(), VarName->getType(),
-                                        true, VarLinkage, VarName,
-                                        getFuncVarName("name"));
-  Name->setSection(getNameSection(CGM));
-  Name->setAlignment(1);
-
-  // Create data variable.
-  auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
-  auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
-  auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
-  auto *Int64PtrTy = llvm::Type::getInt64PtrTy(Ctx);
-  llvm::GlobalVariable *Data = nullptr;
-  if (RegionCounters) {
-    llvm::Type *DataTypes[] = {
-      Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy
-    };
-    auto *DataTy = llvm::StructType::get(Ctx, makeArrayRef(DataTypes));
-    llvm::Constant *DataVals[] = {
-      llvm::ConstantInt::get(Int32Ty, getFuncName().size()),
-      llvm::ConstantInt::get(Int32Ty, NumRegionCounters),
-      llvm::ConstantInt::get(Int64Ty, FunctionHash),
-      llvm::ConstantExpr::getBitCast(Name, Int8PtrTy),
-      llvm::ConstantExpr::getBitCast(RegionCounters, Int64PtrTy)
-    };
-    Data =
-      new llvm::GlobalVariable(CGM.getModule(), DataTy, true, VarLinkage,
-                               llvm::ConstantStruct::get(DataTy, DataVals),
-                               getFuncVarName("data"));
-
-    // All the data should be packed into an array in its own section.
-    Data->setSection(getDataSection(CGM));
-    Data->setAlignment(8);
-  }
-
-  // Create coverage mapping data variable.
-  if (!CoverageMapping.empty())
-    CGM.getCoverageMapping()->addFunctionMappingRecord(Name, getFuncName(),
-                                                       FunctionHash,
-                                                       CoverageMapping);
-
-  // Hide all these symbols so that we correctly get a copy for each
-  // executable.  The profile format expects names and counters to be
-  // contiguous, so references into shared objects would be invalid.
-  if (!llvm::GlobalValue::isLocalLinkage(VarLinkage)) {
-    Name->setVisibility(llvm::GlobalValue::HiddenVisibility);
-    if (Data) {
-      Data->setVisibility(llvm::GlobalValue::HiddenVisibility);
-      RegionCounters->setVisibility(llvm::GlobalValue::HiddenVisibility);
-    }
-  }
-
-  // Make sure the data doesn't get deleted.
-  if (Data) CGM.addUsedGlobal(Data);
-  return Data;
-}
-
-void CodeGenPGO::emitInstrumentationData() {
-  if (!RegionCounters)
-    return;
-
-  // Build the data.
-  auto *Data = buildDataVar();
-
-  // Register the data.
-  auto *RegisterBB = getOrInsertRegisterBB(CGM);
-  if (!RegisterBB)
-    return;
-  CGBuilderTy Builder(RegisterBB->getTerminator());
-  auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
-  Builder.CreateCall(getOrInsertRuntimeRegister(CGM),
-                     Builder.CreateBitCast(Data, VoidPtrTy));
-}
-
-llvm::Function *CodeGenPGO::emitInitialization(CodeGenModule &CGM) {
-  if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
-    return nullptr;
-
-  assert(CGM.getModule().getFunction("__llvm_profile_init") == nullptr &&
-         "profile initialization already emitted");
-
-  // Get the function to call at initialization.
-  llvm::Constant *RegisterF = getRegisterFunc(CGM);
-  if (!RegisterF)
-    return nullptr;
-
-  // Create the initialization function.
-  auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
-  auto *F = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false),
-                                   llvm::GlobalValue::InternalLinkage,
-                                   "__llvm_profile_init", &CGM.getModule());
-  F->setUnnamedAddr(true);
-  F->addFnAttr(llvm::Attribute::NoInline);
-  if (CGM.getCodeGenOpts().DisableRedZone)
-    F->addFnAttr(llvm::Attribute::NoRedZone);
-
-  // Add the basic block and the necessary calls.
-  CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", F));
-  Builder.CreateCall(RegisterF);
-  Builder.CreateRetVoid();
-
-  return F;
+  // Hide the symbol so that we correctly get a copy for each executable.
+  if (!llvm::GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
+    FuncNameVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
 }
 
 namespace {
@@ -297,482 +138,479 @@
 const unsigned PGOHash::NumTypesPerWord;
 const unsigned PGOHash::TooBig;
 
-  /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
-  struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
-    /// The next counter value to assign.
-    unsigned NextCounter;
-    /// The function hash.
-    PGOHash Hash;
-    /// The map of statements to counters.
-    llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
+/// A RecursiveASTVisitor that fills a map of statements to PGO counters.
+struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
+  /// The next counter value to assign.
+  unsigned NextCounter;
+  /// The function hash.
+  PGOHash Hash;
+  /// The map of statements to counters.
+  llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
 
-    MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
-        : NextCounter(0), CounterMap(CounterMap) {}
+  MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
+      : NextCounter(0), CounterMap(CounterMap) {}
 
-    // Blocks and lambdas are handled as separate functions, so we need not
-    // traverse them in the parent context.
-    bool TraverseBlockExpr(BlockExpr *BE) { return true; }
-    bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
-    bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
+  // Blocks and lambdas are handled as separate functions, so we need not
+  // traverse them in the parent context.
+  bool TraverseBlockExpr(BlockExpr *BE) { return true; }
+  bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
+  bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
 
-    bool VisitDecl(const Decl *D) {
-      switch (D->getKind()) {
-      default:
-        break;
-      case Decl::Function:
-      case Decl::CXXMethod:
-      case Decl::CXXConstructor:
-      case Decl::CXXDestructor:
-      case Decl::CXXConversion:
-      case Decl::ObjCMethod:
-      case Decl::Block:
-      case Decl::Captured:
-        CounterMap[D->getBody()] = NextCounter++;
-        break;
-      }
+  bool VisitDecl(const Decl *D) {
+    switch (D->getKind()) {
+    default:
+      break;
+    case Decl::Function:
+    case Decl::CXXMethod:
+    case Decl::CXXConstructor:
+    case Decl::CXXDestructor:
+    case Decl::CXXConversion:
+    case Decl::ObjCMethod:
+    case Decl::Block:
+    case Decl::Captured:
+      CounterMap[D->getBody()] = NextCounter++;
+      break;
+    }
+    return true;
+  }
+
+  bool VisitStmt(const Stmt *S) {
+    auto Type = getHashType(S);
+    if (Type == PGOHash::None)
       return true;
-    }
 
-    bool VisitStmt(const Stmt *S) {
-      auto Type = getHashType(S);
-      if (Type == PGOHash::None)
-        return true;
+    CounterMap[S] = NextCounter++;
+    Hash.combine(Type);
+    return true;
+  }
+  PGOHash::HashType getHashType(const Stmt *S) {
+    switch (S->getStmtClass()) {
+    default:
+      break;
+    case Stmt::LabelStmtClass:
+      return PGOHash::LabelStmt;
+    case Stmt::WhileStmtClass:
+      return PGOHash::WhileStmt;
+    case Stmt::DoStmtClass:
+      return PGOHash::DoStmt;
+    case Stmt::ForStmtClass:
+      return PGOHash::ForStmt;
+    case Stmt::CXXForRangeStmtClass:
+      return PGOHash::CXXForRangeStmt;
+    case Stmt::ObjCForCollectionStmtClass:
+      return PGOHash::ObjCForCollectionStmt;
+    case Stmt::SwitchStmtClass:
+      return PGOHash::SwitchStmt;
+    case Stmt::CaseStmtClass:
+      return PGOHash::CaseStmt;
+    case Stmt::DefaultStmtClass:
+      return PGOHash::DefaultStmt;
+    case Stmt::IfStmtClass:
+      return PGOHash::IfStmt;
+    case Stmt::CXXTryStmtClass:
+      return PGOHash::CXXTryStmt;
+    case Stmt::CXXCatchStmtClass:
+      return PGOHash::CXXCatchStmt;
+    case Stmt::ConditionalOperatorClass:
+      return PGOHash::ConditionalOperator;
+    case Stmt::BinaryConditionalOperatorClass:
+      return PGOHash::BinaryConditionalOperator;
+    case Stmt::BinaryOperatorClass: {
+      const BinaryOperator *BO = cast<BinaryOperator>(S);
+      if (BO->getOpcode() == BO_LAnd)
+        return PGOHash::BinaryOperatorLAnd;
+      if (BO->getOpcode() == BO_LOr)
+        return PGOHash::BinaryOperatorLOr;
+      break;
+    }
+    }
+    return PGOHash::None;
+  }
+};
 
-      CounterMap[S] = NextCounter++;
-      Hash.combine(Type);
-      return true;
-    }
-    PGOHash::HashType getHashType(const Stmt *S) {
-      switch (S->getStmtClass()) {
-      default:
-        break;
-      case Stmt::LabelStmtClass:
-        return PGOHash::LabelStmt;
-      case Stmt::WhileStmtClass:
-        return PGOHash::WhileStmt;
-      case Stmt::DoStmtClass:
-        return PGOHash::DoStmt;
-      case Stmt::ForStmtClass:
-        return PGOHash::ForStmt;
-      case Stmt::CXXForRangeStmtClass:
-        return PGOHash::CXXForRangeStmt;
-      case Stmt::ObjCForCollectionStmtClass:
-        return PGOHash::ObjCForCollectionStmt;
-      case Stmt::SwitchStmtClass:
-        return PGOHash::SwitchStmt;
-      case Stmt::CaseStmtClass:
-        return PGOHash::CaseStmt;
-      case Stmt::DefaultStmtClass:
-        return PGOHash::DefaultStmt;
-      case Stmt::IfStmtClass:
-        return PGOHash::IfStmt;
-      case Stmt::CXXTryStmtClass:
-        return PGOHash::CXXTryStmt;
-      case Stmt::CXXCatchStmtClass:
-        return PGOHash::CXXCatchStmt;
-      case Stmt::ConditionalOperatorClass:
-        return PGOHash::ConditionalOperator;
-      case Stmt::BinaryConditionalOperatorClass:
-        return PGOHash::BinaryConditionalOperator;
-      case Stmt::BinaryOperatorClass: {
-        const BinaryOperator *BO = cast<BinaryOperator>(S);
-        if (BO->getOpcode() == BO_LAnd)
-          return PGOHash::BinaryOperatorLAnd;
-        if (BO->getOpcode() == BO_LOr)
-          return PGOHash::BinaryOperatorLOr;
-        break;
-      }
-      }
-      return PGOHash::None;
-    }
+/// A StmtVisitor that propagates the raw counts through the AST and
+/// records the count at statements where the value may change.
+struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
+  /// PGO state.
+  CodeGenPGO &PGO;
+
+  /// A flag that is set when the current count should be recorded on the
+  /// next statement, such as at the exit of a loop.
+  bool RecordNextStmtCount;
+
+  /// The map of statements to count values.
+  llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
+
+  /// BreakContinueStack - Keep counts of breaks and continues inside loops.
+  struct BreakContinue {
+    uint64_t BreakCount;
+    uint64_t ContinueCount;
+    BreakContinue() : BreakCount(0), ContinueCount(0) {}
   };
+  SmallVector<BreakContinue, 8> BreakContinueStack;
 
-  /// A StmtVisitor that propagates the raw counts through the AST and
-  /// records the count at statements where the value may change.
-  struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
-    /// PGO state.
-    CodeGenPGO &PGO;
+  ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
+                      CodeGenPGO &PGO)
+      : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
 
-    /// A flag that is set when the current count should be recorded on the
-    /// next statement, such as at the exit of a loop.
-    bool RecordNextStmtCount;
-
-    /// The map of statements to count values.
-    llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
-
-    /// BreakContinueStack - Keep counts of breaks and continues inside loops.
-    struct BreakContinue {
-      uint64_t BreakCount;
-      uint64_t ContinueCount;
-      BreakContinue() : BreakCount(0), ContinueCount(0) {}
-    };
-    SmallVector<BreakContinue, 8> BreakContinueStack;
-
-    ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
-                        CodeGenPGO &PGO)
-        : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
-
-    void RecordStmtCount(const Stmt *S) {
-      if (RecordNextStmtCount) {
-        CountMap[S] = PGO.getCurrentRegionCount();
-        RecordNextStmtCount = false;
-      }
-    }
-
-    void VisitStmt(const Stmt *S) {
-      RecordStmtCount(S);
-      for (Stmt::const_child_range I = S->children(); I; ++I) {
-        if (*I)
-         this->Visit(*I);
-      }
-    }
-
-    void VisitFunctionDecl(const FunctionDecl *D) {
-      // Counter tracks entry to the function body.
-      RegionCounter Cnt(PGO, D->getBody());
-      Cnt.beginRegion();
-      CountMap[D->getBody()] = PGO.getCurrentRegionCount();
-      Visit(D->getBody());
-    }
-
-    // Skip lambda expressions. We visit these as FunctionDecls when we're
-    // generating them and aren't interested in the body when generating a
-    // parent context.
-    void VisitLambdaExpr(const LambdaExpr *LE) {}
-
-    void VisitCapturedDecl(const CapturedDecl *D) {
-      // Counter tracks entry to the capture body.
-      RegionCounter Cnt(PGO, D->getBody());
-      Cnt.beginRegion();
-      CountMap[D->getBody()] = PGO.getCurrentRegionCount();
-      Visit(D->getBody());
-    }
-
-    void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
-      // Counter tracks entry to the method body.
-      RegionCounter Cnt(PGO, D->getBody());
-      Cnt.beginRegion();
-      CountMap[D->getBody()] = PGO.getCurrentRegionCount();
-      Visit(D->getBody());
-    }
-
-    void VisitBlockDecl(const BlockDecl *D) {
-      // Counter tracks entry to the block body.
-      RegionCounter Cnt(PGO, D->getBody());
-      Cnt.beginRegion();
-      CountMap[D->getBody()] = PGO.getCurrentRegionCount();
-      Visit(D->getBody());
-    }
-
-    void VisitReturnStmt(const ReturnStmt *S) {
-      RecordStmtCount(S);
-      if (S->getRetValue())
-        Visit(S->getRetValue());
-      PGO.setCurrentRegionUnreachable();
-      RecordNextStmtCount = true;
-    }
-
-    void VisitGotoStmt(const GotoStmt *S) {
-      RecordStmtCount(S);
-      PGO.setCurrentRegionUnreachable();
-      RecordNextStmtCount = true;
-    }
-
-    void VisitLabelStmt(const LabelStmt *S) {
-      RecordNextStmtCount = false;
-      // Counter tracks the block following the label.
-      RegionCounter Cnt(PGO, S);
-      Cnt.beginRegion();
+  void RecordStmtCount(const Stmt *S) {
+    if (RecordNextStmtCount) {
       CountMap[S] = PGO.getCurrentRegionCount();
-      Visit(S->getSubStmt());
+      RecordNextStmtCount = false;
     }
+  }
 
-    void VisitBreakStmt(const BreakStmt *S) {
-      RecordStmtCount(S);
-      assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
-      BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount();
-      PGO.setCurrentRegionUnreachable();
-      RecordNextStmtCount = true;
+  void VisitStmt(const Stmt *S) {
+    RecordStmtCount(S);
+    for (Stmt::const_child_range I = S->children(); I; ++I) {
+      if (*I)
+        this->Visit(*I);
     }
+  }
 
-    void VisitContinueStmt(const ContinueStmt *S) {
-      RecordStmtCount(S);
-      assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
-      BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount();
-      PGO.setCurrentRegionUnreachable();
-      RecordNextStmtCount = true;
-    }
+  void VisitFunctionDecl(const FunctionDecl *D) {
+    // Counter tracks entry to the function body.
+    RegionCounter Cnt(PGO, D->getBody());
+    Cnt.beginRegion();
+    CountMap[D->getBody()] = PGO.getCurrentRegionCount();
+    Visit(D->getBody());
+  }
 
-    void VisitWhileStmt(const WhileStmt *S) {
-      RecordStmtCount(S);
-      // Counter tracks the body of the loop.
-      RegionCounter Cnt(PGO, S);
-      BreakContinueStack.push_back(BreakContinue());
-      // Visit the body region first so the break/continue adjustments can be
-      // included when visiting the condition.
-      Cnt.beginRegion();
-      CountMap[S->getBody()] = PGO.getCurrentRegionCount();
-      Visit(S->getBody());
-      Cnt.adjustForControlFlow();
+  // Skip lambda expressions. We visit these as FunctionDecls when we're
+  // generating them and aren't interested in the body when generating a
+  // parent context.
+  void VisitLambdaExpr(const LambdaExpr *LE) {}
 
-      // ...then go back and propagate counts through the condition. The count
-      // at the start of the condition is the sum of the incoming edges,
-      // the backedge from the end of the loop body, and the edges from
-      // continue statements.
-      BreakContinue BC = BreakContinueStack.pop_back_val();
-      Cnt.setCurrentRegionCount(Cnt.getParentCount() +
-                                Cnt.getAdjustedCount() + BC.ContinueCount);
-      CountMap[S->getCond()] = PGO.getCurrentRegionCount();
-      Visit(S->getCond());
-      Cnt.adjustForControlFlow();
-      Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
-      RecordNextStmtCount = true;
-    }
+  void VisitCapturedDecl(const CapturedDecl *D) {
+    // Counter tracks entry to the capture body.
+    RegionCounter Cnt(PGO, D->getBody());
+    Cnt.beginRegion();
+    CountMap[D->getBody()] = PGO.getCurrentRegionCount();
+    Visit(D->getBody());
+  }
 
-    void VisitDoStmt(const DoStmt *S) {
-      RecordStmtCount(S);
-      // Counter tracks the body of the loop.
-      RegionCounter Cnt(PGO, S);
-      BreakContinueStack.push_back(BreakContinue());
-      Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
-      CountMap[S->getBody()] = PGO.getCurrentRegionCount();
-      Visit(S->getBody());
-      Cnt.adjustForControlFlow();
+  void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
+    // Counter tracks entry to the method body.
+    RegionCounter Cnt(PGO, D->getBody());
+    Cnt.beginRegion();
+    CountMap[D->getBody()] = PGO.getCurrentRegionCount();
+    Visit(D->getBody());
+  }
 
-      BreakContinue BC = BreakContinueStack.pop_back_val();
-      // The count at the start of the condition is equal to the count at the
-      // end of the body. The adjusted count does not include either the
-      // fall-through count coming into the loop or the continue count, so add
-      // both of those separately. This is coincidentally the same equation as
-      // with while loops but for different reasons.
-      Cnt.setCurrentRegionCount(Cnt.getParentCount() +
-                                Cnt.getAdjustedCount() + BC.ContinueCount);
-      CountMap[S->getCond()] = PGO.getCurrentRegionCount();
-      Visit(S->getCond());
-      Cnt.adjustForControlFlow();
-      Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
-      RecordNextStmtCount = true;
-    }
+  void VisitBlockDecl(const BlockDecl *D) {
+    // Counter tracks entry to the block body.
+    RegionCounter Cnt(PGO, D->getBody());
+    Cnt.beginRegion();
+    CountMap[D->getBody()] = PGO.getCurrentRegionCount();
+    Visit(D->getBody());
+  }
 
-    void VisitForStmt(const ForStmt *S) {
-      RecordStmtCount(S);
-      if (S->getInit())
-        Visit(S->getInit());
-      // Counter tracks the body of the loop.
-      RegionCounter Cnt(PGO, S);
-      BreakContinueStack.push_back(BreakContinue());
-      // Visit the body region first. (This is basically the same as a while
-      // loop; see further comments in VisitWhileStmt.)
-      Cnt.beginRegion();
-      CountMap[S->getBody()] = PGO.getCurrentRegionCount();
-      Visit(S->getBody());
-      Cnt.adjustForControlFlow();
+  void VisitReturnStmt(const ReturnStmt *S) {
+    RecordStmtCount(S);
+    if (S->getRetValue())
+      Visit(S->getRetValue());
+    PGO.setCurrentRegionUnreachable();
+    RecordNextStmtCount = true;
+  }
 
-      // The increment is essentially part of the body but it needs to include
-      // the count for all the continue statements.
-      if (S->getInc()) {
-        Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
-                                  BreakContinueStack.back().ContinueCount);
-        CountMap[S->getInc()] = PGO.getCurrentRegionCount();
-        Visit(S->getInc());
-        Cnt.adjustForControlFlow();
-      }
+  void VisitGotoStmt(const GotoStmt *S) {
+    RecordStmtCount(S);
+    PGO.setCurrentRegionUnreachable();
+    RecordNextStmtCount = true;
+  }
 
-      BreakContinue BC = BreakContinueStack.pop_back_val();
+  void VisitLabelStmt(const LabelStmt *S) {
+    RecordNextStmtCount = false;
+    // Counter tracks the block following the label.
+    RegionCounter Cnt(PGO, S);
+    Cnt.beginRegion();
+    CountMap[S] = PGO.getCurrentRegionCount();
+    Visit(S->getSubStmt());
+  }
 
-      // ...then go back and propagate counts through the condition.
-      if (S->getCond()) {
-        Cnt.setCurrentRegionCount(Cnt.getParentCount() +
-                                  Cnt.getAdjustedCount() +
-                                  BC.ContinueCount);
-        CountMap[S->getCond()] = PGO.getCurrentRegionCount();
-        Visit(S->getCond());
-        Cnt.adjustForControlFlow();
-      }
-      Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
-      RecordNextStmtCount = true;
-    }
+  void VisitBreakStmt(const BreakStmt *S) {
+    RecordStmtCount(S);
+    assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
+    BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount();
+    PGO.setCurrentRegionUnreachable();
+    RecordNextStmtCount = true;
+  }
 
-    void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
-      RecordStmtCount(S);
-      Visit(S->getRangeStmt());
-      Visit(S->getBeginEndStmt());
-      // Counter tracks the body of the loop.
-      RegionCounter Cnt(PGO, S);
-      BreakContinueStack.push_back(BreakContinue());
-      // Visit the body region first. (This is basically the same as a while
-      // loop; see further comments in VisitWhileStmt.)
-      Cnt.beginRegion();
-      CountMap[S->getLoopVarStmt()] = PGO.getCurrentRegionCount();
-      Visit(S->getLoopVarStmt());
-      Visit(S->getBody());
-      Cnt.adjustForControlFlow();
+  void VisitContinueStmt(const ContinueStmt *S) {
+    RecordStmtCount(S);
+    assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
+    BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount();
+    PGO.setCurrentRegionUnreachable();
+    RecordNextStmtCount = true;
+  }
 
-      // The increment is essentially part of the body but it needs to include
-      // the count for all the continue statements.
+  void VisitWhileStmt(const WhileStmt *S) {
+    RecordStmtCount(S);
+    // Counter tracks the body of the loop.
+    RegionCounter Cnt(PGO, S);
+    BreakContinueStack.push_back(BreakContinue());
+    // Visit the body region first so the break/continue adjustments can be
+    // included when visiting the condition.
+    Cnt.beginRegion();
+    CountMap[S->getBody()] = PGO.getCurrentRegionCount();
+    Visit(S->getBody());
+    Cnt.adjustForControlFlow();
+
+    // ...then go back and propagate counts through the condition. The count
+    // at the start of the condition is the sum of the incoming edges,
+    // the backedge from the end of the loop body, and the edges from
+    // continue statements.
+    BreakContinue BC = BreakContinueStack.pop_back_val();
+    Cnt.setCurrentRegionCount(Cnt.getParentCount() + Cnt.getAdjustedCount() +
+                              BC.ContinueCount);
+    CountMap[S->getCond()] = PGO.getCurrentRegionCount();
+    Visit(S->getCond());
+    Cnt.adjustForControlFlow();
+    Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
+    RecordNextStmtCount = true;
+  }
+
+  void VisitDoStmt(const DoStmt *S) {
+    RecordStmtCount(S);
+    // Counter tracks the body of the loop.
+    RegionCounter Cnt(PGO, S);
+    BreakContinueStack.push_back(BreakContinue());
+    Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
+    CountMap[S->getBody()] = PGO.getCurrentRegionCount();
+    Visit(S->getBody());
+    Cnt.adjustForControlFlow();
+
+    BreakContinue BC = BreakContinueStack.pop_back_val();
+    // The count at the start of the condition is equal to the count at the
+    // end of the body. The adjusted count does not include either the
+    // fall-through count coming into the loop or the continue count, so add
+    // both of those separately. This is coincidentally the same equation as
+    // with while loops but for different reasons.
+    Cnt.setCurrentRegionCount(Cnt.getParentCount() + Cnt.getAdjustedCount() +
+                              BC.ContinueCount);
+    CountMap[S->getCond()] = PGO.getCurrentRegionCount();
+    Visit(S->getCond());
+    Cnt.adjustForControlFlow();
+    Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
+    RecordNextStmtCount = true;
+  }
+
+  void VisitForStmt(const ForStmt *S) {
+    RecordStmtCount(S);
+    if (S->getInit())
+      Visit(S->getInit());
+    // Counter tracks the body of the loop.
+    RegionCounter Cnt(PGO, S);
+    BreakContinueStack.push_back(BreakContinue());
+    // Visit the body region first. (This is basically the same as a while
+    // loop; see further comments in VisitWhileStmt.)
+    Cnt.beginRegion();
+    CountMap[S->getBody()] = PGO.getCurrentRegionCount();
+    Visit(S->getBody());
+    Cnt.adjustForControlFlow();
+
+    // The increment is essentially part of the body but it needs to include
+    // the count for all the continue statements.
+    if (S->getInc()) {
       Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
                                 BreakContinueStack.back().ContinueCount);
       CountMap[S->getInc()] = PGO.getCurrentRegionCount();
       Visit(S->getInc());
       Cnt.adjustForControlFlow();
+    }
 
-      BreakContinue BC = BreakContinueStack.pop_back_val();
+    BreakContinue BC = BreakContinueStack.pop_back_val();
 
-      // ...then go back and propagate counts through the condition.
-      Cnt.setCurrentRegionCount(Cnt.getParentCount() +
-                                Cnt.getAdjustedCount() +
+    // ...then go back and propagate counts through the condition.
+    if (S->getCond()) {
+      Cnt.setCurrentRegionCount(Cnt.getParentCount() + Cnt.getAdjustedCount() +
                                 BC.ContinueCount);
       CountMap[S->getCond()] = PGO.getCurrentRegionCount();
       Visit(S->getCond());
       Cnt.adjustForControlFlow();
-      Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
-      RecordNextStmtCount = true;
     }
+    Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
+    RecordNextStmtCount = true;
+  }
 
-    void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
-      RecordStmtCount(S);
-      Visit(S->getElement());
-      // Counter tracks the body of the loop.
-      RegionCounter Cnt(PGO, S);
-      BreakContinueStack.push_back(BreakContinue());
-      Cnt.beginRegion();
-      CountMap[S->getBody()] = PGO.getCurrentRegionCount();
-      Visit(S->getBody());
-      BreakContinue BC = BreakContinueStack.pop_back_val();
-      Cnt.adjustForControlFlow();
-      Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
-      RecordNextStmtCount = true;
-    }
+  void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
+    RecordStmtCount(S);
+    Visit(S->getRangeStmt());
+    Visit(S->getBeginEndStmt());
+    // Counter tracks the body of the loop.
+    RegionCounter Cnt(PGO, S);
+    BreakContinueStack.push_back(BreakContinue());
+    // Visit the body region first. (This is basically the same as a while
+    // loop; see further comments in VisitWhileStmt.)
+    Cnt.beginRegion();
+    CountMap[S->getLoopVarStmt()] = PGO.getCurrentRegionCount();
+    Visit(S->getLoopVarStmt());
+    Visit(S->getBody());
+    Cnt.adjustForControlFlow();
 
-    void VisitSwitchStmt(const SwitchStmt *S) {
-      RecordStmtCount(S);
-      Visit(S->getCond());
-      PGO.setCurrentRegionUnreachable();
-      BreakContinueStack.push_back(BreakContinue());
-      Visit(S->getBody());
-      // If the switch is inside a loop, add the continue counts.
-      BreakContinue BC = BreakContinueStack.pop_back_val();
-      if (!BreakContinueStack.empty())
-        BreakContinueStack.back().ContinueCount += BC.ContinueCount;
-      // Counter tracks the exit block of the switch.
-      RegionCounter ExitCnt(PGO, S);
-      ExitCnt.beginRegion();
-      RecordNextStmtCount = true;
-    }
+    // The increment is essentially part of the body but it needs to include
+    // the count for all the continue statements.
+    Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
+                              BreakContinueStack.back().ContinueCount);
+    CountMap[S->getInc()] = PGO.getCurrentRegionCount();
+    Visit(S->getInc());
+    Cnt.adjustForControlFlow();
 
-    void VisitCaseStmt(const CaseStmt *S) {
-      RecordNextStmtCount = false;
-      // Counter for this particular case. This counts only jumps from the
-      // switch header and does not include fallthrough from the case before
-      // this one.
-      RegionCounter Cnt(PGO, S);
-      Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
-      CountMap[S] = Cnt.getCount();
-      RecordNextStmtCount = true;
-      Visit(S->getSubStmt());
-    }
+    BreakContinue BC = BreakContinueStack.pop_back_val();
 
-    void VisitDefaultStmt(const DefaultStmt *S) {
-      RecordNextStmtCount = false;
-      // Counter for this default case. This does not include fallthrough from
-      // the previous case.
-      RegionCounter Cnt(PGO, S);
-      Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
-      CountMap[S] = Cnt.getCount();
-      RecordNextStmtCount = true;
-      Visit(S->getSubStmt());
-    }
+    // ...then go back and propagate counts through the condition.
+    Cnt.setCurrentRegionCount(Cnt.getParentCount() + Cnt.getAdjustedCount() +
+                              BC.ContinueCount);
+    CountMap[S->getCond()] = PGO.getCurrentRegionCount();
+    Visit(S->getCond());
+    Cnt.adjustForControlFlow();
+    Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
+    RecordNextStmtCount = true;
+  }
 
-    void VisitIfStmt(const IfStmt *S) {
-      RecordStmtCount(S);
-      // Counter tracks the "then" part of an if statement. The count for
-      // the "else" part, if it exists, will be calculated from this counter.
-      RegionCounter Cnt(PGO, S);
-      Visit(S->getCond());
+  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
+    RecordStmtCount(S);
+    Visit(S->getElement());
+    // Counter tracks the body of the loop.
+    RegionCounter Cnt(PGO, S);
+    BreakContinueStack.push_back(BreakContinue());
+    Cnt.beginRegion();
+    CountMap[S->getBody()] = PGO.getCurrentRegionCount();
+    Visit(S->getBody());
+    BreakContinue BC = BreakContinueStack.pop_back_val();
+    Cnt.adjustForControlFlow();
+    Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
+    RecordNextStmtCount = true;
+  }
 
-      Cnt.beginRegion();
-      CountMap[S->getThen()] = PGO.getCurrentRegionCount();
-      Visit(S->getThen());
-      Cnt.adjustForControlFlow();
+  void VisitSwitchStmt(const SwitchStmt *S) {
+    RecordStmtCount(S);
+    Visit(S->getCond());
+    PGO.setCurrentRegionUnreachable();
+    BreakContinueStack.push_back(BreakContinue());
+    Visit(S->getBody());
+    // If the switch is inside a loop, add the continue counts.
+    BreakContinue BC = BreakContinueStack.pop_back_val();
+    if (!BreakContinueStack.empty())
+      BreakContinueStack.back().ContinueCount += BC.ContinueCount;
+    // Counter tracks the exit block of the switch.
+    RegionCounter ExitCnt(PGO, S);
+    ExitCnt.beginRegion();
+    RecordNextStmtCount = true;
+  }
 
-      if (S->getElse()) {
-        Cnt.beginElseRegion();
-        CountMap[S->getElse()] = PGO.getCurrentRegionCount();
-        Visit(S->getElse());
-        Cnt.adjustForControlFlow();
-      }
-      Cnt.applyAdjustmentsToRegion(0);
-      RecordNextStmtCount = true;
-    }
+  void VisitCaseStmt(const CaseStmt *S) {
+    RecordNextStmtCount = false;
+    // Counter for this particular case. This counts only jumps from the
+    // switch header and does not include fallthrough from the case before
+    // this one.
+    RegionCounter Cnt(PGO, S);
+    Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
+    CountMap[S] = Cnt.getCount();
+    RecordNextStmtCount = true;
+    Visit(S->getSubStmt());
+  }
 
-    void VisitCXXTryStmt(const CXXTryStmt *S) {
-      RecordStmtCount(S);
-      Visit(S->getTryBlock());
-      for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
-        Visit(S->getHandler(I));
-      // Counter tracks the continuation block of the try statement.
-      RegionCounter Cnt(PGO, S);
-      Cnt.beginRegion();
-      RecordNextStmtCount = true;
-    }
+  void VisitDefaultStmt(const DefaultStmt *S) {
+    RecordNextStmtCount = false;
+    // Counter for this default case. This does not include fallthrough from
+    // the previous case.
+    RegionCounter Cnt(PGO, S);
+    Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
+    CountMap[S] = Cnt.getCount();
+    RecordNextStmtCount = true;
+    Visit(S->getSubStmt());
+  }
 
-    void VisitCXXCatchStmt(const CXXCatchStmt *S) {
-      RecordNextStmtCount = false;
-      // Counter tracks the catch statement's handler block.
-      RegionCounter Cnt(PGO, S);
-      Cnt.beginRegion();
-      CountMap[S] = PGO.getCurrentRegionCount();
-      Visit(S->getHandlerBlock());
-    }
+  void VisitIfStmt(const IfStmt *S) {
+    RecordStmtCount(S);
+    // Counter tracks the "then" part of an if statement. The count for
+    // the "else" part, if it exists, will be calculated from this counter.
+    RegionCounter Cnt(PGO, S);
+    Visit(S->getCond());
 
-    void VisitAbstractConditionalOperator(
-        const AbstractConditionalOperator *E) {
-      RecordStmtCount(E);
-      // Counter tracks the "true" part of a conditional operator. The
-      // count in the "false" part will be calculated from this counter.
-      RegionCounter Cnt(PGO, E);
-      Visit(E->getCond());
+    Cnt.beginRegion();
+    CountMap[S->getThen()] = PGO.getCurrentRegionCount();
+    Visit(S->getThen());
+    Cnt.adjustForControlFlow();
 
-      Cnt.beginRegion();
-      CountMap[E->getTrueExpr()] = PGO.getCurrentRegionCount();
-      Visit(E->getTrueExpr());
-      Cnt.adjustForControlFlow();
-
+    if (S->getElse()) {
       Cnt.beginElseRegion();
-      CountMap[E->getFalseExpr()] = PGO.getCurrentRegionCount();
-      Visit(E->getFalseExpr());
+      CountMap[S->getElse()] = PGO.getCurrentRegionCount();
+      Visit(S->getElse());
       Cnt.adjustForControlFlow();
-
-      Cnt.applyAdjustmentsToRegion(0);
-      RecordNextStmtCount = true;
     }
+    Cnt.applyAdjustmentsToRegion(0);
+    RecordNextStmtCount = true;
+  }
 
-    void VisitBinLAnd(const BinaryOperator *E) {
-      RecordStmtCount(E);
-      // Counter tracks the right hand side of a logical and operator.
-      RegionCounter Cnt(PGO, E);
-      Visit(E->getLHS());
-      Cnt.beginRegion();
-      CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
-      Visit(E->getRHS());
-      Cnt.adjustForControlFlow();
-      Cnt.applyAdjustmentsToRegion(0);
-      RecordNextStmtCount = true;
-    }
+  void VisitCXXTryStmt(const CXXTryStmt *S) {
+    RecordStmtCount(S);
+    Visit(S->getTryBlock());
+    for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
+      Visit(S->getHandler(I));
+    // Counter tracks the continuation block of the try statement.
+    RegionCounter Cnt(PGO, S);
+    Cnt.beginRegion();
+    RecordNextStmtCount = true;
+  }
 
-    void VisitBinLOr(const BinaryOperator *E) {
-      RecordStmtCount(E);
-      // Counter tracks the right hand side of a logical or operator.
-      RegionCounter Cnt(PGO, E);
-      Visit(E->getLHS());
-      Cnt.beginRegion();
-      CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
-      Visit(E->getRHS());
-      Cnt.adjustForControlFlow();
-      Cnt.applyAdjustmentsToRegion(0);
-      RecordNextStmtCount = true;
-    }
-  };
+  void VisitCXXCatchStmt(const CXXCatchStmt *S) {
+    RecordNextStmtCount = false;
+    // Counter tracks the catch statement's handler block.
+    RegionCounter Cnt(PGO, S);
+    Cnt.beginRegion();
+    CountMap[S] = PGO.getCurrentRegionCount();
+    Visit(S->getHandlerBlock());
+  }
+
+  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
+    RecordStmtCount(E);
+    // Counter tracks the "true" part of a conditional operator. The
+    // count in the "false" part will be calculated from this counter.
+    RegionCounter Cnt(PGO, E);
+    Visit(E->getCond());
+
+    Cnt.beginRegion();
+    CountMap[E->getTrueExpr()] = PGO.getCurrentRegionCount();
+    Visit(E->getTrueExpr());
+    Cnt.adjustForControlFlow();
+
+    Cnt.beginElseRegion();
+    CountMap[E->getFalseExpr()] = PGO.getCurrentRegionCount();
+    Visit(E->getFalseExpr());
+    Cnt.adjustForControlFlow();
+
+    Cnt.applyAdjustmentsToRegion(0);
+    RecordNextStmtCount = true;
+  }
+
+  void VisitBinLAnd(const BinaryOperator *E) {
+    RecordStmtCount(E);
+    // Counter tracks the right hand side of a logical and operator.
+    RegionCounter Cnt(PGO, E);
+    Visit(E->getLHS());
+    Cnt.beginRegion();
+    CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
+    Visit(E->getRHS());
+    Cnt.adjustForControlFlow();
+    Cnt.applyAdjustmentsToRegion(0);
+    RecordNextStmtCount = true;
+  }
+
+  void VisitBinLOr(const BinaryOperator *E) {
+    RecordStmtCount(E);
+    // Counter tracks the right hand side of a logical or operator.
+    RegionCounter Cnt(PGO, E);
+    Visit(E->getLHS());
+    Cnt.beginRegion();
+    CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
+    Visit(E->getRHS());
+    Cnt.adjustForControlFlow();
+    Cnt.applyAdjustmentsToRegion(0);
+    RecordNextStmtCount = true;
+  }
+};
 }
 
 void PGOHash::combine(HashType Type) {
@@ -812,35 +650,6 @@
   return endian::read<uint64_t, little, unaligned>(Result);
 }
 
-static void emitRuntimeHook(CodeGenModule &CGM) {
-  const char *const RuntimeVarName = "__llvm_profile_runtime";
-  const char *const RuntimeUserName = "__llvm_profile_runtime_user";
-  if (CGM.getModule().getGlobalVariable(RuntimeVarName))
-    return;
-
-  // Declare the runtime hook.
-  llvm::LLVMContext &Ctx = CGM.getLLVMContext();
-  auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
-  auto *Var = new llvm::GlobalVariable(CGM.getModule(), Int32Ty, false,
-                                       llvm::GlobalValue::ExternalLinkage,
-                                       nullptr, RuntimeVarName);
-
-  // Make a function that uses it.
-  auto *User = llvm::Function::Create(llvm::FunctionType::get(Int32Ty, false),
-                                      llvm::GlobalValue::LinkOnceODRLinkage,
-                                      RuntimeUserName, &CGM.getModule());
-  User->addFnAttr(llvm::Attribute::NoInline);
-  if (CGM.getCodeGenOpts().DisableRedZone)
-    User->addFnAttr(llvm::Attribute::NoRedZone);
-  CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", User));
-  auto *Load = Builder.CreateLoad(Var);
-  Builder.CreateRet(Load);
-
-  // Create a use of the function.  Now the definition of the runtime variable
-  // should get pulled in, along with any static initializears.
-  CGM.addUsedGlobal(User);
-}
-
 void CodeGenPGO::checkGlobalDecl(GlobalDecl GD) {
   // Make sure we only emit coverage mapping for one constructor/destructor.
   // Clang emits several functions for the constructor and the destructor of
@@ -864,15 +673,10 @@
     return;
   CGM.ClearUnusedCoverageMapping(D);
   setFuncName(Fn);
-  setVarLinkage(Fn->getLinkage());
 
   mapRegionCounters(D);
-  if (InstrumentRegions) {
-    emitRuntimeHook(CGM);
-    emitCounterVariables();
-    if (CGM.getCodeGenOpts().CoverageMapping)
-      emitCounterRegionMapping(D);
-  }
+  if (CGM.getCodeGenOpts().CoverageMapping)
+    emitCounterRegionMapping(D);
   if (PGOReader) {
     SourceManager &SM = CGM.getContext().getSourceManager();
     loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
@@ -905,12 +709,19 @@
   if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
     return;
 
+  std::string CoverageMapping;
   llvm::raw_string_ostream OS(CoverageMapping);
   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
                                 CGM.getContext().getSourceManager(),
                                 CGM.getLangOpts(), RegionCounterMap.get());
   MappingGen.emitCounterMapping(D, OS);
   OS.flush();
+
+  if (CoverageMapping.empty())
+    return;
+
+  CGM.getCoverageMapping()->addFunctionMappingRecord(
+      FuncNameVar, FuncName, FunctionHash, CoverageMapping);
 }
 
 void
@@ -918,21 +729,25 @@
                                     llvm::GlobalValue::LinkageTypes Linkage) {
   if (SkipCoverageMapping)
     return;
-  setFuncName(FuncName, Linkage);
-  setVarLinkage(Linkage);
-
   // Don't map the functions inside the system headers
   auto Loc = D->getBody()->getLocStart();
   if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
     return;
 
+  std::string CoverageMapping;
   llvm::raw_string_ostream OS(CoverageMapping);
   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
                                 CGM.getContext().getSourceManager(),
                                 CGM.getLangOpts());
   MappingGen.emitEmptyMapping(D, OS);
   OS.flush();
-  buildDataVar();
+
+  if (CoverageMapping.empty())
+    return;
+
+  setFuncName(FuncName, Linkage);
+  CGM.getCoverageMapping()->addFunctionMappingRecord(
+      FuncNameVar, FuncName, FunctionHash, CoverageMapping);
 }
 
 void CodeGenPGO::computeRegionCounts(const Decl *D) {
@@ -966,34 +781,25 @@
     Fn->addFnAttr(llvm::Attribute::Cold);
 }
 
-void CodeGenPGO::emitCounterVariables() {
-  llvm::LLVMContext &Ctx = CGM.getLLVMContext();
-  llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx),
-                                                    NumRegionCounters);
-  RegionCounters =
-    new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, VarLinkage,
-                             llvm::Constant::getNullValue(CounterTy),
-                             getFuncVarName("counters"));
-  RegionCounters->setAlignment(8);
-  RegionCounters->setSection(getCountersSection(CGM));
-}
-
 void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
-  if (!RegionCounters)
+  if (!CGM.getCodeGenOpts().ProfileInstrGenerate || !RegionCounterMap)
     return;
-  llvm::Value *Addr =
-    Builder.CreateConstInBoundsGEP2_64(RegionCounters, 0, Counter);
-  llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
-  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
-  Builder.CreateStore(Count, Addr);
+  if (!Builder.GetInsertPoint())
+    return;
+  auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
+  Builder.CreateCall4(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
+                      llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
+                      Builder.getInt64(FunctionHash),
+                      Builder.getInt32(NumRegionCounters),
+                      Builder.getInt32(Counter));
 }
 
 void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
                                   bool IsInMainFile) {
   CGM.getPGOStats().addVisited(IsInMainFile);
-  RegionCounts.reset(new std::vector<uint64_t>);
-  if (std::error_code EC = PGOReader->getFunctionCounts(
-          getFuncName(), FunctionHash, *RegionCounts)) {
+  RegionCounts.clear();
+  if (std::error_code EC =
+          PGOReader->getFunctionCounts(FuncName, FunctionHash, RegionCounts)) {
     if (EC == llvm::instrprof_error::unknown_function)
       CGM.getPGOStats().addMissing(IsInMainFile);
     else if (EC == llvm::instrprof_error::hash_mismatch)
@@ -1001,17 +807,10 @@
     else if (EC == llvm::instrprof_error::malformed)
       // TODO: Consider a more specific warning for this case.
       CGM.getPGOStats().addMismatched(IsInMainFile);
-    RegionCounts.reset();
+    RegionCounts.clear();
   }
 }
 
-void CodeGenPGO::destroyRegionCounters() {
-  RegionCounterMap.reset();
-  StmtCountMap.reset();
-  RegionCounts.reset();
-  RegionCounters = nullptr;
-}
-
 /// \brief Calculate what to divide by to scale weights.
 ///
 /// Given the maximum weight, calculate a divisor that will scale all the
diff --git a/lib/CodeGen/CodeGenPGO.h b/lib/CodeGen/CodeGenPGO.h
index fd1418f..431c850 100644
--- a/lib/CodeGen/CodeGenPGO.h
+++ b/lib/CodeGen/CodeGenPGO.h
@@ -31,39 +31,28 @@
 class CodeGenPGO {
 private:
   CodeGenModule &CGM;
-  std::unique_ptr<std::string> PrefixedFuncName;
-  StringRef RawFuncName;
-  llvm::GlobalValue::LinkageTypes VarLinkage;
+  std::string FuncName;
+  llvm::GlobalVariable *FuncNameVar;
 
   unsigned NumRegionCounters;
   uint64_t FunctionHash;
-  llvm::GlobalVariable *RegionCounters;
   std::unique_ptr<llvm::DenseMap<const Stmt *, unsigned>> RegionCounterMap;
   std::unique_ptr<llvm::DenseMap<const Stmt *, uint64_t>> StmtCountMap;
-  std::unique_ptr<std::vector<uint64_t>> RegionCounts;
+  std::vector<uint64_t> RegionCounts;
   uint64_t CurrentRegionCount;
-  std::string CoverageMapping;
   /// \brief A flag that is set to true when this function doesn't need
   /// to have coverage mapping data.
   bool SkipCoverageMapping;
 
 public:
   CodeGenPGO(CodeGenModule &CGM)
-      : CGM(CGM), NumRegionCounters(0), FunctionHash(0),
-        RegionCounters(nullptr), CurrentRegionCount(0),
+      : CGM(CGM), NumRegionCounters(0), FunctionHash(0), CurrentRegionCount(0),
         SkipCoverageMapping(false) {}
 
   /// Whether or not we have PGO region data for the current function. This is
   /// false both when we have no data at all and when our data has been
   /// discarded.
-  bool haveRegionCounts() const { return RegionCounts != nullptr; }
-
-  /// Get the string used to identify this function in the profile data.
-  /// For functions with local linkage, this includes the main file name.
-  StringRef getFuncName() const { return StringRef(*PrefixedFuncName); }
-  std::string getFuncVarName(StringRef VarName) const {
-    return ("__llvm_profile_" + VarName + "_" + RawFuncName).str();
-  }
+  bool haveRegionCounts() const { return !RegionCounts.empty(); }
 
   /// Return the counter value of the current region.
   uint64_t getCurrentRegionCount() const { return CurrentRegionCount; }
@@ -111,13 +100,6 @@
   /// generates global variables or associates PGO data with each of the
   /// counters depending on whether we are generating or using instrumentation.
   void assignRegionCounters(const Decl *D, llvm::Function *Fn);
-  /// Emit static data structures for instrumentation data.
-  void emitInstrumentationData();
-  /// Clean up region counter state. Must be called if assignRegionCounters is
-  /// used.
-  void destroyRegionCounters();
-  /// Emit static initialization code, if any.
-  static llvm::Function *emitInitialization(CodeGenModule &CGM);
   /// Emit a coverage mapping range with a counter zero
   /// for an unused declaration.
   void emitEmptyCounterMapping(const Decl *D, StringRef FuncName,
@@ -125,7 +107,7 @@
 private:
   void setFuncName(llvm::Function *Fn);
   void setFuncName(StringRef Name, llvm::GlobalValue::LinkageTypes Linkage);
-  void setVarLinkage(llvm::GlobalValue::LinkageTypes Linkage);
+  void createFuncNameVar(llvm::GlobalValue::LinkageTypes Linkage);
   void mapRegionCounters(const Decl *D);
   void computeRegionCounts(const Decl *D);
   void applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
@@ -133,7 +115,6 @@
   void loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
                         bool IsInMainFile);
   void emitCounterVariables();
-  llvm::GlobalVariable *buildDataVar();
   void emitCounterRegionMapping(const Decl *D);
 
   /// Emit code to increment the counter at the given index
@@ -151,7 +132,7 @@
   uint64_t getRegionCount(unsigned Counter) {
     if (!haveRegionCounts())
       return 0;
-    return (*RegionCounts)[Counter];
+    return RegionCounts[Counter];
   }
 
   friend class RegionCounter;
diff --git a/lib/CodeGen/CodeGenTypes.cpp b/lib/CodeGen/CodeGenTypes.cpp
index 44494ae..67a9fbe 100644
--- a/lib/CodeGen/CodeGenTypes.cpp
+++ b/lib/CodeGen/CodeGenTypes.cpp
@@ -406,7 +406,7 @@
     llvm_unreachable("Unexpected undeduced auto type!");
   case Type::Complex: {
     llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
-    ResultType = llvm::StructType::get(EltTy, EltTy, NULL);
+    ResultType = llvm::StructType::get(EltTy, EltTy, nullptr);
     break;
   }
   case Type::LValueReference:
diff --git a/lib/CodeGen/CodeGenTypes.h b/lib/CodeGen/CodeGenTypes.h
index 51e0309..64c5799 100644
--- a/lib/CodeGen/CodeGenTypes.h
+++ b/lib/CodeGen/CodeGenTypes.h
@@ -248,7 +248,8 @@
                                                   CXXCtorType CtorKind,
                                                   unsigned ExtraArgs);
   const CGFunctionInfo &arrangeFreeFunctionCall(const CallArgList &Args,
-                                                const FunctionType *Ty);
+                                                const FunctionType *Ty,
+                                                bool ChainCall);
   const CGFunctionInfo &arrangeFreeFunctionCall(QualType ResTy,
                                                 const CallArgList &args,
                                                 FunctionType::ExtInfo info,
@@ -273,7 +274,8 @@
   ///
   /// \param argTypes - must all actually be canonical as params
   const CGFunctionInfo &arrangeLLVMFunctionInfo(CanQualType returnType,
-                                                bool IsInstanceMethod,
+                                                bool instanceMethod,
+                                                bool chainCall,
                                                 ArrayRef<CanQualType> argTypes,
                                                 FunctionType::ExtInfo info,
                                                 RequiredArgs args);
diff --git a/lib/CodeGen/CoverageMappingGen.cpp b/lib/CodeGen/CoverageMappingGen.cpp
index ac0c22c..55e7334 100644
--- a/lib/CodeGen/CoverageMappingGen.cpp
+++ b/lib/CodeGen/CoverageMappingGen.cpp
@@ -15,10 +15,11 @@
 #include "CodeGenFunction.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Lex/Lexer.h"
-#include "llvm/ProfileData/InstrProfReader.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/ProfileData/CoverageMapping.h"
-#include "llvm/ProfileData/CoverageMappingWriter.h"
 #include "llvm/ProfileData/CoverageMappingReader.h"
+#include "llvm/ProfileData/CoverageMappingWriter.h"
+#include "llvm/ProfileData/InstrProfReader.h"
 #include "llvm/Support/FileSystem.h"
 
 using namespace clang;
@@ -33,101 +34,51 @@
 
 /// \brief A region of source code that can be mapped to a counter.
 class SourceMappingRegion {
-public:
-  enum RegionFlags {
-    /// \brief This region won't be emitted if it wasn't extended.
-    /// This is useful so that we won't emit source ranges for single tokens
-    /// that we don't really care that much about, like:
-    ///   the '(' token in #define MACRO (
-    IgnoreIfNotExtended = 0x0001,
-  };
-
-private:
-  FileID File, MacroArgumentFile;
-
   Counter Count;
 
-  /// \brief A statement that initiated the count of Zero.
-  ///
-  /// This initiator statement is useful to prevent merging of unreachable
-  /// regions with different statements that caused the counter to become
-  /// unreachable.
-  const Stmt *UnreachableInitiator;
-
-  /// \brief A statement that separates certain mapping regions into groups.
-  ///
-  /// The group statement is sometimes useful when we are emitting the source
-  /// regions not in their correct lexical order, e.g. the regions for the
-  /// incrementation expression in the 'for' construct. By marking the regions
-  /// in the incrementation expression with the group statement, we avoid the
-  /// merging of the regions from the incrementation expression and the loop's
-  /// body.
-  const Stmt *Group;
-
   /// \brief The region's starting location.
-  SourceLocation LocStart;
+  Optional<SourceLocation> LocStart;
 
   /// \brief The region's ending location.
-  SourceLocation LocEnd, AlternativeLocEnd;
-  unsigned Flags;
+  Optional<SourceLocation> LocEnd;
 
 public:
-  SourceMappingRegion(FileID File, FileID MacroArgumentFile, Counter Count,
-                      const Stmt *UnreachableInitiator, const Stmt *Group,
-                      SourceLocation LocStart, SourceLocation LocEnd,
-                      unsigned Flags = 0)
-      : File(File), MacroArgumentFile(MacroArgumentFile), Count(Count),
-        UnreachableInitiator(UnreachableInitiator), Group(Group),
-        LocStart(LocStart), LocEnd(LocEnd), AlternativeLocEnd(LocStart),
-        Flags(Flags) {}
+  SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
+                      Optional<SourceLocation> LocEnd)
+      : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
 
-  const FileID &getFile() const { return File; }
+  SourceMappingRegion(SourceMappingRegion &&Region)
+      : Count(std::move(Region.Count)), LocStart(std::move(Region.LocStart)),
+        LocEnd(std::move(Region.LocEnd)) {}
+
+  SourceMappingRegion &operator=(SourceMappingRegion &&RHS) {
+    Count = std::move(RHS.Count);
+    LocStart = std::move(RHS.LocStart);
+    LocEnd = std::move(RHS.LocEnd);
+    return *this;
+  }
 
   const Counter &getCounter() const { return Count; }
 
-  const SourceLocation &getStartLoc() const { return LocStart; }
+  void setCounter(Counter C) { Count = C; }
 
-  const SourceLocation &getEndLoc(const SourceManager &SM) const {
-    if (SM.getFileID(LocEnd) != File)
-      return AlternativeLocEnd;
-    return LocEnd;
+  bool hasStartLoc() const { return LocStart.hasValue(); }
+
+  void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
+
+  const SourceLocation &getStartLoc() const {
+    assert(LocStart && "Region has no start location");
+    return *LocStart;
   }
 
-  bool hasFlag(RegionFlags Flag) const { return (Flags & Flag) != 0; }
+  bool hasEndLoc() const { return LocEnd.hasValue(); }
 
-  void setFlag(RegionFlags Flag) { Flags |= Flag; }
+  void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
 
-  void clearFlag(RegionFlags Flag) { Flags &= ~Flag; }
-
-  /// \brief Return true if two regions can be merged together.
-  bool isMergeable(SourceMappingRegion &R) {
-    // FIXME: We allow merging regions with a gap in between them. Should we?
-    return File == R.File && MacroArgumentFile == R.MacroArgumentFile &&
-           Count == R.Count && UnreachableInitiator == R.UnreachableInitiator &&
-           Group == R.Group;
+  const SourceLocation &getEndLoc() const {
+    assert(LocEnd && "Region has no end location");
+    return *LocEnd;
   }
-
-  /// \brief A comparison that sorts such that mergeable regions are adjacent.
-  friend bool operator<(const SourceMappingRegion &LHS,
-                        const SourceMappingRegion &RHS) {
-    return std::tie(LHS.File, LHS.MacroArgumentFile, LHS.Count,
-                    LHS.UnreachableInitiator, LHS.Group) <
-           std::tie(RHS.File, RHS.MacroArgumentFile, RHS.Count,
-                    RHS.UnreachableInitiator, RHS.Group);
-  }
-};
-
-/// \brief The state of the coverage mapping builder.
-struct SourceMappingState {
-  Counter CurrentRegionCount;
-  const Stmt *CurrentSourceGroup;
-  const Stmt *CurrentUnreachableRegionInitiator;
-
-  SourceMappingState(Counter CurrentRegionCount, const Stmt *CurrentSourceGroup,
-                     const Stmt *CurrentUnreachableRegionInitiator)
-      : CurrentRegionCount(CurrentRegionCount),
-        CurrentSourceGroup(CurrentSourceGroup),
-        CurrentUnreachableRegionInitiator(CurrentUnreachableRegionInitiator) {}
 };
 
 /// \brief Provides the common functionality for the different
@@ -139,26 +90,11 @@
   const LangOptions &LangOpts;
 
 private:
-  struct FileInfo {
-    /// \brief The file id that will be used by the coverage mapping system.
-    unsigned CovMappingFileID;
-    const FileEntry *Entry;
-
-    FileInfo(unsigned CovMappingFileID, const FileEntry *Entry)
-        : CovMappingFileID(CovMappingFileID), Entry(Entry) {}
-  };
-
-  /// \brief This mapping maps clang's FileIDs to file ids used
-  /// by the coverage mapping system and clang's file entries.
-  llvm::SmallDenseMap<FileID, FileInfo, 8> FileIDMapping;
+  /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
+  llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
+      FileIDMapping;
 
 public:
-  /// \brief The statement that corresponds to the current source group.
-  const Stmt *CurrentSourceGroup;
-
-  /// \brief The statement the initiated the current unreachable region.
-  const Stmt *CurrentUnreachableRegionInitiator;
-
   /// \brief The coverage mapping regions for this function
   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
   /// \brief The source mapping regions for this function.
@@ -166,60 +102,99 @@
 
   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
                          const LangOptions &LangOpts)
-      : CVM(CVM), SM(SM), LangOpts(LangOpts),
-        CurrentSourceGroup(nullptr),
-        CurrentUnreachableRegionInitiator(nullptr) {}
+      : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
 
   /// \brief Return the precise end location for the given token.
   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
-    return Lexer::getLocForEndOfToken(SM.getSpellingLoc(Loc), 0, SM, LangOpts);
+    // We avoid getLocForEndOfToken here, because it doesn't do what we want for
+    // macro locations, which we just treat as expanded files.
+    unsigned TokLen =
+        Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
+    return Loc.getLocWithOffset(TokLen);
   }
 
-  /// \brief Create the mapping that maps from the function's file ids to
-  /// the indices for the translation unit's filenames.
-  void createFileIDMapping(SmallVectorImpl<unsigned> &Mapping) {
-    Mapping.resize(FileIDMapping.size(), 0);
-    for (const auto &I : FileIDMapping)
-      Mapping[I.second.CovMappingFileID] = CVM.getFileID(I.second.Entry);
+  /// \brief Return the start location of an included file or expanded macro.
+  SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
+    if (Loc.isMacroID())
+      return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
+    return SM.getLocForStartOfFile(SM.getFileID(Loc));
   }
 
-  /// \brief Get the coverage mapping file id that corresponds to the given
-  /// clang file id. If such file id doesn't exist, it gets added to the
-  /// mapping that maps from clang's file ids to coverage mapping file ids.
-  /// Return true if there was an error getting the coverage mapping file id.
-  /// An example of an when this function fails is when the region tries
-  /// to get a coverage file id for a location in a built-in macro.
-  bool getCoverageFileID(SourceLocation LocStart, FileID File,
-                         FileID SpellingFile, unsigned &Result) {
-    auto Mapping = FileIDMapping.find(File);
-    if (Mapping != FileIDMapping.end()) {
-      Result = Mapping->second.CovMappingFileID;
-      return false;
+  /// \brief Return the end location of an included file or expanded macro.
+  SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
+    if (Loc.isMacroID())
+      return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
+                                  SM.getFileOffset(Loc) - 1);
+    return SM.getLocForEndOfFile(SM.getFileID(Loc));
+  }
+
+  /// \brief Find out where the current file is included or macro is expanded.
+  SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
+    return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
+                           : SM.getIncludeLoc(SM.getFileID(Loc));
+  }
+
+  /// \brief Get the start of \c S ignoring macro argument locations.
+  SourceLocation getStart(const Stmt *S) {
+    SourceLocation Loc = S->getLocStart();
+    while (SM.isMacroArgExpansion(Loc))
+      Loc = SM.getImmediateExpansionRange(Loc).first;
+    return Loc;
+  }
+
+  /// \brief Get the end of \c S ignoring macro argument locations.
+  SourceLocation getEnd(const Stmt *S) {
+    SourceLocation Loc = S->getLocEnd();
+    while (SM.isMacroArgExpansion(Loc))
+      Loc = SM.getImmediateExpansionRange(Loc).first;
+    return Loc;
+  }
+
+  /// \brief Find the set of files we have regions for and assign IDs
+  ///
+  /// Fills \c Mapping with the virtual file mapping needed to write out
+  /// coverage and collects the necessary file information to emit source and
+  /// expansion regions.
+  void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
+    FileIDMapping.clear();
+
+    SmallVector<FileID, 8> Visited;
+    SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
+    for (const auto &Region : SourceRegions) {
+      SourceLocation Loc = Region.getStartLoc();
+      FileID File = SM.getFileID(Loc);
+      if (std::find(Visited.begin(), Visited.end(), File) != Visited.end())
+        continue;
+      Visited.push_back(File);
+
+      unsigned Depth = 0;
+      for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
+           !Parent.isInvalid(); Parent = getIncludeOrExpansionLoc(Parent))
+        ++Depth;
+      FileLocs.push_back(std::make_pair(Loc, Depth));
     }
+    std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
 
-    auto Entry = SM.getFileEntryForID(SpellingFile);
-    if (!Entry)
-      return true;
+    for (const auto &FL : FileLocs) {
+      SourceLocation Loc = FL.first;
+      FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
+      auto Entry = SM.getFileEntryForID(SpellingFile);
+      if (!Entry)
+        continue;
 
-    Result = FileIDMapping.size();
-    FileIDMapping.insert(std::make_pair(File, FileInfo(Result, Entry)));
-    createFileExpansionRegion(LocStart, File);
-    return false;
+      FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
+      Mapping.push_back(CVM.getFileID(Entry));
+    }
   }
 
-  /// \brief Get the coverage mapping file id that corresponds to the given
-  /// clang file id.
-  /// Return true if there was an error getting the coverage mapping file id.
-  bool getExistingCoverageFileID(FileID File, unsigned &Result) {
-    // Make sure that the file is valid.
-    if (File.isInvalid())
-      return true;
-    auto Mapping = FileIDMapping.find(File);
-    if (Mapping != FileIDMapping.end()) {
-      Result = Mapping->second.CovMappingFileID;
-      return false;
-    }
-    return true;
+  /// \brief Get the coverage mapping file ID for \c Loc.
+  ///
+  /// If such file id doesn't exist, return None.
+  Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
+    auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
+    if (Mapping != FileIDMapping.end())
+      return Mapping->second.first;
+    return None;
   }
 
   /// \brief Return true if the given clang's file id has a corresponding
@@ -248,162 +223,83 @@
     for (const auto &I : SkippedRanges) {
       auto LocStart = I.getBegin();
       auto LocEnd = I.getEnd();
-      auto FileStart = SM.getFileID(LocStart);
-      if (!hasExistingCoverageFileID(FileStart))
-        continue;
-      auto ActualFileStart = SM.getDecomposedSpellingLoc(LocStart).first;
-      if (ActualFileStart != SM.getDecomposedSpellingLoc(LocEnd).first)
-        // Ignore regions that span across multiple files.
-        continue;
+      assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
+             "region spans multiple files");
 
-      unsigned CovFileID;
-      if (getCoverageFileID(LocStart, FileStart, ActualFileStart, CovFileID))
+      auto CovFileID = getCoverageFileID(LocStart);
+      if (!CovFileID)
         continue;
       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
-      CounterMappingRegion Region(Counter(), CovFileID, LineStart, ColumnStart,
-                                  LineEnd, ColumnEnd, false,
-                                  CounterMappingRegion::SkippedRegion);
+      auto Region = CounterMappingRegion::makeSkipped(
+          *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
       // Make sure that we only collect the regions that are inside
       // the souce code of this function.
-      if (Region.LineStart >= FileLineRanges[CovFileID].first &&
-          Region.LineEnd <= FileLineRanges[CovFileID].second)
+      if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
+          Region.LineEnd <= FileLineRanges[*CovFileID].second)
         MappingRegions.push_back(Region);
     }
   }
 
-  /// \brief Create a mapping region that correponds to an expansion of
-  /// a macro or an embedded include.
-  void createFileExpansionRegion(SourceLocation Loc, FileID ExpandedFile) {
-    SourceLocation LocStart;
-    if (Loc.isMacroID())
-      LocStart = SM.getImmediateExpansionRange(Loc).first;
-    else {
-      LocStart = SM.getIncludeLoc(ExpandedFile);
-      if (LocStart.isInvalid())
-        return; // This file has no expansion region.
-    }
-
-    auto File = SM.getFileID(LocStart);
-    auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
-    unsigned CovFileID, ExpandedFileID;
-    if (getExistingCoverageFileID(ExpandedFile, ExpandedFileID))
-      return;
-    if (getCoverageFileID(LocStart, File, SpellingFile, CovFileID))
-      return;
-    unsigned LineStart = SM.getSpellingLineNumber(LocStart);
-    unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
-    unsigned LineEnd = LineStart;
-    // Compute the end column manually as Lexer::getLocForEndOfToken doesn't
-    // give the correct result in all cases.
-    unsigned ColumnEnd =
-        ColumnStart +
-        Lexer::MeasureTokenLength(SM.getSpellingLoc(LocStart), SM, LangOpts);
-
-    MappingRegions.push_back(CounterMappingRegion(
-        Counter(), CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd,
-        false, CounterMappingRegion::ExpansionRegion));
-    MappingRegions.back().ExpandedFileID = ExpandedFileID;
-  }
-
-  /// \brief Enter a source region group that is identified by the given
-  /// statement.
-  /// It's not possible to enter a group when there is already
-  /// another group present.
-  void beginSourceRegionGroup(const Stmt *Group) {
-    assert(!CurrentSourceGroup);
-    CurrentSourceGroup = Group;
-  }
-
-  /// \brief Exit the current source region group.
-  void endSourceRegionGroup() { CurrentSourceGroup = nullptr; }
-
-  /// \brief Associate a counter with a given source code range.
-  void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
-                          Counter Count, const Stmt *UnreachableInitiator,
-                          const Stmt *SourceGroup, unsigned Flags = 0,
-                          FileID MacroArgumentFile = FileID()) {
-    if (SM.isMacroArgExpansion(LocStart)) {
-      // Map the code range with the macro argument's value.
-      mapSourceCodeRange(SM.getImmediateSpellingLoc(LocStart),
-                         SM.getImmediateSpellingLoc(LocEnd), Count,
-                         UnreachableInitiator, SourceGroup, Flags,
-                         SM.getFileID(LocStart));
-      // Map the code range where the macro argument is referenced.
-      SourceLocation RefLocStart(SM.getImmediateExpansionRange(LocStart).first);
-      SourceLocation RefLocEnd(RefLocStart);
-      if (SM.isMacroArgExpansion(RefLocStart))
-        mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
-                           SourceGroup, 0, SM.getFileID(RefLocStart));
-      else
-        mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
-                           SourceGroup);
-      return;
-    }
-    auto File = SM.getFileID(LocStart);
-    // Make sure that the file id is valid.
-    if (File.isInvalid())
-      return;
-    SourceRegions.emplace_back(File, MacroArgumentFile, Count,
-                               UnreachableInitiator, SourceGroup, LocStart,
-                               LocEnd, Flags);
-  }
-
-  void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
-                          Counter Count, unsigned Flags = 0) {
-    mapSourceCodeRange(LocStart, LocEnd, Count,
-                       CurrentUnreachableRegionInitiator, CurrentSourceGroup,
-                       Flags);
-  }
-
-  void mapSourceCodeRange(const SourceMappingState &State,
-                          SourceLocation LocStart, SourceLocation LocEnd,
-                          unsigned Flags = 0) {
-    mapSourceCodeRange(LocStart, LocEnd, State.CurrentRegionCount,
-                       State.CurrentUnreachableRegionInitiator,
-                       State.CurrentSourceGroup, Flags);
-  }
-
   /// \brief Generate the coverage counter mapping regions from collected
   /// source regions.
   void emitSourceRegions() {
-    std::sort(SourceRegions.begin(), SourceRegions.end());
+    for (const auto &Region : SourceRegions) {
+      assert(Region.hasEndLoc() && "incomplete region");
 
-    for (auto I = SourceRegions.begin(), E = SourceRegions.end(); I != E; ++I) {
-      // Keep the original start location of this region.
-      SourceLocation LocStart = I->getStartLoc();
-      SourceLocation LocEnd = I->getEndLoc(SM);
+      SourceLocation LocStart = Region.getStartLoc();
+      assert(!SM.getFileID(LocStart).isInvalid() && "region in invalid file");
 
-      bool Ignore = I->hasFlag(SourceMappingRegion::IgnoreIfNotExtended);
-      // We need to handle mergeable regions together.
-      for (auto Next = I + 1; Next != E && Next->isMergeable(*I); ++Next) {
-        ++I;
-        LocStart = std::min(LocStart, I->getStartLoc());
-        LocEnd = std::max(LocEnd, I->getEndLoc(SM));
-        // FIXME: Should we && together the Ignore flag of multiple regions?
-        Ignore = false;
-      }
-      if (Ignore)
+      auto CovFileID = getCoverageFileID(LocStart);
+      // Ignore regions that don't have a file, such as builtin macros.
+      if (!CovFileID)
         continue;
 
+      SourceLocation LocEnd = getPreciseTokenLocEnd(Region.getEndLoc());
+      assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
+             "region spans multiple files");
+
       // Find the spilling locations for the mapping region.
-      LocEnd = getPreciseTokenLocEnd(LocEnd);
       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
 
-      auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
-      unsigned CovFileID;
-      if (getCoverageFileID(LocStart, I->getFile(), SpellingFile, CovFileID))
+      assert(LineStart <= LineEnd && "region start and end out of order");
+      MappingRegions.push_back(CounterMappingRegion::makeRegion(
+          Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
+          ColumnEnd));
+    }
+  }
+
+  /// \brief Generate expansion regions for each virtual file we've seen.
+  void emitExpansionRegions() {
+    for (const auto &FM : FileIDMapping) {
+      SourceLocation ExpandedLoc = FM.second.second;
+      SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
+      if (ParentLoc.isInvalid())
         continue;
 
-      assert(LineStart <= LineEnd);
-      MappingRegions.push_back(CounterMappingRegion(
-          I->getCounter(), CovFileID, LineStart, ColumnStart, LineEnd,
-          ColumnEnd, false, CounterMappingRegion::CodeRegion));
+      auto ParentFileID = getCoverageFileID(ParentLoc);
+      if (!ParentFileID)
+        continue;
+      auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
+      assert(ExpandedFileID && "expansion in uncovered file");
+
+      SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
+      assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
+             "region spans multiple files");
+
+      unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
+      unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
+      unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
+      unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
+
+      MappingRegions.push_back(CounterMappingRegion::makeExpansion(
+          *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
+          ColumnEnd));
     }
   }
 };
@@ -419,14 +315,14 @@
     if (!D->hasBody())
       return;
     auto Body = D->getBody();
-    mapSourceCodeRange(Body->getLocStart(), Body->getLocEnd(), Counter());
+    SourceRegions.emplace_back(Counter(), getStart(Body), getEnd(Body));
   }
 
   /// \brief Write the mapping data to the output stream
   void write(llvm::raw_ostream &OS) {
-    emitSourceRegions();
     SmallVector<unsigned, 16> FileIDMapping;
-    createFileIDMapping(FileIDMapping);
+    gatherFileIDs(FileIDMapping);
+    emitSourceRegions();
 
     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
     Writer.write(OS);
@@ -441,136 +337,212 @@
   /// \brief The map of statements to count values.
   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
 
-  Counter CurrentRegionCount;
+  /// \brief A stack of currently live regions.
+  std::vector<SourceMappingRegion> RegionStack;
 
   CounterExpressionBuilder Builder;
 
-  /// \brief Return a counter that represents the
-  /// expression that subracts rhs from lhs.
+  /// \brief A location in the most recently visited file or macro.
+  ///
+  /// This is used to adjust the active source regions appropriately when
+  /// expressions cross file or macro boundaries.
+  SourceLocation MostRecentLocation;
+
+  /// \brief Return a counter for the subtraction of \c RHS from \c LHS
   Counter subtractCounters(Counter LHS, Counter RHS) {
     return Builder.subtract(LHS, RHS);
   }
 
-  /// \brief Return a counter that represents the
-  /// the exression that adds lhs and rhs.
+  /// \brief Return a counter for the sum of \c LHS and \c RHS.
   Counter addCounters(Counter LHS, Counter RHS) {
     return Builder.add(LHS, RHS);
   }
 
+  Counter addCounters(Counter C1, Counter C2, Counter C3) {
+    return addCounters(addCounters(C1, C2), C3);
+  }
+
+  Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
+    return addCounters(addCounters(C1, C2, C3), C4);
+  }
+
   /// \brief Return the region counter for the given statement.
+  ///
   /// This should only be called on statements that have a dedicated counter.
-  unsigned getRegionCounter(const Stmt *S) { return CounterMap[S]; }
-
-  /// \brief Return the region count for the counter at the given index.
-  Counter getRegionCount(unsigned CounterId) {
-    return Counter::getCounter(CounterId);
+  Counter getRegionCounter(const Stmt *S) {
+    return Counter::getCounter(CounterMap[S]);
   }
 
-  /// \brief Return the counter value of the current region.
-  Counter getCurrentRegionCount() { return CurrentRegionCount; }
+  /// \brief Push a region onto the stack.
+  ///
+  /// Returns the index on the stack where the region was pushed. This can be
+  /// used with popRegions to exit a "scope", ending the region that was pushed.
+  size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
+                    Optional<SourceLocation> EndLoc = None) {
+    if (StartLoc)
+      MostRecentLocation = *StartLoc;
+    RegionStack.emplace_back(Count, StartLoc, EndLoc);
 
-  /// \brief Set the counter value for the current region.
-  /// This is used to keep track of changes to the most recent counter
-  /// from control flow and non-local exits.
-  void setCurrentRegionCount(Counter Count) {
-    CurrentRegionCount = Count;
-    CurrentUnreachableRegionInitiator = nullptr;
+    return RegionStack.size() - 1;
   }
 
-  /// \brief Indicate that the current region is never reached,
-  /// and thus should have a counter value of zero.
-  /// This is important so that subsequent regions can correctly track
-  /// their parent counts.
-  void setCurrentRegionUnreachable(const Stmt *Initiator) {
-    CurrentRegionCount = Counter::getZero();
-    CurrentUnreachableRegionInitiator = Initiator;
+  /// \brief Pop regions from the stack into the function's list of regions.
+  ///
+  /// Adds all regions from \c ParentIndex to the top of the stack to the
+  /// function's \c SourceRegions.
+  void popRegions(size_t ParentIndex) {
+    assert(RegionStack.size() >= ParentIndex && "parent not in stack");
+    while (RegionStack.size() > ParentIndex) {
+      SourceMappingRegion &Region = RegionStack.back();
+      if (Region.hasStartLoc()) {
+        SourceLocation StartLoc = Region.getStartLoc();
+        SourceLocation EndLoc = Region.hasEndLoc()
+                                    ? Region.getEndLoc()
+                                    : RegionStack[ParentIndex].getEndLoc();
+        while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
+          // The region ends in a nested file or macro expansion. Create a
+          // separate region for each expansion.
+          SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
+          assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
+
+          SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
+
+          EndLoc = getIncludeOrExpansionLoc(EndLoc);
+          assert(!EndLoc.isInvalid() &&
+                 "File exit was not handled before popRegions");
+        }
+        Region.setEndLoc(EndLoc);
+
+        MostRecentLocation = EndLoc;
+        // If this region happens to span an entire expansion, we need to make
+        // sure we don't overlap the parent region with it.
+        if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
+            EndLoc == getEndOfFileOrMacro(EndLoc))
+          MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
+
+        assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
+        SourceRegions.push_back(std::move(Region));
+      }
+      RegionStack.pop_back();
+    }
   }
 
-  /// \brief A counter for a particular region.
-  /// This is the primary interface through
-  /// which the coverage mapping builder manages counters and their values.
-  class RegionMapper {
-    CounterCoverageMappingBuilder &Mapping;
-    Counter Count;
-    Counter ParentCount;
-    Counter RegionCount;
-    Counter Adjust;
+  /// \brief Return the currently active region.
+  SourceMappingRegion &getRegion() {
+    assert(!RegionStack.empty() && "statement has no region");
+    return RegionStack.back();
+  }
 
-  public:
-    RegionMapper(CounterCoverageMappingBuilder *Mapper, const Stmt *S)
-        : Mapping(*Mapper),
-          Count(Mapper->getRegionCount(Mapper->getRegionCounter(S))),
-          ParentCount(Mapper->getCurrentRegionCount()) {}
+  /// \brief Propagate counts through the children of \c S.
+  Counter propagateCounts(Counter TopCount, const Stmt *S) {
+    size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
+    Visit(S);
+    Counter ExitCount = getRegion().getCounter();
+    popRegions(Index);
+    return ExitCount;
+  }
 
-    /// Get the value of the counter. In most cases this is the number of times
-    /// the region of the counter was entered, but for switch labels it's the
-    /// number of direct jumps to that label.
-    Counter getCount() const { return Count; }
+  /// \brief Adjust the most recently visited location to \c EndLoc.
+  ///
+  /// This should be used after visiting any statements in non-source order.
+  void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
+    MostRecentLocation = EndLoc;
+    if (MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
+      MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
+  }
 
-    /// Get the value of the counter with adjustments applied. Adjustments occur
-    /// when control enters or leaves the region abnormally; i.e., if there is a
-    /// jump to a label within the region, or if the function can return from
-    /// within the region. The adjusted count, then, is the value of the counter
-    /// at the end of the region.
-    Counter getAdjustedCount() const {
-      return Mapping.addCounters(Count, Adjust);
+  /// \brief Check whether \c Loc is included or expanded from \c Parent.
+  bool isNestedIn(SourceLocation Loc, FileID Parent) {
+    do {
+      Loc = getIncludeOrExpansionLoc(Loc);
+      if (Loc.isInvalid())
+        return false;
+    } while (!SM.isInFileID(Loc, Parent));
+    return true;
+  }
+
+  /// \brief Adjust regions and state when \c NewLoc exits a file.
+  ///
+  /// If moving from our most recently tracked location to \c NewLoc exits any
+  /// files, this adjusts our current region stack and creates the file regions
+  /// for the exited file.
+  void handleFileExit(SourceLocation NewLoc) {
+    if (SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
+      return;
+
+    // If NewLoc is not in a file that contains MostRecentLocation, walk up to
+    // find the common ancestor.
+    SourceLocation LCA = NewLoc;
+    FileID ParentFile = SM.getFileID(LCA);
+    while (!isNestedIn(MostRecentLocation, ParentFile)) {
+      LCA = getIncludeOrExpansionLoc(LCA);
+      if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
+        // Since there isn't a common ancestor, no file was exited. We just need
+        // to adjust our location to the new file.
+        MostRecentLocation = NewLoc;
+        return;
+      }
+      ParentFile = SM.getFileID(LCA);
     }
 
-    /// Get the value of the counter in this region's parent, i.e., the region
-    /// that was active when this region began. This is useful for deriving
-    /// counts in implicitly counted regions, like the false case of a condition
-    /// or the normal exits of a loop.
-    Counter getParentCount() const { return ParentCount; }
+    llvm::SmallSet<SourceLocation, 8> StartLocs;
+    Optional<Counter> ParentCounter;
+    for (auto I = RegionStack.rbegin(), E = RegionStack.rend(); I != E; ++I) {
+      if (!I->hasStartLoc())
+        continue;
+      SourceLocation Loc = I->getStartLoc();
+      if (!isNestedIn(Loc, ParentFile)) {
+        ParentCounter = I->getCounter();
+        break;
+      }
 
-    /// Activate the counter by emitting an increment and starting to track
-    /// adjustments. If AddIncomingFallThrough is true, the current region count
-    /// will be added to the counter for the purposes of tracking the region.
-    void beginRegion(bool AddIncomingFallThrough = false) {
-      RegionCount = Count;
-      if (AddIncomingFallThrough)
-        RegionCount =
-            Mapping.addCounters(RegionCount, Mapping.getCurrentRegionCount());
-      Mapping.setCurrentRegionCount(RegionCount);
+      while (!SM.isInFileID(Loc, ParentFile)) {
+        // The most nested region for each start location is the one with the
+        // correct count. We avoid creating redundant regions by stopping once
+        // we've seen this region.
+        if (StartLocs.insert(Loc).second)
+          SourceRegions.emplace_back(I->getCounter(), Loc,
+                                     getEndOfFileOrMacro(Loc));
+        Loc = getIncludeOrExpansionLoc(Loc);
+      }
+      I->setStartLoc(getPreciseTokenLocEnd(Loc));
     }
 
-    /// For counters on boolean branches, begins tracking adjustments for the
-    /// uncounted path.
-    void beginElseRegion() {
-      RegionCount = Mapping.subtractCounters(ParentCount, Count);
-      Mapping.setCurrentRegionCount(RegionCount);
+    if (ParentCounter) {
+      // If the file is contained completely by another region and doesn't
+      // immediately start its own region, the whole file gets a region
+      // corresponding to the parent.
+      SourceLocation Loc = MostRecentLocation;
+      while (isNestedIn(Loc, ParentFile)) {
+        SourceLocation FileStart = getStartOfFileOrMacro(Loc);
+        if (StartLocs.insert(FileStart).second)
+          SourceRegions.emplace_back(*ParentCounter, FileStart,
+                                     getEndOfFileOrMacro(Loc));
+        Loc = getIncludeOrExpansionLoc(Loc);
+      }
     }
 
-    /// Reset the current region count.
-    void setCurrentRegionCount(Counter CurrentCount) {
-      RegionCount = CurrentCount;
-      Mapping.setCurrentRegionCount(RegionCount);
-    }
+    MostRecentLocation = NewLoc;
+  }
 
-    /// Adjust for non-local control flow after emitting a subexpression or
-    /// substatement. This must be called to account for constructs such as
-    /// gotos,
-    /// labels, and returns, so that we can ensure that our region's count is
-    /// correct in the code that follows.
-    void adjustForControlFlow() {
-      Adjust = Mapping.addCounters(
-          Adjust, Mapping.subtractCounters(Mapping.getCurrentRegionCount(),
-                                           RegionCount));
-      // Reset the region count in case this is called again later.
-      RegionCount = Mapping.getCurrentRegionCount();
-    }
+  /// \brief Ensure that \c S is included in the current region.
+  void extendRegion(const Stmt *S) {
+    SourceMappingRegion &Region = getRegion();
+    SourceLocation StartLoc = getStart(S);
 
-    /// Commit all adjustments to the current region. If the region is a loop,
-    /// the LoopAdjust value should be the count of all the breaks and continues
-    /// from the loop, to compensate for those counts being deducted from the
-    /// adjustments for the body of the loop.
-    void applyAdjustmentsToRegion() {
-      Mapping.setCurrentRegionCount(Mapping.addCounters(ParentCount, Adjust));
-    }
-    void applyAdjustmentsToRegion(Counter LoopAdjust) {
-      Mapping.setCurrentRegionCount(Mapping.addCounters(
-          Mapping.addCounters(ParentCount, Adjust), LoopAdjust));
-    }
-  };
+    handleFileExit(StartLoc);
+    if (!Region.hasStartLoc())
+      Region.setStartLoc(StartLoc);
+  }
+
+  /// \brief Mark \c S as a terminator, starting a zero region.
+  void terminateRegion(const Stmt *S) {
+    extendRegion(S);
+    SourceMappingRegion &Region = getRegion();
+    if (!Region.hasEndLoc())
+      Region.setEndLoc(getEnd(S));
+    pushRegion(Counter::getZero());
+  }
 
   /// \brief Keep counts of breaks and continues inside loops.
   struct BreakContinue {
@@ -587,452 +559,301 @@
 
   /// \brief Write the mapping data to the output stream
   void write(llvm::raw_ostream &OS) {
-    emitSourceRegions();
     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
-    createFileIDMapping(VirtualFileMapping);
+    gatherFileIDs(VirtualFileMapping);
+    emitSourceRegions();
+    emitExpansionRegions();
     gatherSkippedRegions();
 
-    CoverageMappingWriter Writer(
-        VirtualFileMapping, Builder.getExpressions(), MappingRegions);
+    CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
+                                 MappingRegions);
     Writer.write(OS);
   }
 
-  /// \brief Return the current source mapping state.
-  SourceMappingState getCurrentState() const {
-    return SourceMappingState(CurrentRegionCount, CurrentSourceGroup,
-                              CurrentUnreachableRegionInitiator);
-  }
-
-  /// \brief Associate the source code range with the current region count.
-  void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
-                          unsigned Flags = 0) {
-    CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocEnd,
-                                               CurrentRegionCount, Flags);
-  }
-
-  void mapSourceCodeRange(SourceLocation LocStart) {
-    CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocStart,
-                                               CurrentRegionCount);
-  }
-
-  /// \brief Associate the source range of a token with the current region
-  /// count.
-  /// Ignore the source range for this token if it produces a distinct
-  /// mapping region with no other source ranges.
-  void mapToken(SourceLocation LocStart) {
-    CoverageMappingBuilder::mapSourceCodeRange(
-        LocStart, LocStart, CurrentRegionCount,
-        SourceMappingRegion::IgnoreIfNotExtended);
-  }
-
-  void mapToken(const SourceMappingState &State, SourceLocation LocStart) {
-    CoverageMappingBuilder::mapSourceCodeRange(
-        State, LocStart, LocStart, SourceMappingRegion::IgnoreIfNotExtended);
-  }
-
   void VisitStmt(const Stmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    if (!S->getLocStart().isInvalid())
+      extendRegion(S);
     for (Stmt::const_child_range I = S->children(); I; ++I) {
       if (*I)
         this->Visit(*I);
     }
+    handleFileExit(getEnd(S));
   }
 
   void VisitDecl(const Decl *D) {
-    if (!D->hasBody())
-      return;
-    // Counter tracks entry to the function body.
-    auto Body = D->getBody();
-    RegionMapper Cnt(this, Body);
-    Cnt.beginRegion();
-    Visit(Body);
-  }
-
-  void VisitDeclStmt(const DeclStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
-    for (Stmt::const_child_range I = static_cast<const Stmt *>(S)->children();
-         I; ++I) {
-      if (*I)
-        this->Visit(*I);
-    }
-  }
-
-  void VisitCompoundStmt(const CompoundStmt *S) {
-    SourceMappingState State = getCurrentState();
-    mapSourceCodeRange(S->getLBracLoc());
-    for (Stmt::const_child_range I = S->children(); I; ++I) {
-      if (*I)
-        this->Visit(*I);
-    }
-    CoverageMappingBuilder::mapSourceCodeRange(State, S->getRBracLoc(),
-                                               S->getRBracLoc());
+    Stmt *Body = D->getBody();
+    propagateCounts(getRegionCounter(Body), Body);
   }
 
   void VisitReturnStmt(const ReturnStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    extendRegion(S);
     if (S->getRetValue())
       Visit(S->getRetValue());
-    setCurrentRegionUnreachable(S);
+    terminateRegion(S);
   }
 
-  void VisitGotoStmt(const GotoStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
-    mapToken(S->getLabelLoc());
-    setCurrentRegionUnreachable(S);
-  }
+  void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
 
   void VisitLabelStmt(const LabelStmt *S) {
-    // Counter tracks the block following the label.
-    RegionMapper Cnt(this, S);
-    Cnt.beginRegion();
-    mapSourceCodeRange(S->getLocStart());
-    // Can't map the ':' token as its location isn't known.
+    SourceLocation Start = getStart(S);
+    // We can't extendRegion here or we risk overlapping with our new region.
+    handleFileExit(Start);
+    pushRegion(getRegionCounter(S), Start);
     Visit(S->getSubStmt());
   }
 
   void VisitBreakStmt(const BreakStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
     BreakContinueStack.back().BreakCount = addCounters(
-        BreakContinueStack.back().BreakCount, getCurrentRegionCount());
-    setCurrentRegionUnreachable(S);
+        BreakContinueStack.back().BreakCount, getRegion().getCounter());
+    terminateRegion(S);
   }
 
   void VisitContinueStmt(const ContinueStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
     BreakContinueStack.back().ContinueCount = addCounters(
-        BreakContinueStack.back().ContinueCount, getCurrentRegionCount());
-    setCurrentRegionUnreachable(S);
+        BreakContinueStack.back().ContinueCount, getRegion().getCounter());
+    terminateRegion(S);
   }
 
   void VisitWhileStmt(const WhileStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
-    // Counter tracks the body of the loop.
-    RegionMapper Cnt(this, S);
-    BreakContinueStack.push_back(BreakContinue());
-    // Visit the body region first so the break/continue adjustments can be
-    // included when visiting the condition.
-    Cnt.beginRegion();
-    Visit(S->getBody());
-    Cnt.adjustForControlFlow();
+    extendRegion(S);
 
-    // ...then go back and propagate counts through the condition. The count
-    // at the start of the condition is the sum of the incoming edges,
-    // the backedge from the end of the loop body, and the edges from
-    // continue statements.
+    Counter ParentCount = getRegion().getCounter();
+    Counter BodyCount = getRegionCounter(S);
+
+    // Handle the body first so that we can get the backedge count.
+    BreakContinueStack.push_back(BreakContinue());
+    extendRegion(S->getBody());
+    Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
     BreakContinue BC = BreakContinueStack.pop_back_val();
-    Cnt.setCurrentRegionCount(
-        addCounters(Cnt.getParentCount(),
-                    addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
-    beginSourceRegionGroup(S->getCond());
-    Visit(S->getCond());
-    endSourceRegionGroup();
-    Cnt.adjustForControlFlow();
-    Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
+
+    // Go back to handle the condition.
+    Counter CondCount =
+        addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
+    propagateCounts(CondCount, S->getCond());
+    adjustForOutOfOrderTraversal(getEnd(S));
+
+    Counter OutCount =
+        addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
+    if (OutCount != ParentCount)
+      pushRegion(OutCount);
   }
 
   void VisitDoStmt(const DoStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
-    // Counter tracks the body of the loop.
-    RegionMapper Cnt(this, S);
-    BreakContinueStack.push_back(BreakContinue());
-    Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
-    Visit(S->getBody());
-    Cnt.adjustForControlFlow();
+    extendRegion(S);
 
+    Counter ParentCount = getRegion().getCounter();
+    Counter BodyCount = getRegionCounter(S);
+
+    BreakContinueStack.push_back(BreakContinue());
+    extendRegion(S->getBody());
+    Counter BackedgeCount =
+        propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
     BreakContinue BC = BreakContinueStack.pop_back_val();
-    // The count at the start of the condition is equal to the count at the
-    // end of the body. The adjusted count does not include either the
-    // fall-through count coming into the loop or the continue count, so add
-    // both of those separately. This is coincidentally the same equation as
-    // with while loops but for different reasons.
-    Cnt.setCurrentRegionCount(
-        addCounters(Cnt.getParentCount(),
-                    addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
-    Visit(S->getCond());
-    Cnt.adjustForControlFlow();
-    Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
+
+    Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
+    propagateCounts(CondCount, S->getCond());
+
+    Counter OutCount =
+        addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
+    if (OutCount != ParentCount)
+      pushRegion(OutCount);
   }
 
   void VisitForStmt(const ForStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    extendRegion(S);
     if (S->getInit())
       Visit(S->getInit());
 
-    // Counter tracks the body of the loop.
-    RegionMapper Cnt(this, S);
+    Counter ParentCount = getRegion().getCounter();
+    Counter BodyCount = getRegionCounter(S);
+
+    // Handle the body first so that we can get the backedge count.
     BreakContinueStack.push_back(BreakContinue());
-    // Visit the body region first. (This is basically the same as a while
-    // loop; see further comments in VisitWhileStmt.)
-    Cnt.beginRegion();
-    Visit(S->getBody());
-    Cnt.adjustForControlFlow();
+    extendRegion(S->getBody());
+    Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
+    BreakContinue BC = BreakContinueStack.pop_back_val();
 
     // The increment is essentially part of the body but it needs to include
     // the count for all the continue statements.
-    if (S->getInc()) {
-      Cnt.setCurrentRegionCount(addCounters(
-          getCurrentRegionCount(), BreakContinueStack.back().ContinueCount));
-      beginSourceRegionGroup(S->getInc());
-      Visit(S->getInc());
-      endSourceRegionGroup();
-      Cnt.adjustForControlFlow();
+    if (const Stmt *Inc = S->getInc())
+      propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
+
+    // Go back to handle the condition.
+    Counter CondCount =
+        addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
+    if (const Expr *Cond = S->getCond()) {
+      propagateCounts(CondCount, Cond);
+      adjustForOutOfOrderTraversal(getEnd(S));
     }
 
-    BreakContinue BC = BreakContinueStack.pop_back_val();
-
-    // ...then go back and propagate counts through the condition.
-    if (S->getCond()) {
-      Cnt.setCurrentRegionCount(
-          addCounters(addCounters(Cnt.getParentCount(), Cnt.getAdjustedCount()),
-                      BC.ContinueCount));
-      beginSourceRegionGroup(S->getCond());
-      Visit(S->getCond());
-      endSourceRegionGroup();
-      Cnt.adjustForControlFlow();
-    }
-    Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
+    Counter OutCount =
+        addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
+    if (OutCount != ParentCount)
+      pushRegion(OutCount);
   }
 
   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    extendRegion(S);
+    Visit(S->getLoopVarStmt());
     Visit(S->getRangeStmt());
-    Visit(S->getBeginEndStmt());
-    // Counter tracks the body of the loop.
-    RegionMapper Cnt(this, S);
+
+    Counter ParentCount = getRegion().getCounter();
+    Counter BodyCount = getRegionCounter(S);
+
     BreakContinueStack.push_back(BreakContinue());
-    // Visit the body region first. (This is basically the same as a while
-    // loop; see further comments in VisitWhileStmt.)
-    Cnt.beginRegion();
-    Visit(S->getBody());
-    Cnt.adjustForControlFlow();
+    extendRegion(S->getBody());
+    Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
     BreakContinue BC = BreakContinueStack.pop_back_val();
-    Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
+
+    Counter OutCount = addCounters(ParentCount, BC.BreakCount, BC.ContinueCount,
+                                   subtractCounters(BodyCount, BackedgeCount));
+    if (OutCount != ParentCount)
+      pushRegion(OutCount);
   }
 
   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    extendRegion(S);
     Visit(S->getElement());
-    // Counter tracks the body of the loop.
-    RegionMapper Cnt(this, S);
+
+    Counter ParentCount = getRegion().getCounter();
+    Counter BodyCount = getRegionCounter(S);
+
     BreakContinueStack.push_back(BreakContinue());
-    Cnt.beginRegion();
-    Visit(S->getBody());
+    extendRegion(S->getBody());
+    Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
     BreakContinue BC = BreakContinueStack.pop_back_val();
-    Cnt.adjustForControlFlow();
-    Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
+
+    Counter OutCount = addCounters(ParentCount, BC.BreakCount, BC.ContinueCount,
+                                   subtractCounters(BodyCount, BackedgeCount));
+    if (OutCount != ParentCount)
+      pushRegion(OutCount);
   }
 
   void VisitSwitchStmt(const SwitchStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    extendRegion(S);
     Visit(S->getCond());
+
     BreakContinueStack.push_back(BreakContinue());
-    // Map the '}' for the body to have the same count as the regions after
-    // the switch.
-    SourceLocation RBracLoc;
-    if (const auto *CS = dyn_cast<CompoundStmt>(S->getBody())) {
-      mapSourceCodeRange(CS->getLBracLoc());
-      setCurrentRegionUnreachable(S);
-      for (Stmt::const_child_range I = CS->children(); I; ++I) {
-        if (*I)
-          this->Visit(*I);
+
+    const Stmt *Body = S->getBody();
+    extendRegion(Body);
+    if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
+      if (!CS->body_empty()) {
+        // The body of the switch needs a zero region so that fallthrough counts
+        // behave correctly, but it would be misleading to include the braces of
+        // the compound statement in the zeroed area, so we need to handle this
+        // specially.
+        size_t Index =
+            pushRegion(Counter::getZero(), getStart(CS->body_front()),
+                       getEnd(CS->body_back()));
+        for (const auto &Child : CS->children())
+          Visit(Child);
+        popRegions(Index);
       }
-      RBracLoc = CS->getRBracLoc();
-    } else {
-      setCurrentRegionUnreachable(S);
-      Visit(S->getBody());
-    }
-    // If the switch is inside a loop, add the continue counts.
+    } else
+      propagateCounts(Counter::getZero(), Body);
     BreakContinue BC = BreakContinueStack.pop_back_val();
+
     if (!BreakContinueStack.empty())
       BreakContinueStack.back().ContinueCount = addCounters(
           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
-    // Counter tracks the exit block of the switch.
-    RegionMapper ExitCnt(this, S);
-    ExitCnt.beginRegion();
-    if (RBracLoc.isValid())
-      mapSourceCodeRange(RBracLoc);
+
+    Counter ExitCount = getRegionCounter(S);
+    pushRegion(ExitCount);
   }
 
-  void VisitCaseStmt(const CaseStmt *S) {
-    // Counter for this particular case. This counts only jumps from the
-    // switch header and does not include fallthrough from the case before
-    // this one.
-    RegionMapper Cnt(this, S);
-    Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
-    mapSourceCodeRange(S->getLocStart());
-    mapToken(S->getColonLoc());
-    Visit(S->getSubStmt());
-  }
+  void VisitSwitchCase(const SwitchCase *S) {
+    extendRegion(S);
 
-  void VisitDefaultStmt(const DefaultStmt *S) {
-    // Counter for this default case. This does not include fallthrough from
-    // the previous case.
-    RegionMapper Cnt(this, S);
-    Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
-    mapSourceCodeRange(S->getLocStart());
-    mapToken(S->getColonLoc());
+    SourceMappingRegion &Parent = getRegion();
+
+    Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
+    // Reuse the existing region if it starts at our label. This is typical of
+    // the first case in a switch.
+    if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
+      Parent.setCounter(Count);
+    else
+      pushRegion(Count, getStart(S));
+
+    if (const CaseStmt *CS = dyn_cast<CaseStmt>(S)) {
+      Visit(CS->getLHS());
+      if (const Expr *RHS = CS->getRHS())
+        Visit(RHS);
+    }
     Visit(S->getSubStmt());
   }
 
   void VisitIfStmt(const IfStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
-    Visit(S->getCond());
-    mapToken(S->getElseLoc());
+    extendRegion(S);
 
-    // Counter tracks the "then" part of an if statement. The count for
-    // the "else" part, if it exists, will be calculated from this counter.
-    RegionMapper Cnt(this, S);
-    Cnt.beginRegion();
-    Visit(S->getThen());
-    Cnt.adjustForControlFlow();
+    Counter ParentCount = getRegion().getCounter();
+    Counter ThenCount = getRegionCounter(S);
 
-    if (S->getElse()) {
-      Cnt.beginElseRegion();
-      Visit(S->getElse());
-      Cnt.adjustForControlFlow();
-    }
-    Cnt.applyAdjustmentsToRegion();
+    // Emitting a counter for the condition makes it easier to interpret the
+    // counter for the body when looking at the coverage.
+    propagateCounts(ParentCount, S->getCond());
+
+    extendRegion(S->getThen());
+    Counter OutCount = propagateCounts(ThenCount, S->getThen());
+
+    Counter ElseCount = subtractCounters(ParentCount, ThenCount);
+    if (const Stmt *Else = S->getElse()) {
+      extendRegion(S->getElse());
+      OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
+    } else
+      OutCount = addCounters(OutCount, ElseCount);
+
+    if (OutCount != ParentCount)
+      pushRegion(OutCount);
   }
 
   void VisitCXXTryStmt(const CXXTryStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
+    extendRegion(S);
     Visit(S->getTryBlock());
     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
       Visit(S->getHandler(I));
-    // Counter tracks the continuation block of the try statement.
-    RegionMapper Cnt(this, S);
-    Cnt.beginRegion();
+
+    Counter ExitCount = getRegionCounter(S);
+    pushRegion(ExitCount);
   }
 
   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
-    mapSourceCodeRange(S->getLocStart());
-    // Counter tracks the catch statement's handler block.
-    RegionMapper Cnt(this, S);
-    Cnt.beginRegion();
-    Visit(S->getHandlerBlock());
+    extendRegion(S);
+    propagateCounts(getRegionCounter(S), S->getHandlerBlock());
   }
 
   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
-    Visit(E->getCond());
-    mapToken(E->getQuestionLoc());
-    auto State = getCurrentState();
+    extendRegion(E);
 
-    // Counter tracks the "true" part of a conditional operator. The
-    // count in the "false" part will be calculated from this counter.
-    RegionMapper Cnt(this, E);
-    Cnt.beginRegion();
-    Visit(E->getTrueExpr());
-    Cnt.adjustForControlFlow();
+    Counter ParentCount = getRegion().getCounter();
+    Counter TrueCount = getRegionCounter(E);
 
-    mapToken(State, E->getColonLoc());
-
-    Cnt.beginElseRegion();
-    Visit(E->getFalseExpr());
-    Cnt.adjustForControlFlow();
-
-    Cnt.applyAdjustmentsToRegion();
+    propagateCounts(TrueCount, E->getTrueExpr());
+    propagateCounts(subtractCounters(ParentCount, TrueCount),
+                    E->getFalseExpr());
   }
 
   void VisitBinLAnd(const BinaryOperator *E) {
+    extendRegion(E);
     Visit(E->getLHS());
-    mapToken(E->getOperatorLoc());
-    // Counter tracks the right hand side of a logical and operator.
-    RegionMapper Cnt(this, E);
-    Cnt.beginRegion();
-    Visit(E->getRHS());
-    Cnt.adjustForControlFlow();
-    Cnt.applyAdjustmentsToRegion();
+
+    extendRegion(E->getRHS());
+    propagateCounts(getRegionCounter(E), E->getRHS());
   }
 
   void VisitBinLOr(const BinaryOperator *E) {
+    extendRegion(E);
     Visit(E->getLHS());
-    mapToken(E->getOperatorLoc());
-    // Counter tracks the right hand side of a logical or operator.
-    RegionMapper Cnt(this, E);
-    Cnt.beginRegion();
-    Visit(E->getRHS());
-    Cnt.adjustForControlFlow();
-    Cnt.applyAdjustmentsToRegion();
+
+    extendRegion(E->getRHS());
+    propagateCounts(getRegionCounter(E), E->getRHS());
   }
 
-  void VisitParenExpr(const ParenExpr *E) {
-    mapToken(E->getLParen());
-    Visit(E->getSubExpr());
-    mapToken(E->getRParen());
-  }
-
-  void VisitBinaryOperator(const BinaryOperator *E) {
-    Visit(E->getLHS());
-    mapToken(E->getOperatorLoc());
-    Visit(E->getRHS());
-  }
-
-  void VisitUnaryOperator(const UnaryOperator *E) {
-    bool Postfix = E->isPostfix();
-    if (!Postfix)
-      mapToken(E->getOperatorLoc());
-    Visit(E->getSubExpr());
-    if (Postfix)
-      mapToken(E->getOperatorLoc());
-  }
-
-  void VisitMemberExpr(const MemberExpr *E) {
-    Visit(E->getBase());
-    mapToken(E->getMemberLoc());
-  }
-
-  void VisitCallExpr(const CallExpr *E) {
-    Visit(E->getCallee());
-    for (const auto &Arg : E->arguments())
-      Visit(Arg);
-    mapToken(E->getRParenLoc());
-  }
-
-  void VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
-    Visit(E->getLHS());
-    Visit(E->getRHS());
-    mapToken(E->getRBracketLoc());
-  }
-
-  void VisitCStyleCastExpr(const CStyleCastExpr *E) {
-    mapToken(E->getLParenLoc());
-    mapToken(E->getRParenLoc());
-    Visit(E->getSubExpr());
-  }
-
-  // Map literals as tokens so that the macros like #define PI 3.14
-  // won't generate coverage mapping regions.
-
-  void VisitIntegerLiteral(const IntegerLiteral *E) {
-    mapToken(E->getLocStart());
-  }
-
-  void VisitFloatingLiteral(const FloatingLiteral *E) {
-    mapToken(E->getLocStart());
-  }
-
-  void VisitCharacterLiteral(const CharacterLiteral *E) {
-    mapToken(E->getLocStart());
-  }
-
-  void VisitStringLiteral(const StringLiteral *E) {
-    mapToken(E->getLocStart());
-  }
-
-  void VisitImaginaryLiteral(const ImaginaryLiteral *E) {
-    mapToken(E->getLocStart());
-  }
-
-  void VisitObjCMessageExpr(const ObjCMessageExpr *E) {
-    mapToken(E->getLeftLoc());
-    for (Stmt::const_child_range I = static_cast<const Stmt*>(E)->children(); I;
-         ++I) {
-      if (*I)
-        this->Visit(*I);
-    }
-    mapToken(E->getRightLoc());
+  void VisitLambdaExpr(const LambdaExpr *LE) {
+    // Lambdas are treated as their own functions for now, so we shouldn't
+    // propagate counts into them.
   }
 };
 }
@@ -1045,10 +866,12 @@
   return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
 }
 
-static void dump(llvm::raw_ostream &OS, const CoverageMappingRecord &Function) {
-  OS << Function.FunctionName << ":\n";
-  CounterMappingContext Ctx(Function.Expressions);
-  for (const auto &R : Function.MappingRegions) {
+static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
+                 ArrayRef<CounterExpression> Expressions,
+                 ArrayRef<CounterMappingRegion> Regions) {
+  OS << FunctionName << ":\n";
+  CounterMappingContext Ctx(Expressions);
+  for (const auto &R : Regions) {
     OS.indent(2);
     switch (R.Kind) {
     case CounterMappingRegion::CodeRegion:
@@ -1061,15 +884,12 @@
       break;
     }
 
-    OS << "File " << R.FileID << ", " << R.LineStart << ":"
-           << R.ColumnStart << " -> " << R.LineEnd << ":" << R.ColumnEnd
-           << " = ";
-    Ctx.dump(R.Count);
-    OS << " (HasCodeBefore = " << R.HasCodeBefore;
+    OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
+       << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
+    Ctx.dump(R.Count, OS);
     if (R.Kind == CounterMappingRegion::ExpansionRegion)
-      OS << ", Expanded file = " << R.ExpandedFileID;
-
-    OS << ")\n";
+      OS << " (Expanded file = " << R.ExpandedFileID << ")";
+    OS << "\n";
   }
 }
 
@@ -1108,13 +928,11 @@
     FilenameRefs.resize(FileEntries.size());
     for (const auto &Entry : FileEntries)
       FilenameRefs[Entry.second] = Entry.first->getName();
-    RawCoverageMappingReader Reader(FunctionNameValue, CoverageMapping,
-                                    FilenameRefs,
-                                    Filenames, Expressions, Regions);
-    CoverageMappingRecord FunctionRecord;
-    if (Reader.read(FunctionRecord))
+    RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
+                                    Expressions, Regions);
+    if (Reader.read())
       return;
-    dump(llvm::outs(), FunctionRecord);
+    dump(llvm::outs(), FunctionNameValue, Expressions, Regions);
   }
 }
 
diff --git a/lib/CodeGen/CoverageMappingGen.h b/lib/CodeGen/CoverageMappingGen.h
index e4c6412..0d1bf6d 100644
--- a/lib/CodeGen/CoverageMappingGen.h
+++ b/lib/CodeGen/CoverageMappingGen.h
@@ -16,10 +16,10 @@
 
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
-#include "clang/Lex/PPCallbacks.h"
 #include "clang/Frontend/CodeGenOptions.h"
-#include "llvm/ADT/StringMap.h"
+#include "clang/Lex/PPCallbacks.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/Support/raw_ostream.h"
 
diff --git a/lib/CodeGen/EHScopeStack.h b/lib/CodeGen/EHScopeStack.h
index e695848..6535b76 100644
--- a/lib/CodeGen/EHScopeStack.h
+++ b/lib/CodeGen/EHScopeStack.h
@@ -75,8 +75,14 @@
 template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
 
 enum CleanupKind : unsigned {
+  /// Denotes a cleanup that should run when a scope is exited using exceptional
+  /// control flow (a throw statement leading to stack unwinding, ).
   EHCleanup = 0x1,
+
+  /// Denotes a cleanup that should run when a scope is exited using normal
+  /// control flow (falling off the end of the scope, return, goto, ...).
   NormalCleanup = 0x2,
+
   NormalAndEHCleanup = EHCleanup | NormalCleanup,
 
   InactiveCleanup = 0x4,
@@ -306,53 +312,10 @@
                    InnermostEHScope(stable_end()) {}
   ~EHScopeStack() { delete[] StartOfBuffer; }
 
-  // Variadic templates would make this not terrible.
-
   /// Push a lazily-created cleanup on the stack.
-  template <class T>
-  void pushCleanup(CleanupKind Kind) {
+  template <class T, class... As> void pushCleanup(CleanupKind Kind, As... A) {
     void *Buffer = pushCleanup(Kind, sizeof(T));
-    Cleanup *Obj = new(Buffer) T();
-    (void) Obj;
-  }
-
-  /// Push a lazily-created cleanup on the stack.
-  template <class T, class A0>
-  void pushCleanup(CleanupKind Kind, A0 a0) {
-    void *Buffer = pushCleanup(Kind, sizeof(T));
-    Cleanup *Obj = new(Buffer) T(a0);
-    (void) Obj;
-  }
-
-  /// Push a lazily-created cleanup on the stack.
-  template <class T, class A0, class A1>
-  void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
-    void *Buffer = pushCleanup(Kind, sizeof(T));
-    Cleanup *Obj = new(Buffer) T(a0, a1);
-    (void) Obj;
-  }
-
-  /// 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) {
-    void *Buffer = pushCleanup(Kind, sizeof(T));
-    Cleanup *Obj = new(Buffer) T(a0, a1, a2);
-    (void) Obj;
-  }
-
-  /// 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) {
-    void *Buffer = pushCleanup(Kind, sizeof(T));
-    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
-    (void) Obj;
-  }
-
-  /// 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) {
-    void *Buffer = pushCleanup(Kind, sizeof(T));
-    Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
+    Cleanup *Obj = new (Buffer) T(A...);
     (void) Obj;
   }
 
@@ -369,10 +332,10 @@
   ///
   /// The pointer returned from this method is valid until the cleanup
   /// 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) {
+  template <class T, class... As>
+  T *pushCleanupWithExtra(CleanupKind Kind, size_t N, As... A) {
     void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
-    return new (Buffer) T(N, a0, a1, a2);
+    return new (Buffer) T(N, A...);
   }
 
   void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
diff --git a/lib/CodeGen/ItaniumCXXABI.cpp b/lib/CodeGen/ItaniumCXXABI.cpp
index a65c5ef..e580969 100644
--- a/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/lib/CodeGen/ItaniumCXXABI.cpp
@@ -110,6 +110,8 @@
                                llvm::Value *Ptr, QualType ElementType,
                                const CXXDestructorDecl *Dtor) override;
 
+  void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
+
   void EmitFundamentalRTTIDescriptor(QualType Type);
   void EmitFundamentalRTTIDescriptors();
   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
@@ -337,6 +339,9 @@
     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
                              /* UseARMGuardVarABI = */ true);
 
+  case TargetCXXABI::GenericMIPS:
+    return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true);
+
   case TargetCXXABI::GenericItanium:
     if (CGM.getContext().getTargetInfo().getTriple().getArch()
         == llvm::Triple::le32) {
@@ -358,7 +363,7 @@
 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
   if (MPT->isMemberDataPointer())
     return CGM.PtrDiffTy;
-  return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
+  return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, nullptr);
 }
 
 /// In the Itanium and ARM ABIs, method pointers have the form:
@@ -887,6 +892,20 @@
     CGF.PopCleanupBlock();
 }
 
+void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
+  // void __cxa_rethrow();
+
+  llvm::FunctionType *FTy =
+    llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
+
+  llvm::Constant *Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
+
+  if (isNoReturn)
+    CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
+  else
+    CGF.EmitRuntimeCallOrInvoke(Fn);
+}
+
 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
   // void *__dynamic_cast(const void *sub,
   //                      const abi::__class_type_info *src,
@@ -1106,7 +1125,7 @@
   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
 
   // The constructor used for constructing this as a complete class;
-  // constucts the virtual bases, then calls the base constructor.
+  // constructs the virtual bases, then calls the base constructor.
   if (!D->getParent()->isAbstract()) {
     // We don't need to emit the complete ctor if the class is abstract.
     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
@@ -1240,6 +1259,9 @@
   // Set the correct linkage.
   VTable->setLinkage(Linkage);
 
+  if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
+    VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
+
   // Set the right visibility.
   CGM.setGlobalVisibility(VTable, RD);
 
@@ -1259,6 +1281,8 @@
       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
       DC->getParent()->isTranslationUnit())
     EmitFundamentalRTTIDescriptors();
+
+  CGM.EmitVTableBitSetEntries(VTable, VTLayout);
 }
 
 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
@@ -1350,6 +1374,8 @@
   Ty = Ty->getPointerTo()->getPointerTo();
   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
 
+  CGF.EmitVTablePtrCheckForCall(cast<CXXMethodDecl>(GD.getDecl()), VTable);
+
   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
   llvm::Value *VFuncPtr =
       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
@@ -1695,11 +1721,12 @@
 
     // The ABI says: It is suggested that it be emitted in the same COMDAT group
     // as the associated data object
-    if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) {
-      llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName());
+    llvm::Comdat *C = var->getComdat();
+    if (!D.isLocalVarDecl() && C) {
       guard->setComdat(C);
-      var->setComdat(C);
       CGF.CurFn->setComdat(C);
+    } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
+      guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
     }
 
     CGM.setStaticLocalDeclGuardAddress(&D, guard);
@@ -2699,9 +2726,13 @@
 
   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
 
+  llvm::Module &M = CGM.getModule();
   llvm::GlobalVariable *GV =
-    new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
-                             /*Constant=*/true, Linkage, Init, Name);
+      new llvm::GlobalVariable(M, Init->getType(),
+                               /*Constant=*/true, Linkage, Init, Name);
+
+  if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
+    GV->setComdat(M.getOrInsertComdat(GV->getName()));
 
   // If there's already an old global variable, replace it with the new one.
   if (OldGV) {
@@ -3185,5 +3216,7 @@
       getMangleContext().mangleCXXCtorComdat(CD, Out);
     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
     Fn->setComdat(C);
+  } else {
+    CGM.maybeSetTrivialComdat(*MD, *Fn);
   }
 }
diff --git a/lib/CodeGen/MicrosoftCXXABI.cpp b/lib/CodeGen/MicrosoftCXXABI.cpp
index 659ed0a..48adf3a 100644
--- a/lib/CodeGen/MicrosoftCXXABI.cpp
+++ b/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -70,6 +70,8 @@
                                llvm::Value *Ptr, QualType ElementType,
                                const CXXDestructorDecl *Dtor) override;
 
+  void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
+
   llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
                                                    const VPtrInfo *Info);
 
@@ -665,6 +667,30 @@
     CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
 }
 
+static llvm::Function *getRethrowFn(CodeGenModule &CGM) {
+  // _CxxThrowException takes two pointer width arguments: a value and a context
+  // object which points to a TypeInfo object.
+  llvm::Type *ArgTypes[] = {CGM.Int8PtrTy, CGM.Int8PtrTy};
+  llvm::FunctionType *FTy =
+      llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
+  auto *Fn = cast<llvm::Function>(
+      CGM.CreateRuntimeFunction(FTy, "_CxxThrowException"));
+  // _CxxThrowException is stdcall on 32-bit x86 platforms.
+  if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86)
+    Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
+  return Fn;
+}
+
+void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
+  llvm::Value *Args[] = {llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
+                         llvm::ConstantPointerNull::get(CGM.Int8PtrTy)};
+  auto *Fn = getRethrowFn(CGM);
+  if (isNoReturn)
+    CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
+  else
+    CGF.EmitRuntimeCallOrInvoke(Fn, Args);
+}
+
 /// \brief Gets the offset to the virtual base that contains the vfptr for
 /// MS-ABI polymorphic types.
 static llvm::Value *getPolymorphicOffset(CodeGenFunction &CGF,
@@ -1394,6 +1420,10 @@
         } else {
           llvm_unreachable("unexpected linkage for vftable!");
         }
+      } else {
+        if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage))
+          VTable->setComdat(
+              CGM.getModule().getOrInsertComdat(VTable->getName()));
       }
       VFTable->setLinkage(VFTableLinkage);
       CGM.setGlobalVisibility(VFTable, RD);
@@ -1439,9 +1469,9 @@
   llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
 
   ASTContext &Context = CGF.getContext();
-  llvm::Value *ImplicitParam =
-      llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
-                             DtorType == Dtor_Deleting);
+  llvm::Value *ImplicitParam = llvm::ConstantInt::get(
+      llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
+      DtorType == Dtor_Deleting);
 
   This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
   RValue RV = CGF.EmitCXXStructorCall(Dtor, Callee, ReturnValueSlot(), This,
@@ -1504,10 +1534,18 @@
   ThunkFn->setLinkage(MD->isExternallyVisible()
                           ? llvm::GlobalValue::LinkOnceODRLinkage
                           : llvm::GlobalValue::InternalLinkage);
+  if (MD->isExternallyVisible())
+    ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
 
   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
 
+  // Add the "thunk" attribute so that LLVM knows that the return type is
+  // meaningless. These thunks can be used to call functions with differing
+  // return types, and the caller is required to cast the prototype
+  // appropriately to extract the correct value.
+  ThunkFn->addFnAttr("thunk");
+
   // These thunks can be compared, so they are not unnamed.
   ThunkFn->setUnnamedAddr(false);
 
@@ -1544,7 +1582,8 @@
   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
     const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
-    emitVBTableDefinition(*VBT, RD, GV);
+    if (GV->isDeclaration())
+      emitVBTableDefinition(*VBT, RD, GV);
   }
 }
 
@@ -1571,6 +1610,9 @@
   else if (RD->hasAttr<DLLExportAttr>())
     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
 
+  if (!GV->hasExternalLinkage())
+    emitVBTableDefinition(VBT, RD, GV);
+
   return GV;
 }
 
@@ -1803,18 +1845,10 @@
     llvm::Function *F = CXXThreadLocalInits[I];
 
     // If the GV is already in a comdat group, then we have to join it.
-    llvm::Comdat *C = GV->getComdat();
-
-    // LinkOnce and Weak linkage are lowered down to a single-member comdat
-    // group.
-    // Make an explicit group so we can join it.
-    if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) {
-      C = CGM.getModule().getOrInsertComdat(GV->getName());
-      GV->setComdat(C);
+    if (llvm::Comdat *C = GV->getComdat())
       AddToXDU(F)->setComdat(C);
-    } else {
+    else
       NonComdatInits.push_back(F);
-    }
   }
 
   if (!NonComdatInits.empty()) {
@@ -1843,7 +1877,9 @@
   if (!D.isStaticLocal()) {
     assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
     // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
-    CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
+    llvm::Function *F = CGF.CurFn;
+    F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
+    F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
     return;
   }
@@ -1899,6 +1935,9 @@
                                  GV->getLinkage(), Zero, GuardName.str());
     GI->Guard->setVisibility(GV->getVisibility());
     GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
+    if (GI->Guard->isWeakForLinker())
+      GI->Guard->setComdat(
+          CGM.getModule().getOrInsertComdat(GI->Guard->getName()));
   } else {
     assert(GI->Guard->getLinkage() == GV->getLinkage() &&
            "static local from the same function had different linkage");
@@ -2836,6 +2875,8 @@
   auto CHD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
                                       /*Initializer=*/nullptr,
                                       MangledName.c_str());
+  if (CHD->isWeakForLinker())
+    CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
 
   // Initialize the base class ClassHierarchyDescriptor.
   llvm::Constant *Fields[] = {
@@ -2869,6 +2910,8 @@
   auto *BCA = new llvm::GlobalVariable(
       Module, ArrType,
       /*Constant=*/true, Linkage, /*Initializer=*/nullptr, MangledName.c_str());
+  if (BCA->isWeakForLinker())
+    BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
 
   // Initialize the BaseClassArray.
   SmallVector<llvm::Constant *, 8> BaseClassArrayData;
@@ -2909,6 +2952,8 @@
   auto BCD = new llvm::GlobalVariable(Module, Type, /*Constant=*/true, Linkage,
                                       /*Initializer=*/nullptr,
                                       MangledName.c_str());
+  if (BCD->isWeakForLinker())
+    BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
 
   // Initialize the BaseClassDescriptor.
   llvm::Constant *Fields[] = {
@@ -2968,6 +3013,8 @@
   if (!ABI.isImageRelative())
     FieldsRef = FieldsRef.drop_back();
   COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
+  if (COL->isWeakForLinker())
+    COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
   return COL;
 }
 
@@ -2999,13 +3046,14 @@
     llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
   llvm::StructType *TypeDescriptorType =
       getTypeDescriptorType(TypeInfoString);
-  return llvm::ConstantExpr::getBitCast(
-      new llvm::GlobalVariable(
-          CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
-          getLinkageForRTTI(Type),
-          llvm::ConstantStruct::get(TypeDescriptorType, Fields),
-          MangledName.c_str()),
-      CGM.Int8PtrTy);
+  auto *Var = new llvm::GlobalVariable(
+      CGM.getModule(), TypeDescriptorType, /*Constant=*/false,
+      getLinkageForRTTI(Type),
+      llvm::ConstantStruct::get(TypeDescriptorType, Fields),
+      MangledName.c_str());
+  if (Var->isWeakForLinker())
+    Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
+  return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
 }
 
 /// \brief Gets or a creates a Microsoft CompleteObjectLocator.
@@ -3019,7 +3067,8 @@
                                const CXXConstructorDecl *ctor,
                                StructorType ctorType) {
   // There are no constructor variants, always emit the complete destructor.
-  CGM.codegenCXXStructor(ctor, StructorType::Complete);
+  llvm::Function *Fn = CGM.codegenCXXStructor(ctor, StructorType::Complete);
+  CGM.maybeSetTrivialComdat(*ctor, *Fn);
 }
 
 static void emitCXXDestructor(CodeGenModule &CGM, const CXXDestructorDecl *dtor,
@@ -3045,7 +3094,9 @@
   if (dtorType == StructorType::Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
     return;
 
-  CGM.codegenCXXStructor(dtor, dtorType);
+  llvm::Function *Fn = CGM.codegenCXXStructor(dtor, dtorType);
+  if (Fn->isWeakForLinker())
+    Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
 }
 
 void MicrosoftCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
diff --git a/lib/CodeGen/ModuleBuilder.cpp b/lib/CodeGen/ModuleBuilder.cpp
index ee6f6f9..03771e1 100644
--- a/lib/CodeGen/ModuleBuilder.cpp
+++ b/lib/CodeGen/ModuleBuilder.cpp
@@ -52,15 +52,22 @@
     std::unique_ptr<llvm::Module> M;
     std::unique_ptr<CodeGen::CodeGenModule> Builder;
 
+  private:
+    SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
+
   public:
     CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
                       const CodeGenOptions &CGO, llvm::LLVMContext& C,
                       CoverageSourceInfo *CoverageInfo = nullptr)
-      : Diags(diags), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
+      : Diags(diags), Ctx(nullptr), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
         CoverageInfo(CoverageInfo),
         M(new llvm::Module(ModuleName, C)) {}
 
-    virtual ~CodeGeneratorImpl() {}
+    virtual ~CodeGeneratorImpl() {
+      // There should normally not be any leftover inline method definitions.
+      assert(DeferredInlineMethodDefinitions.empty() ||
+             Diags.hasErrorOccurred());
+    }
 
     llvm::Module* GetModule() override {
       return M.get();
@@ -88,7 +95,8 @@
 
       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
       M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
-      TD.reset(new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
+      TD.reset(
+          new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
       Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
                                                Diags, CoverageInfo));
 
@@ -204,11 +212,11 @@
       Builder->EmitTentativeDefinition(D);
     }
 
-    void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
+    void HandleVTable(CXXRecordDecl *RD) override {
       if (Diags.hasErrorOccurred())
         return;
 
-      Builder->EmitVTable(RD, DefinitionRequired);
+      Builder->EmitVTable(RD);
     }
 
     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
@@ -223,9 +231,6 @@
     void HandleDependentLibrary(llvm::StringRef Lib) override {
       Builder->AddDependentLib(Lib);
     }
-
-  private:
-    std::vector<CXXMethodDecl *> DeferredInlineMethodDefinitions;
   };
 }
 
@@ -234,7 +239,6 @@
 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
                                         const std::string& ModuleName,
                                         const CodeGenOptions &CGO,
-                                        const TargetOptions &/*TO*/,
                                         llvm::LLVMContext& C,
                                         CoverageSourceInfo *CoverageInfo) {
   return new CodeGeneratorImpl(Diags, ModuleName, CGO, C, CoverageInfo);
diff --git a/lib/CodeGen/SanitizerMetadata.cpp b/lib/CodeGen/SanitizerMetadata.cpp
index 70bc058..7c38b28 100644
--- a/lib/CodeGen/SanitizerMetadata.cpp
+++ b/lib/CodeGen/SanitizerMetadata.cpp
@@ -30,8 +30,8 @@
   IsDynInit &= !CGM.isInSanitizerBlacklist(GV, Loc, Ty, "init");
   IsBlacklisted |= CGM.isInSanitizerBlacklist(GV, Loc, Ty);
 
-  llvm::Value *LocDescr = nullptr;
-  llvm::Value *GlobalName = nullptr;
+  llvm::Metadata *LocDescr = nullptr;
+  llvm::Metadata *GlobalName = nullptr;
   llvm::LLVMContext &VMContext = CGM.getLLVMContext();
   if (!IsBlacklisted) {
     // Don't generate source location and global name if it is blacklisted -
@@ -41,10 +41,12 @@
       GlobalName = llvm::MDString::get(VMContext, Name);
   }
 
-  llvm::Value *GlobalMetadata[] = {
-      GV, LocDescr, GlobalName,
-      llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsDynInit),
-      llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsBlacklisted)};
+  llvm::Metadata *GlobalMetadata[] = {
+      llvm::ConstantAsMetadata::get(GV), LocDescr, GlobalName,
+      llvm::ConstantAsMetadata::get(
+          llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsDynInit)),
+      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+          llvm::Type::getInt1Ty(VMContext), IsBlacklisted))};
 
   llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalMetadata);
   llvm::NamedMDNode *AsanGlobals =
@@ -70,9 +72,8 @@
 }
 
 void SanitizerMetadata::disableSanitizerForInstruction(llvm::Instruction *I) {
-  I->setMetadata(
-      CGM.getModule().getMDKindID("nosanitize"),
-      llvm::MDNode::get(CGM.getLLVMContext(), ArrayRef<llvm::Value *>()));
+  I->setMetadata(CGM.getModule().getMDKindID("nosanitize"),
+                 llvm::MDNode::get(CGM.getLLVMContext(), None));
 }
 
 llvm::MDNode *SanitizerMetadata::getLocationMetadata(SourceLocation Loc) {
@@ -80,11 +81,12 @@
   if (!PLoc.isValid())
     return nullptr;
   llvm::LLVMContext &VMContext = CGM.getLLVMContext();
-  llvm::Value *LocMetadata[] = {
+  llvm::Metadata *LocMetadata[] = {
       llvm::MDString::get(VMContext, PLoc.getFilename()),
-      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), PLoc.getLine()),
-      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
-                             PLoc.getColumn()),
+      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+          llvm::Type::getInt32Ty(VMContext), PLoc.getLine())),
+      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
+          llvm::Type::getInt32Ty(VMContext), PLoc.getColumn())),
   };
   return llvm::MDNode::get(VMContext, LocMetadata);
 }
diff --git a/lib/CodeGen/SanitizerMetadata.h b/lib/CodeGen/SanitizerMetadata.h
index f3c700a..166f0e6 100644
--- a/lib/CodeGen/SanitizerMetadata.h
+++ b/lib/CodeGen/SanitizerMetadata.h
@@ -13,9 +13,9 @@
 #ifndef LLVM_CLANG_LIB_CODEGEN_SANITIZERMETADATA_H
 #define LLVM_CLANG_LIB_CODEGEN_SANITIZERMETADATA_H
 
+#include "clang/AST/Type.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
-#include "clang/AST/Type.h"
 
 namespace llvm {
 class GlobalVariable;
@@ -31,8 +31,8 @@
 class CodeGenModule;
 
 class SanitizerMetadata {
-  SanitizerMetadata(const SanitizerMetadata &) LLVM_DELETED_FUNCTION;
-  void operator=(const SanitizerMetadata &) LLVM_DELETED_FUNCTION;
+  SanitizerMetadata(const SanitizerMetadata &) = delete;
+  void operator=(const SanitizerMetadata &) = delete;
 
   CodeGenModule &CGM;
 public:
diff --git a/lib/CodeGen/TargetInfo.cpp b/lib/CodeGen/TargetInfo.cpp
index 2604720..36f9914 100644
--- a/lib/CodeGen/TargetInfo.cpp
+++ b/lib/CodeGen/TargetInfo.cpp
@@ -20,11 +20,11 @@
 #include "clang/AST/RecordLayout.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/Frontend/CodeGenOptions.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/Type.h"
 #include "llvm/Support/raw_ostream.h"
-
 #include <algorithm>    // std::sort
 
 using namespace clang;
@@ -665,6 +665,9 @@
     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
   }
 
+  bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
+    return true;
+  }
 };
 
 }
@@ -1145,6 +1148,10 @@
     }
   }
 
+  // The chain argument effectively gives us another free register.
+  if (FI.isChainCall())
+    ++State.FreeRegs;
+
   bool UsedInAlloca = false;
   for (auto &I : FI.arguments()) {
     I.info = classifyArgumentType(I.type, State);
@@ -1301,17 +1308,8 @@
   case llvm::Triple::FreeBSD:
   case llvm::Triple::OpenBSD:
   case llvm::Triple::Bitrig:
-    return true;
   case llvm::Triple::Win32:
-    switch (Triple.getEnvironment()) {
-    case llvm::Triple::UnknownEnvironment:
-    case llvm::Triple::Cygnus:
-    case llvm::Triple::GNU:
-    case llvm::Triple::MSVC:
-      return true;
-    default:
-      return false;
-    }
+    return true;
   default:
     return false;
   }
@@ -1509,6 +1507,10 @@
 
   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                          CodeGenFunction &CGF) const override;
+
+  bool has64BitPointers() const {
+    return Has64BitPointers;
+  }
 };
 
 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
@@ -1594,24 +1596,51 @@
 
   llvm::Constant *
   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
-    unsigned Sig = (0xeb << 0) |  // jmp rel8
-                   (0x0a << 8) |  //           .+0x0c
-                   ('F' << 16) |
-                   ('T' << 24);
+    unsigned Sig;
+    if (getABIInfo().has64BitPointers())
+      Sig = (0xeb << 0) |  // jmp rel8
+            (0x0a << 8) |  //           .+0x0c
+            ('F' << 16) |
+            ('T' << 24);
+    else
+      Sig = (0xeb << 0) |  // jmp rel8
+            (0x06 << 8) |  //           .+0x08
+            ('F' << 16) |
+            ('T' << 24);
     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
   }
 
   unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
     return HasAVX ? 32 : 16;
   }
+
+  bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
+    return true;
+  }
+};
+
+class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
+public:
+  PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
+    : X86_64TargetCodeGenInfo(CGT, HasAVX) {}
+
+  void getDependentLibraryOption(llvm::StringRef Lib,
+                                 llvm::SmallString<24> &Opt) const {
+    Opt = "\01";
+    Opt += Lib;
+  }
 };
 
 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
-  // If the argument does not end in .lib, automatically add the suffix. This
-  // matches the behavior of MSVC.
-  std::string ArgStr = Lib;
+  // If the argument does not end in .lib, automatically add the suffix.
+  // If the argument contains a space, enclose it in quotes.
+  // This matches the behavior of MSVC.
+  bool Quote = (Lib.find(" ") != StringRef::npos);
+  std::string ArgStr = Quote ? "\"" : "";
+  ArgStr += Lib;
   if (!Lib.endswith_lower(".lib"))
     ArgStr += ".lib";
+  ArgStr += Quote ? "\"" : "";
   return ArgStr;
 }
 
@@ -1621,6 +1650,9 @@
         bool d, bool p, bool w, unsigned RegParms)
     : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
 
+  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+                           CodeGen::CodeGenModule &CGM) const override;
+
   void getDependentLibraryOption(llvm::StringRef Lib,
                                  llvm::SmallString<24> &Opt) const override {
     Opt = "/DEFAULTLIB:";
@@ -1634,12 +1666,35 @@
   }
 };
 
+static void addStackProbeSizeTargetAttribute(const Decl *D,
+                                             llvm::GlobalValue *GV,
+                                             CodeGen::CodeGenModule &CGM) {
+  if (isa<FunctionDecl>(D)) {
+    if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
+      llvm::Function *Fn = cast<llvm::Function>(GV);
+
+      Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
+    }
+  }
+}
+
+void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
+                                                     llvm::GlobalValue *GV,
+                                            CodeGen::CodeGenModule &CGM) const {
+  X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
+
+  addStackProbeSizeTargetAttribute(D, GV, CGM);
+}
+
 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
   bool HasAVX;
 public:
   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
     : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
 
+  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+                           CodeGen::CodeGenModule &CGM) const override;
+
   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
     return 7;
   }
@@ -1671,6 +1726,13 @@
   }
 };
 
+void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
+                                                     llvm::GlobalValue *GV,
+                                            CodeGen::CodeGenModule &CGM) const {
+  TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
+
+  addStackProbeSizeTargetAttribute(D, GV, CGM);
+}
 }
 
 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
@@ -2139,19 +2201,15 @@
   return ABIArgInfo::getIndirect(Align);
 }
 
-/// GetByteVectorType - The ABI specifies that a value should be passed in an
-/// full vector XMM/YMM register.  Pick an LLVM IR type that will be passed as a
-/// vector register.
+/// The ABI specifies that a value should be passed in a full vector XMM/YMM
+/// register. Pick an LLVM IR type that will be passed as a vector register.
 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
-  llvm::Type *IRType = CGT.ConvertType(Ty);
+  // Wrapper structs/arrays that only contain vectors are passed just like
+  // vectors; strip them off if present.
+  if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
+    Ty = QualType(InnerTy, 0);
 
-  // Wrapper structs that just contain vectors are passed just like vectors,
-  // strip them off if present.
-  llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
-  while (STy && STy->getNumElements() == 1) {
-    IRType = STy->getElementType(0);
-    STy = dyn_cast<llvm::StructType>(IRType);
-  }
+  llvm::Type *IRType = CGT.ConvertType(Ty);
 
   // If the preferred type is a 16-byte vector, prefer to pass it.
   if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
@@ -2415,7 +2473,7 @@
     }
   }
 
-  llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
+  llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
 
 
   // Verify that the second element is at an 8-byte offset.
@@ -2492,7 +2550,7 @@
     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
                                     llvm::Type::getX86_FP80Ty(getVMContext()),
-                                    NULL);
+                                    nullptr);
     break;
   }
 
@@ -2695,6 +2753,10 @@
   if (FI.getReturnInfo().isIndirect())
     --freeIntRegs;
 
+  // The chain argument effectively gives us another free register.
+  if (FI.isChainCall())
+    ++freeIntRegs;
+
   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
   // get assigned (in left-to-right order) for passing as follows...
@@ -2895,7 +2957,7 @@
     llvm::Type *DoubleTy = CGF.DoubleTy;
     llvm::Type *DblPtrTy =
       llvm::PointerType::getUnqual(DoubleTy);
-    llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
+    llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
     llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
     Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
     V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
@@ -2990,7 +3052,7 @@
       return ABIArgInfo::getDirect();
   }
 
-  if (RT || Ty->isMemberPointerType()) {
+  if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
     // not 1, 2, 4, or 8 bytes, must be passed by reference."
     if (Width > 64 || !llvm::isPowerOf2_64(Width))
@@ -3046,48 +3108,6 @@
   return AddrTyped;
 }
 
-namespace {
-
-class NaClX86_64ABIInfo : public ABIInfo {
- public:
-  NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
-      : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
-  void computeInfo(CGFunctionInfo &FI) const override;
-  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
-                         CodeGenFunction &CGF) const override;
- private:
-  PNaClABIInfo PInfo;  // Used for generating calls with pnaclcall callingconv.
-  X86_64ABIInfo NInfo; // Used for everything else.
-};
-
-class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo  {
-  bool HasAVX;
- public:
-   NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
-       : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
-   }
-   unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
-     return HasAVX ? 32 : 16;
-   }
-};
-
-}
-
-void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
-  if (FI.getASTCallingConvention() == CC_PnaclCall)
-    PInfo.computeInfo(FI);
-  else
-    NInfo.computeInfo(FI);
-}
-
-llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
-                                          CodeGenFunction &CGF) const {
-  // Always use the native convention; calling pnacl-style varargs functions
-  // is unuspported.
-  return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
-}
-
-
 // PowerPC-32
 namespace {
 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
@@ -3114,6 +3134,10 @@
   unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
     return 16; // Natural alignment for Altivec vectors.
   }
+
+  bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
+    return true;
+  }
 };
 
 }
@@ -3326,6 +3350,10 @@
   unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
     return 16; // Natural alignment for Altivec and VSX vectors.
   }
+
+  bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
+    return true;
+  }
 };
 
 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
@@ -3343,6 +3371,10 @@
   unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
     return 16; // Natural alignment for Altivec vectors.
   }
+
+  bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
+    return true;
+  }
 };
 
 }
@@ -3645,7 +3677,7 @@
       llvm::Type *CoerceTy;
       if (Bits > GPRBits) {
         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
-        CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
+        CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
       } else
         CoerceTy = llvm::IntegerType::get(getVMContext(),
                                           llvm::RoundUpToAlignment(Bits, 8));
@@ -3822,9 +3854,7 @@
   bool isDarwinPCS() const { return Kind == DarwinPCS; }
 
   ABIArgInfo classifyReturnType(QualType RetTy) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
-                                  bool &IsHA, unsigned &AllocatedGPR,
-                                  bool &IsSmallAggr, bool IsNamedArg) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy) const;
   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
                                          uint64_t Members) const override;
@@ -3832,68 +3862,11 @@
   bool isIllegalVectorType(QualType Ty) const;
 
   void computeInfo(CGFunctionInfo &FI) const override {
-    // To correctly handle Homogeneous Aggregate, we need to keep track of the
-    // number of SIMD and Floating-point registers allocated so far.
-    // If the argument is an HFA or an HVA and there are sufficient unallocated
-    // SIMD and Floating-point registers, then the argument is allocated to SIMD
-    // and Floating-point Registers (with one register per member of the HFA or
-    // HVA). Otherwise, the NSRN is set to 8.
-    unsigned AllocatedVFP = 0;
-
-    // To correctly handle small aggregates, we need to keep track of the number
-    // of GPRs allocated so far. If the small aggregate can't all fit into
-    // registers, it will be on stack. We don't allow the aggregate to be
-    // partially in registers.
-    unsigned AllocatedGPR = 0;
-
-    // Find the number of named arguments. Variadic arguments get special
-    // treatment with the Darwin ABI.
-    unsigned NumRequiredArgs = FI.getNumRequiredArgs();
-
     if (!getCXXABI().classifyReturnType(FI))
       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
-    unsigned ArgNo = 0;
-    for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
-         it != ie; ++it, ++ArgNo) {
-      unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
-      bool IsHA = false, IsSmallAggr = false;
-      const unsigned NumVFPs = 8;
-      const unsigned NumGPRs = 8;
-      bool IsNamedArg = ArgNo < NumRequiredArgs;
-      it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
-                                      AllocatedGPR, IsSmallAggr, IsNamedArg);
 
-      // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
-      // as sequences of floats since they'll get "holes" inserted as
-      // padding by the back end.
-      if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
-          getContext().getTypeAlign(it->type) < 64) {
-        uint32_t NumStackSlots = getContext().getTypeSize(it->type);
-        NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
-
-        llvm::Type *CoerceTy = llvm::ArrayType::get(
-            llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
-        it->info = ABIArgInfo::getDirect(CoerceTy);
-      }
-
-      // If we do not have enough VFP registers for the HA, any VFP registers
-      // that are unallocated are marked as unavailable. To achieve this, we add
-      // padding of (NumVFPs - PreAllocation) floats.
-      if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
-        llvm::Type *PaddingTy = llvm::ArrayType::get(
-            llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
-        it->info.setPaddingType(PaddingTy);
-      }
-
-      // If we do not have enough GPRs for the small aggregate, any GPR regs
-      // that are unallocated are marked as unavailable.
-      if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
-        llvm::Type *PaddingTy = llvm::ArrayType::get(
-            llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
-        it->info =
-            ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
-      }
-    }
+    for (auto &it : FI.arguments())
+      it.info = classifyArgumentType(it.type);
   }
 
   llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
@@ -3924,12 +3897,7 @@
 };
 }
 
-ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
-                                                unsigned &AllocatedVFP,
-                                                bool &IsHA,
-                                                unsigned &AllocatedGPR,
-                                                bool &IsSmallAggr,
-                                                bool IsNamedArg) const {
+ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
   Ty = useFirstFieldIfTransparentUnion(Ty);
 
   // Handle illegal vector types here.
@@ -3938,53 +3906,30 @@
     // Android promotes <2 x i8> to i16, not i32
     if (Size <= 16) {
       llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
-      AllocatedGPR++;
       return ABIArgInfo::getDirect(ResType);
     }
     if (Size == 32) {
       llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
-      AllocatedGPR++;
       return ABIArgInfo::getDirect(ResType);
     }
     if (Size == 64) {
       llvm::Type *ResType =
           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
-      AllocatedVFP++;
       return ABIArgInfo::getDirect(ResType);
     }
     if (Size == 128) {
       llvm::Type *ResType =
           llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
-      AllocatedVFP++;
       return ABIArgInfo::getDirect(ResType);
     }
-    AllocatedGPR++;
     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
   }
-  if (Ty->isVectorType())
-    // Size of a legal vector should be either 64 or 128.
-    AllocatedVFP++;
-  if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
-    if (BT->getKind() == BuiltinType::Half ||
-        BT->getKind() == BuiltinType::Float ||
-        BT->getKind() == BuiltinType::Double ||
-        BT->getKind() == BuiltinType::LongDouble)
-      AllocatedVFP++;
-  }
 
   if (!isAggregateTypeForABI(Ty)) {
     // Treat an enum type as its underlying type.
     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
       Ty = EnumTy->getDecl()->getIntegerType();
 
-    if (!Ty->isFloatingType() && !Ty->isVectorType()) {
-      unsigned Alignment = getContext().getTypeAlign(Ty);
-      if (!isDarwinPCS() && Alignment > 64)
-        AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
-
-      int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
-      AllocatedGPR += RegsNeeded;
-    }
     return (Ty->isPromotableIntegerType() && isDarwinPCS()
                 ? ABIArgInfo::getExtend()
                 : ABIArgInfo::getDirect());
@@ -3993,9 +3938,8 @@
   // Structures with either a non-trivial destructor or a non-trivial
   // copy constructor are always indirect.
   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
-    AllocatedGPR++;
     return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
-                                          CGCXXABI::RAA_DirectInMemory);
+                                   CGCXXABI::RAA_DirectInMemory);
   }
 
   // Empty records are always ignored on Darwin, but actually passed in C++ mode
@@ -4004,7 +3948,6 @@
     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
       return ABIArgInfo::getIgnore();
 
-    ++AllocatedGPR;
     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
   }
 
@@ -4012,28 +3955,16 @@
   const Type *Base = nullptr;
   uint64_t Members = 0;
   if (isHomogeneousAggregate(Ty, Base, Members)) {
-    IsHA = true;
-    if (!IsNamedArg && isDarwinPCS()) {
-      // With the Darwin ABI, variadic arguments are always passed on the stack
-      // and should not be expanded. Treat variadic HFAs as arrays of doubles.
-      uint64_t Size = getContext().getTypeSize(Ty);
-      llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
-      return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
-    }
-    AllocatedVFP += Members;
-    return ABIArgInfo::getExpand();
+    return ABIArgInfo::getDirect(
+        llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
   }
 
   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
   uint64_t Size = getContext().getTypeSize(Ty);
   if (Size <= 128) {
     unsigned Alignment = getContext().getTypeAlign(Ty);
-    if (!isDarwinPCS() && Alignment > 64)
-      AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
-
     Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
-    AllocatedGPR += Size / 64;
-    IsSmallAggr = true;
+
     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
     // For aggregates with 16-byte alignment, we use i128.
     if (Alignment < 128 && Size == 128) {
@@ -4043,7 +3974,6 @@
     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
   }
 
-  AllocatedGPR++;
   return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
 }
 
@@ -4119,14 +4049,25 @@
   return Members <= 4;
 }
 
-llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
-                                          CodeGenFunction &CGF) const {
-  unsigned AllocatedGPR = 0, AllocatedVFP = 0;
-  bool IsHA = false, IsSmallAggr = false;
-  ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
-                                       IsSmallAggr, false /*IsNamedArg*/);
+llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
+                                            QualType Ty,
+                                            CodeGenFunction &CGF) const {
+  ABIArgInfo AI = classifyArgumentType(Ty);
   bool IsIndirect = AI.isIndirect();
 
+  llvm::Type *BaseTy = CGF.ConvertType(Ty);
+  if (IsIndirect)
+    BaseTy = llvm::PointerType::getUnqual(BaseTy);
+  else if (AI.getCoerceToType())
+    BaseTy = AI.getCoerceToType();
+
+  unsigned NumRegs = 1;
+  if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
+    BaseTy = ArrTy->getElementType();
+    NumRegs = ArrTy->getNumElements();
+  }
+  bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
+
   // The AArch64 va_list type and handling is specified in the Procedure Call
   // Standard, section B.4:
   //
@@ -4146,21 +4087,19 @@
 
   llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
   int reg_top_index;
-  int RegSize;
-  if (AllocatedGPR) {
-    assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
+  int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
+  if (!IsFPR) {
     // 3 is the field number of __gr_offs
     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
     reg_top_index = 1; // field number for __gr_top
-    RegSize = 8 * AllocatedGPR;
+    RegSize = llvm::RoundUpToAlignment(RegSize, 8);
   } else {
-    assert(!AllocatedGPR && "Argument must go in VFP or int regs");
     // 4 is the field number of __vr_offs.
     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
     reg_top_index = 2; // field number for __vr_top
-    RegSize = 16 * AllocatedVFP;
+    RegSize = 16 * NumRegs;
   }
 
   //=======================================
@@ -4184,7 +4123,7 @@
   // Integer arguments may need to correct register alignment (for example a
   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
   // align __gr_offs to calculate the potential address.
-  if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
+  if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
     int Align = Ctx.getTypeAlign(Ty) / 8;
 
     reg_offs = CGF.Builder.CreateAdd(
@@ -4428,17 +4367,10 @@
 
 private:
   ABIKind Kind;
-  mutable int VFPRegs[16];
-  const unsigned NumVFPs;
-  const unsigned NumGPRs;
-  mutable unsigned AllocatedGPRs;
-  mutable unsigned AllocatedVFPs;
 
 public:
-  ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
-    NumVFPs(16), NumGPRs(4) {
-    setRuntimeCC();
-    resetAllocatedRegs();
+  ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
+    setCCs();
   }
 
   bool isEABI() const {
@@ -4468,8 +4400,7 @@
 
 private:
   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
-                                  bool &IsCPRC) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
   bool isIllegalVectorType(QualType Ty) const;
 
   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
@@ -4483,11 +4414,7 @@
 
   llvm::CallingConv::ID getLLVMDefaultCC() const;
   llvm::CallingConv::ID getABIDefaultCC() const;
-  void setRuntimeCC();
-
-  void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
-  void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
-  void resetAllocatedRegs(void) const;
+  void setCCs();
 };
 
 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
@@ -4559,57 +4486,50 @@
                                               B));
   }
 
+  bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
+    return false;
+    // FIXME: backend implementation too restricted, even on Darwin.
+    // return CGF.getTarget().getTriple().isOSDarwin();
+  }
 };
 
+class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
+  void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
+                                        CodeGen::CodeGenModule &CGM) const;
+
+public:
+  WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
+      : ARMTargetCodeGenInfo(CGT, K) {}
+
+  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+                           CodeGen::CodeGenModule &CGM) const override;
+};
+
+void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
+    const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
+  if (!isa<FunctionDecl>(D))
+    return;
+  if (CGM.getCodeGenOpts().StackProbeSize == 4096)
+    return;
+
+  llvm::Function *F = cast<llvm::Function>(GV);
+  F->addFnAttr("stack-probe-size",
+               llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
+}
+
+void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
+    const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
+  ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
+  addStackProbeSizeTargetAttribute(D, GV, CGM);
+}
 }
 
 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
-  // To correctly handle Homogeneous Aggregate, we need to keep track of the
-  // VFP registers allocated so far.
-  // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
-  // VFP registers of the appropriate type unallocated then the argument is
-  // allocated to the lowest-numbered sequence of such registers.
-  // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
-  // unallocated are marked as unavailable. 
-  resetAllocatedRegs();
-
-  if (getCXXABI().classifyReturnType(FI)) {
-    if (FI.getReturnInfo().isIndirect())
-      markAllocatedGPRs(1, 1);
-  } else {
+  if (!getCXXABI().classifyReturnType(FI))
     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
-  }
-  for (auto &I : FI.arguments()) {
-    unsigned PreAllocationVFPs = AllocatedVFPs;
-    unsigned PreAllocationGPRs = AllocatedGPRs;
-    bool IsCPRC = false;
-    // 6.1.2.3 There is one VFP co-processor register class using registers
-    // s0-s15 (d0-d7) for passing arguments.
-    I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
 
-    // If we have allocated some arguments onto the stack (due to running
-    // out of VFP registers), we cannot split an argument between GPRs and
-    // the stack. If this situation occurs, we add padding to prevent the
-    // GPRs from being used. In this situation, the current argument could
-    // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
-    // unusable anyway.
-    // We do not have to do this if the argument is being passed ByVal, as the
-    // backend can handle that situation correctly.
-    const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
-    const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
-    if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
-        StackUsed && !IsByVal) {
-      llvm::Type *PaddingTy = llvm::ArrayType::get(
-          llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
-      if (I.info.canHaveCoerceToType()) {
-        I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */,
-                                       0 /* offset */, PaddingTy, true);
-      } else {
-        I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
-                                       PaddingTy, true);
-      }
-    }
-  }
+  for (auto &I : FI.arguments())
+    I.info = classifyArgumentType(I.type, FI.isVariadic());
 
   // Always honor user-specified calling convention.
   if (FI.getCallingConvention() != llvm::CallingConv::C)
@@ -4617,7 +4537,7 @@
 
   llvm::CallingConv::ID cc = getRuntimeCC();
   if (cc != llvm::CallingConv::C)
-    FI.setEffectiveCallingConvention(cc);    
+    FI.setEffectiveCallingConvention(cc);
 }
 
 /// Return the default calling convention that LLVM will use.
@@ -4642,7 +4562,7 @@
   llvm_unreachable("bad ABI kind");
 }
 
-void ARMABIInfo::setRuntimeCC() {
+void ARMABIInfo::setCCs() {
   assert(getRuntimeCC() == llvm::CallingConv::C);
 
   // Don't muddy up the IR with a ton of explicit annotations if
@@ -4650,66 +4570,13 @@
   llvm::CallingConv::ID abiCC = getABIDefaultCC();
   if (abiCC != getLLVMDefaultCC())
     RuntimeCC = abiCC;
+
+  BuiltinCC = (getABIKind() == APCS ?
+               llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
 }
 
-/// markAllocatedVFPs - update VFPRegs according to the alignment and
-/// number of VFP registers (unit is S register) requested.
-void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
-                                   unsigned NumRequired) const {
-  // Early Exit.
-  if (AllocatedVFPs >= 16) {
-    // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
-    // the stack.
-    AllocatedVFPs = 17;
-    return;
-  }
-  // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
-  // VFP registers of the appropriate type unallocated then the argument is
-  // allocated to the lowest-numbered sequence of such registers.
-  for (unsigned I = 0; I < 16; I += Alignment) {
-    bool FoundSlot = true;
-    for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
-      if (J >= 16 || VFPRegs[J]) {
-         FoundSlot = false;
-         break;
-      }
-    if (FoundSlot) {
-      for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
-        VFPRegs[J] = 1;
-      AllocatedVFPs += NumRequired;
-      return;
-    }
-  }
-  // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
-  // unallocated are marked as unavailable.
-  for (unsigned I = 0; I < 16; I++)
-    VFPRegs[I] = 1;
-  AllocatedVFPs = 17; // We do not have enough VFP registers.
-}
-
-/// Update AllocatedGPRs to record the number of general purpose registers
-/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
-/// this represents arguments being stored on the stack.
-void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
-                                   unsigned NumRequired) const {
-  assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
-
-  if (Alignment == 2 && AllocatedGPRs & 0x1)
-    AllocatedGPRs += 1;
-
-  AllocatedGPRs += NumRequired;
-}
-
-void ARMABIInfo::resetAllocatedRegs(void) const {
-  AllocatedGPRs = 0;
-  AllocatedVFPs = 0;
-  for (unsigned i = 0; i < NumVFPs; ++i)
-    VFPRegs[i] = 0;
-}
-
-ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
-                                            bool &IsCPRC) const {
-  // We update number of allocated VFPs according to
+ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
+                                            bool isVariadic) const {
   // 6.1.2.1 The following argument types are VFP CPRCs:
   //   A single-precision floating-point type (including promoted
   //   half-precision types); A double-precision floating-point type;
@@ -4727,58 +4594,20 @@
     if (Size <= 32) {
       llvm::Type *ResType =
           llvm::Type::getInt32Ty(getVMContext());
-      markAllocatedGPRs(1, 1);
       return ABIArgInfo::getDirect(ResType);
     }
     if (Size == 64) {
       llvm::Type *ResType = llvm::VectorType::get(
           llvm::Type::getInt32Ty(getVMContext()), 2);
-      if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
-        markAllocatedGPRs(2, 2);
-      } else {
-        markAllocatedVFPs(2, 2);
-        IsCPRC = true;
-      }
       return ABIArgInfo::getDirect(ResType);
     }
     if (Size == 128) {
       llvm::Type *ResType = llvm::VectorType::get(
           llvm::Type::getInt32Ty(getVMContext()), 4);
-      if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
-        markAllocatedGPRs(2, 4);
-      } else {
-        markAllocatedVFPs(4, 4);
-        IsCPRC = true;
-      }
       return ABIArgInfo::getDirect(ResType);
     }
-    markAllocatedGPRs(1, 1);
     return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
   }
-  // Update VFPRegs for legal vector types.
-  if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
-    if (const VectorType *VT = Ty->getAs<VectorType>()) {
-      uint64_t Size = getContext().getTypeSize(VT);
-      // Size of a legal vector should be power of 2 and above 64.
-      markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
-      IsCPRC = true;
-    }
-  }
-  // Update VFPRegs for floating point types.
-  if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
-    if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
-      if (BT->getKind() == BuiltinType::Half ||
-          BT->getKind() == BuiltinType::Float) {
-        markAllocatedVFPs(1, 1);
-        IsCPRC = true;
-      }
-      if (BT->getKind() == BuiltinType::Double ||
-          BT->getKind() == BuiltinType::LongDouble) {
-        markAllocatedVFPs(2, 2);
-        IsCPRC = true;
-      }
-    }
-  }
 
   if (!isAggregateTypeForABI(Ty)) {
     // Treat an enum type as its underlying type.
@@ -4786,15 +4615,11 @@
       Ty = EnumTy->getDecl()->getIntegerType();
     }
 
-    unsigned Size = getContext().getTypeSize(Ty);
-    if (!IsCPRC)
-      markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
     return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
                                           : ABIArgInfo::getDirect());
   }
 
   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
-    markAllocatedGPRs(1, 1);
     return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
   }
 
@@ -4810,19 +4635,6 @@
     if (isHomogeneousAggregate(Ty, Base, Members)) {
       assert(Base && "Base class should be set for homogeneous aggregate");
       // Base can be a floating-point or a vector.
-      if (Base->isVectorType()) {
-        // ElementSize is in number of floats.
-        unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
-        markAllocatedVFPs(ElementSize,
-                          Members * ElementSize);
-      } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
-        markAllocatedVFPs(1, Members);
-      else {
-        assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
-               Base->isSpecificBuiltinType(BuiltinType::LongDouble));
-        markAllocatedVFPs(2, Members * 2);
-      }
-      IsCPRC = true;
       return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
     }
   }
@@ -4841,7 +4653,6 @@
     // argument is greater than 64 bytes, this will always use up any available
     // registers (of which there are 4). We also don't care about getting the
     // alignment right, because general-purpose registers cannot be back-filled.
-    markAllocatedGPRs(1, 4);
     return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
            /*Realign=*/TyAlign > ABIAlign);
   }
@@ -4854,11 +4665,9 @@
   if (getContext().getTypeAlign(Ty) <= 32) {
     ElemTy = llvm::Type::getInt32Ty(getVMContext());
     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
-    markAllocatedGPRs(1, SizeRegs);
   } else {
     ElemTy = llvm::Type::getInt64Ty(getVMContext());
     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
-    markAllocatedGPRs(2, SizeRegs * 2);
   }
 
   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
@@ -4958,7 +4767,6 @@
 
   // Large vector types should be returned via memory.
   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
-    markAllocatedGPRs(1, 1);
     return ABIArgInfo::getIndirect(0);
   }
 
@@ -4996,7 +4804,6 @@
     }
 
     // Otherwise return in memory.
-    markAllocatedGPRs(1, 1);
     return ABIArgInfo::getIndirect(0);
   }
 
@@ -5032,7 +4839,6 @@
     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
   }
 
-  markAllocatedGPRs(1, 1);
   return ABIArgInfo::getIndirect(0);
 }
 
@@ -5145,42 +4951,6 @@
   return AddrTyped;
 }
 
-namespace {
-
-class NaClARMABIInfo : public ABIInfo {
- public:
-  NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
-      : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
-  void computeInfo(CGFunctionInfo &FI) const override;
-  llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
-                         CodeGenFunction &CGF) const override;
- private:
-  PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
-  ARMABIInfo NInfo; // Used for everything else.
-};
-
-class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo  {
- public:
-  NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
-      : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
-};
-
-}
-
-void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
-  if (FI.getASTCallingConvention() == CC_PnaclCall)
-    PInfo.computeInfo(FI);
-  else
-    static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
-}
-
-llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
-                                       CodeGenFunction &CGF) const {
-  // Always use the native convention; calling pnacl-style varargs functions
-  // is unsupported.
-  return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
-}
-
 //===----------------------------------------------------------------------===//
 // NVPTX ABI Implementation
 //===----------------------------------------------------------------------===//
@@ -5314,9 +5084,10 @@
   // Get "nvvm.annotations" metadata node
   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
 
-  llvm::Value *MDVals[] = {
-      F, llvm::MDString::get(Ctx, Name),
-      llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
+  llvm::Metadata *MDVals[] = {
+      llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
+      llvm::ConstantAsMetadata::get(
+          llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
   // Append metadata to nvvm.annotations
   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
 }
@@ -5785,6 +5556,8 @@
 
 ABIArgInfo
 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
+  Ty = useFirstFieldIfTransparentUnion(Ty);
+
   uint64_t OrigOffset = Offset;
   uint64_t TySize = getContext().getTypeSize(Ty);
   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
@@ -5923,10 +5696,13 @@
   llvm::Type *BP = CGF.Int8PtrTy;
   llvm::Type *BPP = CGF.Int8PtrPtrTy;
 
-  // Integer arguments are promoted 32-bit on O32 and 64-bit on N32/N64.
+  // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
+  // Pointers are also promoted in the same way but this only matters for N32.
   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
-  if (Ty->isIntegerType() &&
-      CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) {
+  unsigned PtrWidth = getTarget().getPointerWidth(0);
+  if ((Ty->isIntegerType() &&
+          CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
+      (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
     Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
                                                 Ty->isSignedIntegerType());
   }
@@ -5938,7 +5714,6 @@
       std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
   llvm::Value *AddrTyped;
-  unsigned PtrWidth = getTarget().getPointerWidth(0);
   llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
 
   if (TypeAlign > MinABIStackAlignInBytes) {
@@ -6028,20 +5803,24 @@
         llvm::NamedMDNode *OpenCLMetadata = 
             M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
 
-        SmallVector<llvm::Value*, 5> Operands;
-        Operands.push_back(F);
+        SmallVector<llvm::Metadata *, 5> Operands;
+        Operands.push_back(llvm::ConstantAsMetadata::get(F));
 
-        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 
-                             llvm::APInt(32, Attr->getXDim())));
-        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
-                             llvm::APInt(32, Attr->getYDim())));
-        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty, 
-                             llvm::APInt(32, Attr->getZDim())));
+        Operands.push_back(
+            llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
+                M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
+        Operands.push_back(
+            llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
+                M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
+        Operands.push_back(
+            llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
+                M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
 
         // Add a boolean constant operand for "required" (true) or "hint" (false)
         // for implementing the work_group_size_hint attr later. Currently 
         // always true as the hint is not yet implemented.
-        Operands.push_back(llvm::ConstantInt::getTrue(Context));
+        Operands.push_back(
+            llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
       }
     }
@@ -6183,6 +5962,45 @@
   return AddrTyped;
 }
 
+//===----------------------------------------------------------------------===//
+// AMDGPU ABI Implementation
+//===----------------------------------------------------------------------===//
+
+namespace {
+
+class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
+public:
+  AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
+    : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
+  void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+                           CodeGen::CodeGenModule &M) const override;
+};
+
+}
+
+void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
+  const Decl *D,
+  llvm::GlobalValue *GV,
+  CodeGen::CodeGenModule &M) const {
+  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
+  if (!FD)
+    return;
+
+  if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
+    llvm::Function *F = cast<llvm::Function>(GV);
+    uint32_t NumVGPR = Attr->getNumVGPR();
+    if (NumVGPR != 0)
+      F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
+  }
+
+  if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
+    llvm::Function *F = cast<llvm::Function>(GV);
+    unsigned NumSGPR = Attr->getNumSGPR();
+    if (NumSGPR != 0)
+      F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
+  }
+}
+
 
 //===----------------------------------------------------------------------===//
 // SPARC v9 ABI Implementation.
@@ -6766,8 +6584,8 @@
   SmallStringEnc Enc;
   if (getTypeString(Enc, D, CGM, TSC)) {
     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
-    llvm::SmallVector<llvm::Value *, 2> MDVals;
-    MDVals.push_back(GV);
+    llvm::SmallVector<llvm::Metadata *, 2> MDVals;
+    MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
     MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
     llvm::NamedMDNode *MD =
       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
@@ -7153,6 +6971,12 @@
   case llvm::Triple::thumb:
   case llvm::Triple::thumbeb:
     {
+      if (Triple.getOS() == llvm::Triple::Win32) {
+        TheTargetCodeGenInfo =
+            new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
+        return *TheTargetCodeGenInfo;
+      }
+
       ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
       if (getTarget().getABI() == "apcs-gnu")
         Kind = ARMABIInfo::APCS;
@@ -7161,14 +6985,7 @@
                 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
         Kind = ARMABIInfo::AAPCS_VFP;
 
-      switch (Triple.getOS()) {
-        case llvm::Triple::NaCl:
-          return *(TheTargetCodeGenInfo =
-                   new NaClARMTargetCodeGenInfo(Types, Kind));
-        default:
-          return *(TheTargetCodeGenInfo =
-                   new ARMTargetCodeGenInfo(Types, Kind));
-      }
+      return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
     }
 
   case llvm::Triple::ppc:
@@ -7210,7 +7027,7 @@
     bool IsDarwinVectorABI = Triple.isOSDarwin();
     bool IsSmallStructInRegABI =
         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
-    bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
+    bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
 
     if (Triple.getOS() == llvm::Triple::Win32) {
       return *(TheTargetCodeGenInfo =
@@ -7234,9 +7051,8 @@
     case llvm::Triple::Win32:
       return *(TheTargetCodeGenInfo =
                    new WinX86_64TargetCodeGenInfo(Types, HasAVX));
-    case llvm::Triple::NaCl:
-      return *(TheTargetCodeGenInfo =
-                   new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
+    case llvm::Triple::PS4:
+      return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types, HasAVX));
     default:
       return *(TheTargetCodeGenInfo =
                    new X86_64TargetCodeGenInfo(Types, HasAVX));
@@ -7244,6 +7060,10 @@
   }
   case llvm::Triple::hexagon:
     return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
+  case llvm::Triple::r600:
+    return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
+  case llvm::Triple::amdgcn:
+    return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
   case llvm::Triple::sparcv9:
     return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
   case llvm::Triple::xcore:
diff --git a/lib/CodeGen/TargetInfo.h b/lib/CodeGen/TargetInfo.h
index cc469d6..87f1376 100644
--- a/lib/CodeGen/TargetInfo.h
+++ b/lib/CodeGen/TargetInfo.h
@@ -225,6 +225,13 @@
   virtual unsigned getOpenMPSimdDefaultAlignment(QualType Type) const {
     return 0;
   }
+
+  /// Control whether __builtin_longjmp / __builtin_setjmp are lowered to
+  /// llvm.eh.sjlj.longjmp / llvm.eh.sjlj.setjmp or the normal library
+  /// function.
+  virtual bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const {
+    return false;
+  }
 };
 }
 
diff --git a/lib/Driver/Action.cpp b/lib/Driver/Action.cpp
index d4f339d..360dbee 100644
--- a/lib/Driver/Action.cpp
+++ b/lib/Driver/Action.cpp
@@ -29,6 +29,7 @@
   case AnalyzeJobClass: return "analyzer";
   case MigrateJobClass: return "migrator";
   case CompileJobClass: return "compiler";
+  case BackendJobClass: return "backend";
   case AssembleJobClass: return "assembler";
   case LinkJobClass: return "linker";
   case LipoJobClass: return "lipo";
@@ -92,6 +93,12 @@
                                    types::ID OutputType)
     : JobAction(CompileJobClass, std::move(Input), OutputType) {}
 
+void BackendJobAction::anchor() {}
+
+BackendJobAction::BackendJobAction(std::unique_ptr<Action> Input,
+                                   types::ID OutputType)
+    : JobAction(BackendJobClass, std::move(Input), OutputType) {}
+
 void AssembleJobAction::anchor() {}
 
 AssembleJobAction::AssembleJobAction(std::unique_ptr<Action> Input,
diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp
index d459e4b..61aaa97 100644
--- a/lib/Driver/Driver.cpp
+++ b/lib/Driver/Driver.cpp
@@ -17,6 +17,7 @@
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Job.h"
 #include "clang/Driver/Options.h"
+#include "clang/Driver/SanitizerArgs.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Driver/ToolChain.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -44,20 +45,17 @@
 using namespace clang;
 using namespace llvm::opt;
 
-Driver::Driver(StringRef ClangExecutable,
-               StringRef DefaultTargetTriple,
+Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
                DiagnosticsEngine &Diags)
-  : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
-    ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-    UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
-    DefaultImageName("a.out"),
-    DriverTitle("clang LLVM compiler"),
-    CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
-    CCLogDiagnosticsFilename(nullptr),
-    CCCPrintBindings(false),
-    CCPrintHeaders(false), CCLogDiagnostics(false),
-    CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
-    CCCUsePCH(true), SuppressMissingInputWarning(false) {
+    : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
+      SaveTemps(SaveTempsNone), ClangExecutable(ClangExecutable),
+      SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
+      DefaultTargetTriple(DefaultTargetTriple),
+      DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
+      CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
+      CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+      CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
+      CCCUsePCH(true), SuppressMissingInputWarning(false) {
 
   Name = llvm::sys::path::stem(ClangExecutable);
   Dir  = llvm::sys::path::parent_path(ClangExecutable);
@@ -65,10 +63,13 @@
   // Compute the path to the resource directory.
   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
   SmallString<128> P(Dir);
-  if (ClangResourceDir != "")
+  if (ClangResourceDir != "") {
     llvm::sys::path::append(P, ClangResourceDir);
-  else
-    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
+  } else {
+    StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
+    llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
+                            CLANG_VERSION_STRING);
+  }
   ResourceDir = P.str();
 }
 
@@ -125,9 +126,7 @@
       << Args->getArgString(MissingArgIndex) << MissingArgCount;
 
   // Check for unsupported options.
-  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
-       it != ie; ++it) {
-    Arg *A = *it;
+  for (const Arg *A : *Args) {
     if (A->getOption().hasFlag(options::Unsupported)) {
       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
       continue;
@@ -165,7 +164,7 @@
       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
     FinalPhase = phases::Preprocess;
 
-    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
+    // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
@@ -174,10 +173,13 @@
              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
                                         options::OPT__analyze_auto)) ||
-             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
-             (PhaseArg = DAL.getLastArg(options::OPT_S))) {
+             (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
     FinalPhase = phases::Compile;
 
+    // -S only runs up to the backend.
+  } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
+    FinalPhase = phases::Backend;
+
     // -c only runs up to the assembler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
     FinalPhase = phases::Assemble;
@@ -205,10 +207,7 @@
   DerivedArgList *DAL = new DerivedArgList(Args);
 
   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
-  for (ArgList::const_iterator it = Args.begin(),
-         ie = Args.end(); it != ie; ++it) {
-    const Arg *A = *it;
-
+  for (Arg *A : Args) {
     // Unfortunately, we have to parse some forwarding options (-Xassembler,
     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
     // (assembler and preprocessor), or bypass a previous driver ('collect2').
@@ -274,7 +273,7 @@
       continue;
     }
 
-    DAL->append(*it);
+    DAL->append(A);
   }
 
   // Add a default value of -mlinker-version=, if one was given and the user
@@ -364,6 +363,13 @@
   if (const Arg *A = Args->getLastArg(options::OPT_resource_dir))
     ResourceDir = A->getValue();
 
+  if (const Arg *A = Args->getLastArg(options::OPT_save_temps_EQ)) {
+    SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
+                    .Case("cwd", SaveTempsCwd)
+                    .Case("obj", SaveTempsObj)
+                    .Default(SaveTempsCwd);
+  }
+
   // Perform the default argument translations.
   DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
 
@@ -468,9 +474,7 @@
   // Don't attempt to generate preprocessed files if multiple -arch options are
   // used, unless they're all duplicates.
   llvm::StringSet<> ArchNames;
-  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
-       it != ie; ++it) {
-    Arg *A = *it;
+  for (const Arg *A : C.getArgs()) {
     if (A->getOption().matches(options::OPT_arch)) {
       StringRef ArchName = A->getValue();
       ArchNames.insert(ArchName);
@@ -506,7 +510,7 @@
 
   // If any of the preprocessing commands failed, clean up and exit.
   if (!FailingCommands.empty()) {
-    if (!C.getArgs().hasArg(options::OPT_save_temps))
+    if (!isSaveTempsEnabled())
       C.CleanupFileList(C.getTempFiles(), true);
 
     Diag(clang::diag::note_drv_command_failed_diag_msg)
@@ -550,6 +554,11 @@
     Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
     Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
   }
+
+  for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
+                                            options::OPT_frewrite_map_file_EQ))
+    Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
+
   Diag(clang::diag::note_drv_command_failed_diag_msg)
       << "\n\n********************";
 }
@@ -609,7 +618,7 @@
     const Command *FailingCommand = it->second;
 
     // Remove result files if we're not saving temps.
-    if (!C.getArgs().hasArg(options::OPT_save_temps)) {
+    if (!isSaveTempsEnabled()) {
       const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
       C.CleanupFileMap(C.getResultFiles(), JA, true);
 
@@ -849,7 +858,9 @@
 /// \brief Check whether the given input tree contains any compilation or
 /// assembly actions.
 static bool ContainsCompileOrAssembleAction(const Action *A) {
-  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
+  if (isa<CompileJobAction>(A) ||
+      isa<BackendJobAction>(A) ||
+      isa<AssembleJobAction>(A))
     return true;
 
   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
@@ -868,10 +879,7 @@
   // be handled once (in the order seen).
   llvm::StringSet<> ArchNames;
   SmallVector<const char *, 4> Archs;
-  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
-       it != ie; ++it) {
-    Arg *A = *it;
-
+  for (Arg *A : Args) {
     if (A->getOption().matches(options::OPT_arch)) {
       // Validate the option here; we don't save the type here because its
       // particular spelling may participate in other driver choices.
@@ -1019,10 +1027,7 @@
     assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
   }
 
-  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
-       it != ie; ++it) {
-    Arg *A = *it;
-
+  for (Arg *A : Args) {
     if (A->getOption().getKind() == Option::InputClass) {
       const char *Value = A->getValue();
       types::ID Ty = types::TY_INVALID;
@@ -1265,7 +1270,7 @@
         continue;
 
       // Otherwise construct the appropriate action.
-      Current = ConstructPhaseAction(Args, Phase, std::move(Current));
+      Current = ConstructPhaseAction(TC, Args, Phase, std::move(Current));
       if (Current->getType() == types::TY_Nothing)
         break;
     }
@@ -1291,7 +1296,8 @@
 }
 
 std::unique_ptr<Action>
-Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
+Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
+                             phases::ID Phase,
                              std::unique_ptr<Action> Input) const {
   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
   // Build the appropriate action.
@@ -1346,17 +1352,21 @@
     if (Args.hasArg(options::OPT_verify_pch))
       return llvm::make_unique<VerifyPCHJobAction>(std::move(Input),
                                                    types::TY_Nothing);
-    if (IsUsingLTO(Args)) {
+    return llvm::make_unique<CompileJobAction>(std::move(Input),
+                                               types::TY_LLVM_BC);
+  }
+  case phases::Backend: {
+    if (IsUsingLTO(TC, Args)) {
       types::ID Output =
         Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
-      return llvm::make_unique<CompileJobAction>(std::move(Input), Output);
+      return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
     }
     if (Args.hasArg(options::OPT_emit_llvm)) {
       types::ID Output =
         Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
-      return llvm::make_unique<CompileJobAction>(std::move(Input), Output);
+      return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
     }
-    return llvm::make_unique<CompileJobAction>(std::move(Input),
+    return llvm::make_unique<BackendJobAction>(std::move(Input),
                                                types::TY_PP_Asm);
   }
   case phases::Assemble:
@@ -1367,7 +1377,10 @@
   llvm_unreachable("invalid phase in ConstructPhaseAction");
 }
 
-bool Driver::IsUsingLTO(const ArgList &Args) const {
+bool Driver::IsUsingLTO(const ToolChain &TC, const ArgList &Args) const {
+  if (TC.getSanitizerArgs().needsLTO())
+    return true;
+
   if (Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
     return true;
 
@@ -1383,9 +1396,8 @@
   // files.
   if (FinalOutput) {
     unsigned NumOutputs = 0;
-    for (ActionList::const_iterator it = C.getActions().begin(),
-           ie = C.getActions().end(); it != ie; ++it)
-      if ((*it)->getType() != types::TY_Nothing)
+    for (const Action *A : C.getActions())
+      if (A->getType() != types::TY_Nothing)
         ++NumOutputs;
 
     if (NumOutputs > 1) {
@@ -1396,19 +1408,12 @@
 
   // Collect the list of architectures.
   llvm::StringSet<> ArchNames;
-  if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) {
-    for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
-         it != ie; ++it) {
-      Arg *A = *it;
+  if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
+    for (const Arg *A : C.getArgs())
       if (A->getOption().matches(options::OPT_arch))
         ArchNames.insert(A->getValue());
-    }
-  }
 
-  for (ActionList::const_iterator it = C.getActions().begin(),
-         ie = C.getActions().end(); it != ie; ++it) {
-    Action *A = *it;
-
+  for (Action *A : C.getActions()) {
     // If we are linking an image for multiple archs then the linker wants
     // -arch_multiple and -final_output <final image name>. Unfortunately, this
     // doesn't fit in cleanly because we have to pass this information down.
@@ -1420,7 +1425,7 @@
       if (FinalOutput)
         LinkingOutput = FinalOutput->getValue();
       else
-        LinkingOutput = DefaultImageName.c_str();
+        LinkingOutput = getDefaultImageName();
     }
 
     InputInfo II;
@@ -1444,10 +1449,7 @@
   // Claim --driver-mode, it was handled earlier.
   (void) C.getArgs().hasArg(options::OPT_driver_mode);
 
-  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
-       it != ie; ++it) {
-    Arg *A = *it;
-
+  for (Arg *A : C.getArgs()) {
     // FIXME: It would be nice to be able to send the argument to the
     // DiagnosticsEngine, so that extra values, position, and so on could be
     // printed.
@@ -1479,8 +1481,8 @@
   }
 }
 
-static const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC,
-                                    const JobAction *JA,
+static const Tool *SelectToolForJob(Compilation &C, bool SaveTemps,
+                                    const ToolChain *TC, const JobAction *JA,
                                     const ActionList *&Inputs) {
   const Tool *ToolForJob = nullptr;
 
@@ -1489,17 +1491,38 @@
   // compiler input.
 
   if (TC->useIntegratedAs() &&
-      !C.getArgs().hasArg(options::OPT_save_temps) &&
+      !SaveTemps &&
       !C.getArgs().hasArg(options::OPT_via_file_asm) &&
       !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
       !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
       isa<AssembleJobAction>(JA) &&
-      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
-    const Tool *Compiler =
-      TC->SelectTool(cast<JobAction>(**Inputs->begin()));
+      Inputs->size() == 1 && isa<BackendJobAction>(*Inputs->begin())) {
+    // A BackendJob is always preceded by a CompileJob, and without
+    // -save-temps they will always get combined together, so instead of
+    // checking the backend tool, check if the tool for the CompileJob
+    // has an integrated assembler.
+    const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
+    JobAction *CompileJA = cast<CompileJobAction>(*BackendInputs->begin());
+    const Tool *Compiler = TC->SelectTool(*CompileJA);
     if (!Compiler)
       return nullptr;
     if (Compiler->hasIntegratedAssembler()) {
+      Inputs = &(*BackendInputs)[0]->getInputs();
+      ToolForJob = Compiler;
+    }
+  }
+
+  // A backend job should always be combined with the preceding compile job
+  // unless OPT_save_temps is enabled and the compiler is capable of emitting
+  // LLVM IR as an intermediate output.
+  if (isa<BackendJobAction>(JA)) {
+    // Check if the compiler supports emitting LLVM IR.
+    assert(Inputs->size() == 1);
+    JobAction *CompileJA = cast<CompileJobAction>(*Inputs->begin());
+    const Tool *Compiler = TC->SelectTool(*CompileJA);
+    if (!Compiler)
+      return nullptr;
+    if (!Compiler->canEmitIR() || !SaveTemps) {
       Inputs = &(*Inputs)[0]->getInputs();
       ToolForJob = Compiler;
     }
@@ -1515,7 +1538,7 @@
   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
       !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
-      !C.getArgs().hasArg(options::OPT_save_temps) &&
+      !SaveTemps &&
       !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
       ToolForJob->hasIntegratedCPP())
     Inputs = &(*Inputs)[0]->getInputs();
@@ -1563,14 +1586,13 @@
   const ActionList *Inputs = &A->getInputs();
 
   const JobAction *JA = cast<JobAction>(A);
-  const Tool *T = SelectToolForJob(C, TC, JA, Inputs);
+  const Tool *T = SelectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs);
   if (!T)
     return;
 
   // Only use pipes when there is exactly one input.
   InputInfoList InputInfos;
-  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
-       it != ie; ++it) {
+  for (const Action *Input : *Inputs) {
     // Treat dsymutil and verify sub-jobs as being at the top-level too, they
     // shouldn't get temporary output names.
     // FIXME: Clean this up.
@@ -1579,7 +1601,7 @@
       SubJobAtTopLevel = true;
 
     InputInfo II;
-    BuildJobsForAction(C, *it, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
+    BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
                        LinkingOutput, II);
     InputInfos.push_back(II);
   }
@@ -1615,6 +1637,11 @@
   }
 }
 
+const char *Driver::getDefaultImageName() const {
+  llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
+  return Target.isOSWindows() ? "a.exe" : "a.out";
+}
+
 /// \brief Create output filename based on ArgValue, which could either be a
 /// full filename, filename without extension, or a directory. If ArgValue
 /// does not provide a filename, then use BaseName, and use the extension
@@ -1690,7 +1717,7 @@
   }
 
   // Output to a temporary file?
-  if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps) &&
+  if ((!AtTopLevel && !isSaveTempsEnabled() &&
         !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
       CCGenDiagnostics) {
     StringRef Name = llvm::sys::path::filename(BaseInput);
@@ -1733,12 +1760,12 @@
       NamedOutput = MakeCLOutputFilename(C.getArgs(), "", BaseName,
                                          types::TY_Image);
     } else if (MultipleArchs && BoundArch) {
-      SmallString<128> Output(DefaultImageName.c_str());
+      SmallString<128> Output(getDefaultImageName());
       Output += "-";
       Output.append(BoundArch);
       NamedOutput = C.getArgs().MakeArgString(Output.c_str());
     } else
-      NamedOutput = DefaultImageName.c_str();
+      NamedOutput = getDefaultImageName();
   } else {
     const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
     assert(Suffix && "All types used for output should have a suffix.");
@@ -1751,16 +1778,31 @@
       Suffixed += "-";
       Suffixed.append(BoundArch);
     }
+    // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
+    // the unoptimized bitcode so that it does not get overwritten by the ".bc"
+    // optimized bitcode output.
+    if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
+        JA.getType() == types::TY_LLVM_BC)
+      Suffixed += ".tmp";
     Suffixed += '.';
     Suffixed += Suffix;
     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
   }
 
+  // Prepend object file path if -save-temps=obj
+  if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
+      JA.getType() != types::TY_PCH) {
+    Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
+    SmallString<128> TempPath(FinalOutput->getValue());
+    llvm::sys::path::remove_filename(TempPath);
+    StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
+    llvm::sys::path::append(TempPath, OutputFileName);
+    NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
+  }
+
   // If we're saving temps and the temp file conflicts with the input file,
   // then avoid overwriting input file.
-  if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
-      NamedOutput == BaseName) {
-
+  if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
     bool SameFile = false;
     SmallString<256> Result;
     llvm::sys::fs::current_path(Result);
@@ -2063,7 +2105,7 @@
         TC = new toolchains::Generic_ELF(*this, Target, Args);
         break;
       }
-      if (Target.getObjectFormat() == llvm::Triple::MachO) {
+      if (Target.isOSBinFormatMachO()) {
         TC = new toolchains::MachO(*this, Target, Args);
         break;
       }
@@ -2083,7 +2125,7 @@
 
   // Otherwise make sure this is an action clang understands.
   if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
-      !isa<CompileJobAction>(JA))
+      !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
     return false;
 
   return true;
diff --git a/lib/Driver/Job.cpp b/lib/Driver/Job.cpp
index c5b3f5a..66434cf 100644
--- a/lib/Driver/Job.cpp
+++ b/lib/Driver/Job.cpp
@@ -217,8 +217,7 @@
 
   if (ResponseFile == nullptr) {
     Argv.push_back(Executable);
-    for (size_t i = 0, e = Arguments.size(); i != e; ++i)
-      Argv.push_back(Arguments[i]);
+    Argv.append(Arguments.begin(), Arguments.end());
     Argv.push_back(nullptr);
 
     return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
diff --git a/lib/Driver/MSVCToolChain.cpp b/lib/Driver/MSVCToolChain.cpp
index 692d01d5..874e540 100644
--- a/lib/Driver/MSVCToolChain.cpp
+++ b/lib/Driver/MSVCToolChain.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Process.h"
+#include <cstdio>
 
 // Include the necessary headers to interface with the Windows registry and
 // environment.
@@ -31,7 +32,9 @@
 #ifdef USE_WIN32
   #define WIN32_LEAN_AND_MEAN
   #define NOGDI
-  #define NOMINMAX
+  #ifndef NOMINMAX
+    #define NOMINMAX
+  #endif
   #include <windows.h>
 #endif
 
@@ -43,6 +46,9 @@
 MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple& Triple,
                              const ArgList &Args)
   : ToolChain(D, Triple, Args) {
+  getProgramPaths().push_back(getDriver().getInstalledDir());
+  if (getDriver().getInstalledDir() != getDriver().Dir)
+    getProgramPaths().push_back(getDriver().Dir);
 }
 
 Tool *MSVCToolChain::buildLinker() const {
@@ -207,7 +213,7 @@
       "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
       "InstallationFolder", path, &sdkVersion);
   if (!sdkVersion.empty())
-    ::sscanf(sdkVersion.c_str(), "v%d.%d", &major, &minor);
+    std::sscanf(sdkVersion.c_str(), "v%d.%d", &major, &minor);
   return hasSDKDir && !path.empty();
 }
 
diff --git a/lib/Driver/Phases.cpp b/lib/Driver/Phases.cpp
index 155e53b..7ae2708 100644
--- a/lib/Driver/Phases.cpp
+++ b/lib/Driver/Phases.cpp
@@ -18,6 +18,7 @@
   case Preprocess: return "preprocessor";
   case Precompile: return "precompiler";
   case Compile: return "compiler";
+  case Backend: return "backend";
   case Assemble: return "assembler";
   case Link: return "linker";
   }
diff --git a/lib/Driver/SanitizerArgs.cpp b/lib/Driver/SanitizerArgs.cpp
index 4460f9f..11b9288 100644
--- a/lib/Driver/SanitizerArgs.cpp
+++ b/lib/Driver/SanitizerArgs.cpp
@@ -42,8 +42,13 @@
 #include "clang/Basic/Sanitizers.def"
   NeedsUbsanRt = Undefined | Integer,
   NotAllowedWithTrap = Vptr,
-  HasZeroBaseShadow = Thread | Memory | DataFlow,
-  NeedsUnwindTables = Address | Thread | Memory | DataFlow
+  RequiresPIE = Memory | DataFlow,
+  NeedsUnwindTables = Address | Thread | Memory | DataFlow,
+  SupportsCoverage = Address | Memory | Leak | Undefined | Integer,
+  RecoverableByDefault = Undefined | Integer,
+  Unrecoverable = Address | Unreachable | Return,
+  LegacyFsanitizeRecoverMask = Undefined | Integer,
+  NeedsLTO = CFIVptr,
 };
 }
 
@@ -83,12 +88,6 @@
 static unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                                bool DiagnoseErrors);
 
-/// Parse a single flag of the form -f[no]sanitize=.
-/// Sets the masks defining required change of the set of sanitizers.
-/// Returns true if the flag was parsed successfully.
-static bool parseArgument(const Driver &D, const llvm::opt::Arg *A,
-                          unsigned &Add, unsigned &Remove, bool DiagnoseErrors);
-
 /// Produce an argument string from ArgList \p Args, which shows how it
 /// provides some sanitizer kind from \p Mask. For example, the argument list
 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
@@ -122,12 +121,14 @@
   bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
   bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
   bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
+  bool IsMIPS64 = TC.getTriple().getArch() == llvm::Triple::mips64 ||
+                  TC.getTriple().getArch() == llvm::Triple::mips64el;
 
   unsigned Unsupported = 0;
-  if (!(IsLinux && IsX86_64)) {
+  if (!(IsLinux && (IsX86_64 || IsMIPS64))) {
     Unsupported |= Memory | DataFlow;
   }
-  if (!((IsLinux || IsFreeBSD) && IsX86_64)) {
+  if (!((IsLinux || IsFreeBSD) && (IsX86_64 || IsMIPS64))) {
     Unsupported |= Thread;
   }
   if (!(IsLinux && (IsX86 || IsX86_64))) {
@@ -140,18 +141,22 @@
   return !UbsanTrapOnError && hasOneOf(Sanitizers, NeedsUbsanRt);
 }
 
-bool SanitizerArgs::hasZeroBaseShadow() const {
-  return AsanZeroBaseShadow || hasOneOf(Sanitizers, HasZeroBaseShadow);
+bool SanitizerArgs::requiresPIE() const {
+  return AsanZeroBaseShadow || hasOneOf(Sanitizers, RequiresPIE);
 }
 
 bool SanitizerArgs::needsUnwindTables() const {
   return hasOneOf(Sanitizers, NeedsUnwindTables);
 }
 
+bool SanitizerArgs::needsLTO() const {
+  return hasOneOf(Sanitizers, CFIVptr);
+}
+
 void SanitizerArgs::clear() {
   Sanitizers.clear();
-  SanitizeRecover = false;
-  BlacklistFile = "";
+  RecoverableSanitizers.clear();
+  BlacklistFiles.clear();
   SanitizeCoverage = 0;
   MsanTrackOrigins = 0;
   AsanFieldPadding = 0;
@@ -171,43 +176,111 @@
                                 // Used to deduplicate diagnostics.
   unsigned Kinds = 0;
   unsigned NotSupported = getToolchainUnsupportedKinds(TC);
+  ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
+
   const Driver &D = TC.getDriver();
   for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
        I != E; ++I) {
-    unsigned Add, Remove;
-    if (!parseArgument(D, *I, Add, Remove, true))
-      continue;
-    (*I)->claim();
+    const auto *Arg = *I;
+    if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
+      Arg->claim();
+      unsigned Add = parseArgValues(D, Arg, true);
 
-    AllRemove |= expandGroups(Remove);
+      // Avoid diagnosing any sanitizer which is disabled later.
+      Add &= ~AllRemove;
+      // At this point we have not expanded groups, so any unsupported
+      // sanitizers in Add are those which have been explicitly enabled.
+      // Diagnose them.
+      if (unsigned KindsToDiagnose = Add & NotSupported & ~DiagnosedKinds) {
+        // Only diagnose the new kinds.
+        std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
+        D.Diag(diag::err_drv_unsupported_opt_for_target)
+            << Desc << TC.getTriple().str();
+        DiagnosedKinds |= KindsToDiagnose;
+      }
+      Add &= ~NotSupported;
 
-    // Avoid diagnosing any sanitizer which is disabled later.
-    Add &= ~AllRemove;
+      // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
+      // so we don't error out if -fno-rtti and -fsanitize=undefined were
+      // passed.
+      if (Add & SanitizeKind::Vptr &&
+          (RTTIMode == ToolChain::RM_DisabledImplicitly ||
+           RTTIMode == ToolChain::RM_DisabledExplicitly)) {
+        if (RTTIMode == ToolChain::RM_DisabledImplicitly)
+          // Warn about not having rtti enabled if the vptr sanitizer is
+          // explicitly enabled
+          D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
+        else {
+          const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
+          assert(NoRTTIArg &&
+                 "RTTI disabled explicitly but we have no argument!");
+          D.Diag(diag::err_drv_argument_not_allowed_with)
+              << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
+        }
 
-    // At this point we have not expanded groups, so any unsupported sanitizers
-    // in Add are those which have been explicitly enabled. Diagnose them.
-    if (unsigned KindsToDiagnose = Add & NotSupported & ~DiagnosedKinds) {
-      // Only diagnose the new kinds.
-      std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
-      D.Diag(diag::err_drv_unsupported_opt_for_target) << Desc
-                                                       << TC.getTriple().str();
-      DiagnosedKinds |= KindsToDiagnose;
+        // Take out the Vptr sanitizer from the enabled sanitizers
+        AllRemove |= SanitizeKind::Vptr;
+      }
+
+      Add = expandGroups(Add);
+      // Group expansion may have enabled a sanitizer which is disabled later.
+      Add &= ~AllRemove;
+      // Silently discard any unsupported sanitizers implicitly enabled through
+      // group expansion.
+      Add &= ~NotSupported;
+
+      Kinds |= Add;
+    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
+      Arg->claim();
+      unsigned Remove = parseArgValues(D, Arg, true);
+      AllRemove |= expandGroups(Remove);
     }
-    Add &= ~NotSupported;
-
-    Add = expandGroups(Add);
-    // Group expansion may have enabled a sanitizer which is disabled later.
-    Add &= ~AllRemove;
-    // Silently discard any unsupported sanitizers implicitly enabled through
-    // group expansion.
-    Add &= ~NotSupported;
-
-    Kinds |= Add;
   }
   addAllOf(Sanitizers, Kinds);
 
-  SanitizeRecover = Args.hasFlag(options::OPT_fsanitize_recover,
-                                 options::OPT_fno_sanitize_recover, true);
+  // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
+  // is disabled.
+  if (Sanitizers.has(SanitizerKind::Vptr) &&
+      (RTTIMode == ToolChain::RM_DisabledImplicitly ||
+       RTTIMode == ToolChain::RM_DisabledExplicitly)) {
+    Kinds &= ~SanitizeKind::Vptr;
+    Sanitizers.set(SanitizerKind::Vptr, 0);
+  }
+
+  // Parse -f(no-)?sanitize-recover flags.
+  unsigned RecoverableKinds = RecoverableByDefault;
+  unsigned DiagnosedUnrecoverableKinds = 0;
+  for (const auto *Arg : Args) {
+    if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
+      // FIXME: Add deprecation notice, and then remove this flag.
+      RecoverableKinds |= expandGroups(LegacyFsanitizeRecoverMask);
+      Arg->claim();
+    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
+      // FIXME: Add deprecation notice, and then remove this flag.
+      RecoverableKinds &= ~expandGroups(LegacyFsanitizeRecoverMask);
+      Arg->claim();
+    } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
+      unsigned Add = parseArgValues(D, Arg, true);
+      // Report error if user explicitly tries to recover from unrecoverable
+      // sanitizer.
+      if (unsigned KindsToDiagnose =
+              Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
+        SanitizerSet SetToDiagnose;
+        addAllOf(SetToDiagnose, KindsToDiagnose);
+        D.Diag(diag::err_drv_unsupported_option_argument)
+            << Arg->getOption().getName() << toString(SetToDiagnose);
+        DiagnosedUnrecoverableKinds |= KindsToDiagnose;
+      }
+      RecoverableKinds |= expandGroups(Add);
+      Arg->claim();
+    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
+      RecoverableKinds &= ~expandGroups(parseArgValues(D, Arg, true));
+      Arg->claim();
+    }
+  }
+  RecoverableKinds &= Kinds;
+  RecoverableKinds &= ~Unrecoverable;
+  addAllOf(RecoverableSanitizers, RecoverableKinds);
 
   UbsanTrapOnError =
     Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
@@ -250,30 +323,34 @@
   // -f(-no)sanitize=leak should change whether leak detection is enabled by
   // default in ASan?
 
-  // Parse -f(no-)sanitize-blacklist options.
-  if (Arg *BLArg = Args.getLastArg(options::OPT_fsanitize_blacklist,
-                                   options::OPT_fno_sanitize_blacklist)) {
-    if (BLArg->getOption().matches(options::OPT_fsanitize_blacklist)) {
-      std::string BLPath = BLArg->getValue();
-      if (llvm::sys::fs::exists(BLPath)) {
-        // Validate the blacklist format.
-        std::string BLError;
-        std::unique_ptr<llvm::SpecialCaseList> SCL(
-            llvm::SpecialCaseList::create(BLPath, BLError));
-        if (!SCL.get())
-          D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
-        else
-          BlacklistFile = BLPath;
-      } else {
-        D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
-      }
-    }
-  } else {
-    // If no -fsanitize-blacklist option is specified, try to look up for
-    // blacklist in the resource directory.
+  // Setup blacklist files.
+  // Add default blacklist from resource directory.
+  {
     std::string BLPath;
     if (getDefaultBlacklist(D, BLPath) && llvm::sys::fs::exists(BLPath))
-      BlacklistFile = BLPath;
+      BlacklistFiles.push_back(BLPath);
+  }
+  // Parse -f(no-)sanitize-blacklist options.
+  for (const auto *Arg : Args) {
+    if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
+      Arg->claim();
+      std::string BLPath = Arg->getValue();
+      if (llvm::sys::fs::exists(BLPath))
+        BlacklistFiles.push_back(BLPath);
+      else
+        D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
+    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
+      Arg->claim();
+      BlacklistFiles.clear();
+    }
+  }
+  // Validate blacklists format.
+  {
+    std::string BLError;
+    std::unique_ptr<llvm::SpecialCaseList> SCL(
+        llvm::SpecialCaseList::create(BlacklistFiles, BLError));
+    if (!SCL.get())
+      D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
   }
 
   // Parse -f[no-]sanitize-memory-track-origins[=level] options.
@@ -283,7 +360,7 @@
                             options::OPT_fsanitize_memory_track_origins,
                             options::OPT_fno_sanitize_memory_track_origins)) {
       if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
-        MsanTrackOrigins = 1;
+        MsanTrackOrigins = 2;
       } else if (A->getOption().matches(
                      options::OPT_fno_sanitize_memory_track_origins)) {
         MsanTrackOrigins = 0;
@@ -297,8 +374,8 @@
     }
   }
 
-  // Parse -fsanitize-coverage=N
-  if (NeedsAsan) {  // Currently asan is required.
+  // Parse -fsanitize-coverage=N. Currently one of asan/msan/lsan is required.
+  if (hasOneOf(Sanitizers, SupportsCoverage)) {
     if (Arg *A = Args.getLastArg(options::OPT_fsanitize_coverage)) {
       StringRef S = A->getValue();
       // Legal values are 0..4.
@@ -363,15 +440,16 @@
     return;
   CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
 
-  if (!SanitizeRecover)
-    CmdArgs.push_back("-fno-sanitize-recover");
+  if (!RecoverableSanitizers.empty())
+    CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
+                                         toString(RecoverableSanitizers)));
 
   if (UbsanTrapOnError)
     CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
 
-  if (!BlacklistFile.empty()) {
+  for (const auto &BLPath : BlacklistFiles) {
     SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
-    BlacklistOpt += BlacklistFile;
+    BlacklistOpt += BLPath;
     CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
   }
 
@@ -384,8 +462,13 @@
   if (SanitizeCoverage)
     CmdArgs.push_back(Args.MakeArgString("-fsanitize-coverage=" +
                                          llvm::utostr(SanitizeCoverage)));
-  // Workaround for PR16386.
-  if (Sanitizers.has(SanitizerKind::Memory))
+  // MSan: Workaround for PR16386.
+  // ASan: This is mainly to help LSan with cases such as
+  // https://code.google.com/p/address-sanitizer/issues/detail?id=373
+  // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
+  // affect compilation.
+  if (Sanitizers.has(SanitizerKind::Memory) ||
+      Sanitizers.has(SanitizerKind::Address))
     CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
 }
 
@@ -427,30 +510,29 @@
 
 unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                         bool DiagnoseErrors) {
-  unsigned Kind = 0;
+  assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
+          A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
+          A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
+          A->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) &&
+         "Invalid argument in parseArgValues!");
+  unsigned Kinds = 0;
   for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
-    if (unsigned K = parseValue(A->getValue(I)))
-      Kind |= K;
+    const char *Value = A->getValue(I);
+    unsigned Kind;
+    // Special case: don't accept -fsanitize=all.
+    if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
+        0 == strcmp("all", Value))
+      Kind = 0;
+    else
+      Kind = parseValue(Value);
+
+    if (Kind)
+      Kinds |= Kind;
     else if (DiagnoseErrors)
       D.Diag(clang::diag::err_drv_unsupported_option_argument)
-        << A->getOption().getName() << A->getValue(I);
+          << A->getOption().getName() << Value;
   }
-  return Kind;
-}
-
-bool parseArgument(const Driver &D, const llvm::opt::Arg *A, unsigned &Add,
-                   unsigned &Remove, bool DiagnoseErrors) {
-  Add = 0;
-  Remove = 0;
-  if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
-    Add = parseArgValues(D, A, DiagnoseErrors);
-    return true;
-  }
-  if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) {
-    Remove = parseArgValues(D, A, DiagnoseErrors);
-    return true;
-  }
-  return false;
+  return Kinds;
 }
 
 std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
@@ -458,11 +540,15 @@
   for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
                                                   E = Args.rend();
        I != E; ++I) {
-    unsigned Add, Remove;
-    if (parseArgument(D, *I, Add, Remove, false) &&
-        (expandGroups(Add) & Mask))
-      return describeSanitizeArg(*I, Mask);
-    Mask &= ~Remove;
+    const auto *Arg = *I;
+    if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
+      unsigned AddKinds = expandGroups(parseArgValues(D, Arg, false));
+      if (AddKinds & Mask)
+        return describeSanitizeArg(Arg, Mask);
+    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
+      unsigned RemoveKinds = expandGroups(parseArgValues(D, Arg, false));
+      Mask &= ~RemoveKinds;
+    }
   }
   llvm_unreachable("arg list didn't provide expected value");
 }
diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp
index 6734ce7..5feeda4 100644
--- a/lib/Driver/ToolChain.cpp
+++ b/lib/Driver/ToolChain.cpp
@@ -26,14 +26,47 @@
 using namespace clang;
 using namespace llvm::opt;
 
+static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
+  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
+                         options::OPT_fno_rtti, options::OPT_frtti);
+}
+
+static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
+                                             const llvm::Triple &Triple,
+                                             const Arg *CachedRTTIArg) {
+  // Explicit rtti/no-rtti args
+  if (CachedRTTIArg) {
+    if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
+      return ToolChain::RM_EnabledExplicitly;
+    else
+      return ToolChain::RM_DisabledExplicitly;
+  }
+
+  // -frtti is default, except for the PS4 CPU.
+  if (!Triple.isPS4CPU())
+    return ToolChain::RM_EnabledImplicitly;
+
+  // On the PS4, turning on c++ exceptions turns on rtti.
+  // We're assuming that, if we see -fexceptions, rtti gets turned on.
+  Arg *Exceptions = Args.getLastArg(
+      options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
+      options::OPT_fexceptions, options::OPT_fno_exceptions);
+  if (Exceptions &&
+      (Exceptions->getOption().matches(options::OPT_fexceptions) ||
+       Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
+    return ToolChain::RM_EnabledImplicitly;
+
+  return ToolChain::RM_DisabledImplicitly;
+}
+
 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
                      const ArgList &Args)
-  : D(D), Triple(T), Args(Args) {
+    : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
+      CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
     if (!isThreadModelSupported(A->getValue()))
       D.Diag(diag::err_drv_invalid_thread_model_for_target)
-          << A->getValue()
-          << A->getAsString(Args);
+          << A->getValue() << A->getAsString(Args);
 }
 
 ToolChain::~ToolChain() {
@@ -129,6 +162,7 @@
   case Action::AnalyzeJobClass:
   case Action::MigrateJobClass:
   case Action::VerifyPCHJobClass:
+  case Action::BackendJobClass:
     return getClang();
   }
 
diff --git a/lib/Driver/ToolChains.cpp b/lib/Driver/ToolChains.cpp
index 17ef107..93e6db8 100644
--- a/lib/Driver/ToolChains.cpp
+++ b/lib/Driver/ToolChains.cpp
@@ -132,11 +132,11 @@
     .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5")
     .Case("xscale", "xscale")
     .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6")
-    .Case("cortex-m0", "armv6m")
+    .Cases("sc000", "cortex-m0", "cortex-m0plus", "cortex-m1", "armv6m")
     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7")
     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "armv7")
-    .Cases("cortex-r4", "cortex-r5", "armv7r")
-    .Case("cortex-m3", "armv7m")
+    .Cases("cortex-r4", "cortex-r5", "cortex-r7", "armv7r")
+    .Cases("sc300", "cortex-m3", "armv7m")
     .Cases("cortex-m4", "cortex-m7", "armv7em")
     .Case("swift", "armv7s")
     .Default(nullptr);
@@ -902,8 +902,7 @@
   // FIXME: It would be far better to avoid inserting those -static arguments,
   // but we can't check the deployment target in the translation code until
   // it is set here.
-  if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0) &&
-      getTriple().getArch() != llvm::Triple::aarch64) {
+  if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) {
     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
       Arg *A = *it;
       ++it;
@@ -1725,6 +1724,7 @@
 
   MultilibSet AndroidMipsMultilibs = MultilibSet()
     .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
+    .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
     .FilterOut(NonExistent);
 
   MultilibSet DebianMipsMultilibs;
@@ -1783,9 +1783,13 @@
   addMultilibFlag(isMips64(TargetArch), "m64", Flags);
   addMultilibFlag(isMips16(Args), "mips16", Flags);
   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
-  addMultilibFlag(CPUName == "mips32r2", "march=mips32r2", Flags);
+  addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
+                      CPUName == "mips32r5",
+                  "march=mips32r2", Flags);
+  addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
-  addMultilibFlag(CPUName == "mips64r2" || CPUName == "octeon",
+  addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
+                      CPUName == "mips64r5" || CPUName == "octeon",
                   "march=mips64r2", Flags);
   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
@@ -2068,8 +2072,11 @@
          getTriple().getArch() == llvm::Triple::armeb ||
          getTriple().getArch() == llvm::Triple::thumb ||
          getTriple().getArch() == llvm::Triple::thumbeb ||
+         getTriple().getArch() == llvm::Triple::ppc ||
          getTriple().getArch() == llvm::Triple::ppc64 ||
          getTriple().getArch() == llvm::Triple::ppc64le ||
+         getTriple().getArch() == llvm::Triple::sparc ||
+         getTriple().getArch() == llvm::Triple::sparcv9 ||
          getTriple().getArch() == llvm::Triple::systemz;
 }
 
@@ -2507,7 +2514,7 @@
 }
 
 bool FreeBSD::isPIEDefault() const {
-  return getSanitizerArgs().hasZeroBaseShadow();
+  return getSanitizerArgs().requiresPIE();
 }
 
 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
@@ -3152,7 +3159,8 @@
     SmallVector<StringRef, 5> dirs;
     CIncludeDirs.split(dirs, ":");
     for (StringRef dir : dirs) {
-      StringRef Prefix = llvm::sys::path::is_absolute(dir) ? SysRoot : "";
+      StringRef Prefix =
+          llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
     }
     return;
@@ -3383,7 +3391,7 @@
 }
 
 bool Linux::isPIEDefault() const {
-  return getSanitizerArgs().hasZeroBaseShadow();
+  return getSanitizerArgs().requiresPIE();
 }
 
 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
diff --git a/lib/Driver/ToolChains.h b/lib/Driver/ToolChains.h
index 876bb01..90893c3 100644
--- a/lib/Driver/ToolChains.h
+++ b/lib/Driver/ToolChains.h
@@ -256,7 +256,7 @@
 
   bool IsBlocksDefault() const override {
     // Always allow blocks on Apple; users interested in versioning are
-    // expected to use /usr/include/Blocks.h.
+    // expected to use /usr/include/Block.h.
     return true;
   }
   bool IsIntegratedAssemblerDefault() const override {
@@ -362,8 +362,7 @@
                          llvm::opt::ArgStringList &CmdArgs) const override;
 
   bool isKernelStatic() const override {
-    return !isTargetIPhoneOS() || isIPhoneOSVersionLT(6, 0) ||
-           getTriple().getArch() == llvm::Triple::aarch64;
+    return !isTargetIPhoneOS() || isIPhoneOSVersionLT(6, 0);
   }
 
 protected:
@@ -534,17 +533,6 @@
     return 2;
   }
 
-  virtual bool IsIntegratedAssemblerDefault() const override {
-    switch (getTriple().getArch()) {
-    case llvm::Triple::ppc:
-    case llvm::Triple::sparc:
-    case llvm::Triple::sparcv9:
-      return true;
-    default:
-      return Generic_ELF::IsIntegratedAssemblerDefault();
-    }
-  }
-
 protected:
   Tool *buildAssembler() const override;
   Tool *buildLinker() const override;
@@ -586,14 +574,6 @@
   void
   AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
                                llvm::opt::ArgStringList &CC1Args) const override;
-  bool IsIntegratedAssemblerDefault() const override {
-    switch (getTriple().getArch()) {
-    case llvm::Triple::ppc:
-      return true;
-    default:
-      return Generic_ELF::IsIntegratedAssemblerDefault();
-    }
-  }
 
   bool UseSjLjExceptions() const override;
   bool isPIEDefault() const override;
@@ -618,14 +598,6 @@
   bool IsUnwindTablesDefault() const override {
     return true;
   }
-  bool IsIntegratedAssemblerDefault() const override {
-    switch (getTriple().getArch()) {
-    case llvm::Triple::ppc:
-      return true;
-    default:
-      return Generic_ELF::IsIntegratedAssemblerDefault();
-    }
-  }
 
 protected:
   Tool *buildAssembler() const override;
diff --git a/lib/Driver/Tools.cpp b/lib/Driver/Tools.cpp
index 28b9068..b0e581b 100644
--- a/lib/Driver/Tools.cpp
+++ b/lib/Driver/Tools.cpp
@@ -10,9 +10,11 @@
 #include "Tools.h"
 #include "InputInfo.h"
 #include "ToolChains.h"
+#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/ObjCRuntime.h"
 #include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
 #include "clang/Driver/Action.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
@@ -32,13 +34,16 @@
 #include "llvm/Support/Compression.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/Format.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/raw_ostream.h"
 
+#ifdef LLVM_ON_UNIX
+#include <unistd.h> // For getuid().
+#endif
+
 using namespace clang::driver;
 using namespace clang::driver::tools;
 using namespace clang;
@@ -589,6 +594,12 @@
     Features.push_back("+crypto");
   } else if (FPU == "neon") {
     Features.push_back("+neon");
+  } else if (FPU == "neon-vfpv3") {
+    Features.push_back("+vfp3");
+    Features.push_back("+neon");
+  } else if (FPU == "neon-vfpv4") {
+    Features.push_back("+neon");
+    Features.push_back("+vfp4");
   } else if (FPU == "none") {
     Features.push_back("-vfp2");
     Features.push_back("-vfp3");
@@ -759,6 +770,7 @@
   // Select the ABI to use.
   //
   // FIXME: Support -meabi.
+  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
   const char *ABIName = nullptr;
   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
     ABIName = A->getValue();
@@ -766,8 +778,7 @@
     // The backend is hardwired to assume AAPCS for M-class processors, ensure
     // the frontend matches that.
     if (Triple.getEnvironment() == llvm::Triple::EABI ||
-        (Triple.getOS() == llvm::Triple::UnknownOS &&
-         Triple.getObjectFormat() == llvm::Triple::MachO) ||
+        Triple.getOS() == llvm::Triple::UnknownOS ||
         StringRef(CPUName).startswith("cortex-m")) {
       ABIName = "aapcs";
     } else {
@@ -932,6 +943,19 @@
       CmdArgs.push_back("-aarch64-no-strict-align");
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
+                               options::OPT_mno_fix_cortex_a53_835769)) {
+    CmdArgs.push_back("-backend-option");
+    if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
+      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
+    else
+      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
+  } else if (Triple.getEnvironment() == llvm::Triple::Android) {
+    // Enabled A53 errata (835769) workaround by default on android
+    CmdArgs.push_back("-backend-option");
+    CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
+  }
+
   // Setting -mno-global-merge disables the codegen global merge pass. Setting
   // -mglobal-merge has no effect as the pass is enabled by default.
   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
@@ -939,6 +963,11 @@
     if (A->getOption().matches(options::OPT_mno_global_merge))
       CmdArgs.push_back("-mno-global-merge");
   }
+
+  if (Args.hasArg(options::OPT_ffixed_x18)) {
+    CmdArgs.push_back("-backend-option");
+    CmdArgs.push_back("-aarch64-reserve-x18");
+  }
 }
 
 // Get CPU and ABI names. They are not independent
@@ -958,6 +987,10 @@
     DefMips64CPU = "mips64r6";
   }
 
+  // MIPS3 is the default for mips64*-unknown-openbsd.
+  if (Triple.getOS() == llvm::Triple::OpenBSD)
+    DefMips64CPU = "mips3";
+
   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
                                options::OPT_mcpu_EQ))
     CPUName = A->getValue();
@@ -1067,17 +1100,6 @@
   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   ABIName = getGnuCompatibleMipsABIName(ABIName);
 
-  // Always override the backend's default ABI.
-  std::string ABIFeature = llvm::StringSwitch<StringRef>(ABIName)
-                               .Case("32", "+o32")
-                               .Case("n32", "+n32")
-                               .Case("64", "+n64")
-                               .Case("eabi", "+eabi")
-                               .Default(("+" + ABIName).str());
-  Features.push_back("-o32");
-  Features.push_back("-n64");
-  Features.push_back(Args.MakeArgString(ABIFeature));
-
   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
                    options::OPT_mabicalls, "noabicalls");
 
@@ -1416,6 +1438,10 @@
     return Is64Bit ? "core2" : "yonah";
   }
 
+  // Set up default CPU name for PS4 compilers.
+  if (Triple.isPS4CPU())
+    return "btver2";
+
   // On Android use targets compatible with gcc
   if (Triple.getEnvironment() == llvm::Triple::Android)
     return Is64Bit ? "x86-64" : "i686";
@@ -1499,6 +1525,7 @@
     return getSystemZTargetCPU(Args);
 
   case llvm::Triple::r600:
+  case llvm::Triple::amdgcn:
     return getR600TargetGPU(Args);
   }
 }
@@ -1509,7 +1536,7 @@
   // as gold requires -plugin to come before any -plugin-opt that -Wl might
   // forward.
   CmdArgs.push_back("-plugin");
-  std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
+  std::string Plugin = ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
   CmdArgs.push_back(Args.MakeArgString(Plugin));
 
   // Try to pass driver level flags relevant to LTO code generation down to
@@ -1704,7 +1731,7 @@
                               std::vector<const char *> &Features) {
   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
   CPU = Split.first;
-  if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57") {
+  if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" || CPU == "cortex-a72") {
     Features.push_back("+neon");
     Features.push_back("+crc");
     Features.push_back("+crypto");
@@ -1893,55 +1920,28 @@
            Triple.getArch() == llvm::Triple::arm));
 }
 
-namespace {
-  struct ExceptionSettings {
-    bool ExceptionsEnabled;
-    bool ShouldUseExceptionTables;
-    ExceptionSettings() : ExceptionsEnabled(false),
-                          ShouldUseExceptionTables(false) {}
-  };
-} // end anonymous namespace.
-
 // exceptionSettings() exists to share the logic between -cc1 and linker
 // invocations.
-static ExceptionSettings exceptionSettings(const ArgList &Args,
-                                           const llvm::Triple &Triple) {
-  ExceptionSettings ES;
-
-  // Are exceptions enabled by default?
-  ES.ExceptionsEnabled = (Triple.getArch() != llvm::Triple::xcore);
-
-  // This keeps track of whether exceptions were explicitly turned on or off.
-  bool DidHaveExplicitExceptionFlag = false;
-
+static bool exceptionSettings(const ArgList &Args, const llvm::Triple &Triple) {
   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
-                               options::OPT_fno_exceptions)) {
+                               options::OPT_fno_exceptions))
     if (A->getOption().matches(options::OPT_fexceptions))
-      ES.ExceptionsEnabled = true;
-    else
-      ES.ExceptionsEnabled = false;
+      return true;
 
-    DidHaveExplicitExceptionFlag = true;
-  }
-
-  // Exception tables and cleanups can be enabled with -fexceptions even if the
-  // language itself doesn't support exceptions.
-  if (ES.ExceptionsEnabled && DidHaveExplicitExceptionFlag)
-    ES.ShouldUseExceptionTables = true;
-
-  return ES;
+  return false;
 }
 
-/// addExceptionArgs - Adds exception related arguments to the driver command
-/// arguments. There's a master flag, -fexceptions and also language specific
-/// flags to enable/disable C++ and Objective-C exceptions.
-/// This makes it possible to for example disable C++ exceptions but enable
-/// Objective-C exceptions.
+/// Adds exception related arguments to the driver command arguments. There's a
+/// master flag, -fexceptions and also language specific flags to enable/disable
+/// C++ and Objective-C exceptions. This makes it possible to for example
+/// disable C++ exceptions but enable Objective-C exceptions.
 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
-                             const llvm::Triple &Triple,
-                             bool KernelOrKext,
+                             const ToolChain &TC, bool KernelOrKext,
                              const ObjCRuntime &objcRuntime,
                              ArgStringList &CmdArgs) {
+  const Driver &D = TC.getDriver();
+  const llvm::Triple &Triple = TC.getTriple();
+
   if (KernelOrKext) {
     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
     // arguments now to avoid warnings about unused arguments.
@@ -1954,8 +1954,8 @@
     return;
   }
 
-   // Gather the exception settings from the command line arguments.
-   ExceptionSettings ES = exceptionSettings(Args, Triple);
+  // Gather the exception settings from the command line arguments.
+  bool EH = exceptionSettings(Args, Triple);
 
   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
   // is not necessarily sensible, but follows GCC.
@@ -1965,31 +1965,43 @@
                    true)) {
     CmdArgs.push_back("-fobjc-exceptions");
 
-    ES.ShouldUseExceptionTables |=
-      shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
+    EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
   }
 
   if (types::isCXX(InputType)) {
-    bool CXXExceptionsEnabled = ES.ExceptionsEnabled;
-
-    if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
-                                 options::OPT_fno_cxx_exceptions,
-                                 options::OPT_fexceptions,
-                                 options::OPT_fno_exceptions)) {
-      if (A->getOption().matches(options::OPT_fcxx_exceptions))
-        CXXExceptionsEnabled = true;
-      else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
-        CXXExceptionsEnabled = false;
-    }
+    bool CXXExceptionsEnabled =
+        Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
+    Arg *ExceptionArg = Args.getLastArg(
+        options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
+        options::OPT_fexceptions, options::OPT_fno_exceptions);
+    if (ExceptionArg)
+      CXXExceptionsEnabled =
+          ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
+          ExceptionArg->getOption().matches(options::OPT_fexceptions);
 
     if (CXXExceptionsEnabled) {
+      if (Triple.isPS4CPU()) {
+        ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
+        assert(ExceptionArg &&
+               "On the PS4 exceptions should only be enabled if passing "
+               "an argument");
+        if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
+          const Arg *RTTIArg = TC.getRTTIArg();
+          assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
+          D.Diag(diag::err_drv_argument_not_allowed_with)
+              << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
+        } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
+          D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
+      } else
+        assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
+
       CmdArgs.push_back("-fcxx-exceptions");
 
-      ES.ShouldUseExceptionTables = true;
+      EH = true;
     }
   }
 
-  if (ES.ShouldUseExceptionTables)
+  if (EH)
     CmdArgs.push_back("-fexceptions");
 }
 
@@ -2015,7 +2027,7 @@
 
 /// \brief Check whether the given input tree contains any compilation actions.
 static bool ContainsCompileAction(const Action *A) {
-  if (isa<CompileJobAction>(A))
+  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
     return true;
 
   for (const auto &Act : *A)
@@ -2116,11 +2128,13 @@
 
 // Until ARM libraries are build separately, we have them all in one library
 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
-  if (TC.getArch() == llvm::Triple::arm ||
-      TC.getArch() == llvm::Triple::armeb)
+  // FIXME: handle 64-bit
+  if (TC.getTriple().isOSWindows() &&
+      !TC.getTriple().isWindowsItaniumEnvironment())
+    return "i386";
+  if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
     return "arm";
-  else
-    return TC.getArchName();
+  return TC.getArchName();
 }
 
 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
@@ -2128,38 +2142,48 @@
   SmallString<128> Res(TC.getDriver().ResourceDir);
   const llvm::Triple &Triple = TC.getTriple();
   // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
-  StringRef OSLibName = (Triple.getOS() == llvm::Triple::FreeBSD) ?
-    "freebsd" : TC.getOS();
+  StringRef OSLibName =
+      (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
   llvm::sys::path::append(Res, "lib", OSLibName);
   return Res;
 }
 
+static SmallString<128> getCompilerRT(const ToolChain &TC, StringRef Component,
+                                      bool Shared = false) {
+  const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
+                        ? "-android"
+                        : "";
+
+  bool IsOSWindows = TC.getTriple().isOSWindows();
+  StringRef Arch = getArchNameForCompilerRTLib(TC);
+  const char *Prefix = IsOSWindows ? "" : "lib";
+  const char *Suffix =
+      Shared ? (IsOSWindows ? ".dll" : ".so") : (IsOSWindows ? ".lib" : ".a");
+
+  SmallString<128> Path = getCompilerRTLibDir(TC);
+  llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
+                                    Arch + Env + Suffix);
+
+  return Path;
+}
+
 // This adds the static libclang_rt.builtins-arch.a directly to the command line
 // FIXME: Make sure we can also emit shared objects if they're requested
 // and available, check for possible errors, etc.
-static void addClangRTLinux(
-    const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
-  SmallString<128> LibClangRT = getCompilerRTLibDir(TC);
-  llvm::sys::path::append(LibClangRT, Twine("libclang_rt.builtins-") +
-                                          getArchNameForCompilerRTLib(TC) +
-                                          ".a");
+static void addClangRT(const ToolChain &TC, const ArgList &Args,
+                       ArgStringList &CmdArgs) {
+  CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
 
-  CmdArgs.push_back(Args.MakeArgString(LibClangRT));
-  CmdArgs.push_back("-lgcc_s");
-  if (TC.getDriver().CCCIsCXX())
-    CmdArgs.push_back("-lgcc_eh");
+  if (!TC.getTriple().isOSWindows()) {
+    // FIXME: why do we link against gcc when we are using compiler-rt?
+    CmdArgs.push_back("-lgcc_s");
+    if (TC.getDriver().CCCIsCXX())
+      CmdArgs.push_back("-lgcc_eh");
+  }
 }
 
-static void addClangRTWindows(const ToolChain &TC, const ArgList &Args,
-                              ArgStringList &CmdArgs) {
-  SmallString<128> LibClangRT = getCompilerRTLibDir(TC);
-  llvm::sys::path::append(LibClangRT, Twine("libclang_rt.builtins-") +
-                          getArchNameForCompilerRTLib(TC) + ".lib");
-  CmdArgs.push_back(Args.MakeArgString(LibClangRT));
-}
-
-static void addProfileRT(
-    const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
+static void addProfileRT(const ToolChain &TC, const ArgList &Args,
+                         ArgStringList &CmdArgs) {
   if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
                      false) ||
         Args.hasArg(options::OPT_fprofile_generate) ||
@@ -2168,38 +2192,17 @@
         Args.hasArg(options::OPT_coverage)))
     return;
 
-  SmallString<128> LibProfile = getCompilerRTLibDir(TC);
-  llvm::sys::path::append(LibProfile, Twine("libclang_rt.profile-") +
-                                          getArchNameForCompilerRTLib(TC) +
-                                          ".a");
-
-  CmdArgs.push_back(Args.MakeArgString(LibProfile));
-}
-
-static SmallString<128> getSanitizerRTLibName(const ToolChain &TC,
-                                              StringRef Sanitizer,
-                                              bool Shared) {
-  // Sanitizer runtime has name "libclang_rt.<Sanitizer>-<ArchName>.{a,so}"
-  // (or "libclang_rt.<Sanitizer>-<ArchName>-android.so for Android)
-  const char *EnvSuffix =
-    TC.getTriple().getEnvironment() == llvm::Triple::Android ?  "-android" : "";
-  SmallString<128> LibSanitizer = getCompilerRTLibDir(TC);
-  llvm::sys::path::append(LibSanitizer,
-                          Twine("libclang_rt.") + Sanitizer + "-" +
-                              getArchNameForCompilerRTLib(TC) + EnvSuffix +
-                              (Shared ? ".so" : ".a"));
-  return LibSanitizer;
+  CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
 }
 
 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
                                 ArgStringList &CmdArgs, StringRef Sanitizer,
                                 bool IsShared) {
-  SmallString<128> LibSanitizer = getSanitizerRTLibName(TC, Sanitizer, IsShared);
   // Static runtimes must be forced into executable, so we wrap them in
   // whole-archive.
   if (!IsShared)
     CmdArgs.push_back("-whole-archive");
-  CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
+  CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
   if (!IsShared)
     CmdArgs.push_back("-no-whole-archive");
 }
@@ -2209,10 +2212,9 @@
 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
                                     ArgStringList &CmdArgs,
                                     StringRef Sanitizer) {
-  SmallString<128> LibSanitizer = getSanitizerRTLibName(TC, Sanitizer, false);
-  if (llvm::sys::fs::exists(LibSanitizer + ".syms")) {
-    CmdArgs.push_back(
-        Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms"));
+  SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
+  if (llvm::sys::fs::exists(SanRT + ".syms")) {
+    CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
     return true;
   }
   return false;
@@ -2301,27 +2303,49 @@
   return !StaticRuntimes.empty();
 }
 
+static bool areOptimizationsEnabled(const ArgList &Args) {
+  // Find the last -O arg and see if it is non-zero.
+  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
+    return !A->getOption().matches(options::OPT_O0);
+  // Defaults to -O0.
+  return false;
+}
+
 static bool shouldUseFramePointerForTarget(const ArgList &Args,
                                            const llvm::Triple &Triple) {
-  switch (Triple.getArch()) {
-  // Don't use a frame pointer on linux if optimizing for certain targets.
-  case llvm::Triple::mips64:
-  case llvm::Triple::mips64el:
-  case llvm::Triple::mips:
-  case llvm::Triple::mipsel:
-  case llvm::Triple::systemz:
-  case llvm::Triple::x86:
-  case llvm::Triple::x86_64:
-    if (Triple.isOSLinux())
-      if (Arg *A = Args.getLastArg(options::OPT_O_Group))
-        if (!A->getOption().matches(options::OPT_O0))
-          return false;
-    return true;
-  case llvm::Triple::xcore:
+  // XCore never wants frame pointers, regardless of OS.
+  if (Triple.getArch() == llvm::Triple::xcore) {
     return false;
-  default:
-    return true;
   }
+
+  if (Triple.isOSLinux()) {
+    switch (Triple.getArch()) {
+    // Don't use a frame pointer on linux if optimizing for certain targets.
+    case llvm::Triple::mips64:
+    case llvm::Triple::mips64el:
+    case llvm::Triple::mips:
+    case llvm::Triple::mipsel:
+    case llvm::Triple::systemz:
+    case llvm::Triple::x86:
+    case llvm::Triple::x86_64:
+      return !areOptimizationsEnabled(Args);
+    default:
+      return true;
+    }
+  }
+
+  if (Triple.isOSWindows()) {
+    switch (Triple.getArch()) {
+    case llvm::Triple::x86:
+      return !areOptimizationsEnabled(Args);
+    default:
+      // All other supported Windows ISAs use xdata unwind information, so frame
+      // pointers are not generally useful.
+      return false;
+    }
+  }
+
+  return true;
 }
 
 static bool shouldUseFramePointer(const ArgList &Args,
@@ -2339,6 +2363,9 @@
                                options::OPT_momit_leaf_frame_pointer))
     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
 
+  if (Triple.isPS4CPU())
+    return false;
+
   return shouldUseFramePointerForTarget(Args, Triple);
 }
 
@@ -2461,6 +2488,48 @@
       llvm::utostr_32(Build);
 }
 
+// Claim options we don't want to warn if they are unused. We do this for
+// options that build systems might add but are unused when assembling or only
+// running the preprocessor for example.
+static void claimNoWarnArgs(const ArgList &Args) {
+  // Don't warn about unused -f(no-)?lto.  This can happen when we're
+  // preprocessing, precompiling or assembling.
+  Args.ClaimAllArgs(options::OPT_flto);
+  Args.ClaimAllArgs(options::OPT_fno_lto);
+}
+
+static void appendUserToPath(SmallVectorImpl<char> &Result) {
+#ifdef LLVM_ON_UNIX
+  const char *Username = getenv("LOGNAME");
+#else
+  const char *Username = getenv("USERNAME");
+#endif
+  if (Username) {
+    // Validate that LoginName can be used in a path, and get its length.
+    size_t Len = 0;
+    for (const char *P = Username; *P; ++P, ++Len) {
+      if (!isAlphanumeric(*P) && *P != '_') {
+        Username = nullptr;
+        break;
+      }
+    }
+
+    if (Username && Len > 0) {
+      Result.append(Username, Username + Len);
+      return;
+    }
+  }
+
+  // Fallback to user id.
+#ifdef LLVM_ON_UNIX
+  std::string UID = llvm::utostr(getuid());
+#else
+  // FIXME: Windows seems to have an 'SID' that might work.
+  std::string UID = "9999";
+#endif
+  Result.append(UID.begin(), UID.end());
+}
+
 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
                          const InputInfo &Output,
                          const InputInfoList &Inputs,
@@ -2541,7 +2610,8 @@
   } else if (isa<VerifyPCHJobAction>(JA)) {
     CmdArgs.push_back("-verify-pch");
   } else {
-    assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
+    assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
+           "Invalid action for clang tool.");
 
     if (JA.getType() == types::TY_Nothing) {
       CmdArgs.push_back("-fsyntax-only");
@@ -2734,8 +2804,7 @@
   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
   // PIC or PIE options above, if these show up, PIC is disabled.
   llvm::Triple Triple(TripleStr);
-  if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6) ||
-                       Triple.getArch() == llvm::Triple::aarch64))
+  if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
     PIC = PIE = false;
   if (Args.hasArg(options::OPT_static))
     PIC = PIE = false;
@@ -2787,6 +2856,19 @@
 
   // LLVM Code Generator Options.
 
+  if (Args.hasArg(options::OPT_frewrite_map_file) ||
+      Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
+    for (arg_iterator
+             MFI = Args.filtered_begin(options::OPT_frewrite_map_file,
+                                       options::OPT_frewrite_map_file_EQ),
+             MFE = Args.filtered_end();
+         MFI != MFE; ++MFI) {
+      CmdArgs.push_back("-frewrite-map-file");
+      CmdArgs.push_back((*MFI)->getValue());
+      (*MFI)->claim();
+    }
+  }
+
   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
     StringRef v = A->getValue();
     CmdArgs.push_back("-mllvm");
@@ -2948,6 +3030,8 @@
       !TrappingMath)
     CmdArgs.push_back("-menable-unsafe-fp-math");
 
+  if (!SignedZeros)
+    CmdArgs.push_back("-fno-signed-zeros");
 
   // Validate and pass through -fp-contract option. 
   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
@@ -3232,6 +3316,10 @@
     CmdArgs.push_back("-fdata-sections");
   }
 
+  if (!Args.hasFlag(options::OPT_funique_section_names,
+                    options::OPT_fno_unique_section_names, true))
+    CmdArgs.push_back("-fno-unique-section-names");
+
   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
 
   if (Args.hasArg(options::OPT_fprofile_instr_generate) &&
@@ -3400,9 +3488,7 @@
     D.Diag(diag::warn_ignored_gcc_optimization) << (*it)->getAsString(Args);
   }
 
-  // Don't warn about unused -flto.  This can happen when we're preprocessing or
-  // precompiling.
-  Args.ClaimAllArgs(options::OPT_flto);
+  claimNoWarnArgs(Args);
 
   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
@@ -3425,8 +3511,10 @@
     else
       Std->render(Args, CmdArgs);
 
+    // If -f(no-)trigraphs appears after the language standard flag, honor it.
     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
-                                 options::OPT_trigraphs))
+                                 options::OPT_ftrigraphs,
+                                 options::OPT_fno_trigraphs))
       if (A != Std)
         A->render(Args, CmdArgs);
   } else {
@@ -3442,7 +3530,8 @@
     else if (IsWindowsMSVC)
       CmdArgs.push_back("-std=c++11");
 
-    Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
+    Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
+                    options::OPT_fno_trigraphs);
   }
 
   // GCC's behavior for -Wwrite-strings is a bit strange:
@@ -3561,6 +3650,11 @@
     CmdArgs.push_back(A->getValue());
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
+    CmdArgs.push_back("-fspell-checking-limit");
+    CmdArgs.push_back(A->getValue());
+  }
+
   // Pass -fmessage-length=.
   CmdArgs.push_back("-fmessage-length");
   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
@@ -3720,6 +3814,15 @@
     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
   }
 
+  if (Args.hasArg(options::OPT_mstack_probe_size)) {
+    StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
+
+    if (!Size.empty())
+      CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
+    else
+      CmdArgs.push_back("-mstack-probe-size=0");
+  }
+
   if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
       getToolChain().getTriple().getArch() == llvm::Triple::aarch64_be)
     CmdArgs.push_back("-fallow-half-arguments-and-returns");
@@ -3826,6 +3929,12 @@
     CmdArgs.push_back("-fmodules-strict-decluse");
   }
 
+  // -fno-implicit-modules turns off implicitly compiling modules on demand.
+  if (!Args.hasFlag(options::OPT_fimplicit_modules,
+                    options::OPT_fno_implicit_modules)) {
+    CmdArgs.push_back("-fno-implicit-modules");
+  }
+
   // -fmodule-name specifies the module that is currently being built (or
   // used for header checking by -fmodule-maps).
   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
@@ -3853,7 +3962,8 @@
       // No module path was provided: use the default.
       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
                                              ModuleCachePath);
-      llvm::sys::path::append(ModuleCachePath, "org.llvm.clang");
+      llvm::sys::path::append(ModuleCachePath, "org.llvm.clang.");
+      appendUserToPath(ModuleCachePath);
       llvm::sys::path::append(ModuleCachePath, "ModuleCache");
     }
     const char Arg[] = "-fmodules-cache-path=";
@@ -3892,10 +4002,9 @@
     llvm::sys::fs::file_status Status;
     if (llvm::sys::fs::status(A->getValue(), Status))
       D.Diag(diag::err_drv_no_such_file) << A->getValue();
-    char TimeStamp[48];
-    snprintf(TimeStamp, sizeof(TimeStamp), "-fbuild-session-timestamp=%" PRIu64,
-             (uint64_t)Status.getLastModificationTime().toEpochTime());
-    CmdArgs.push_back(Args.MakeArgString(TimeStamp));
+    CmdArgs.push_back(Args.MakeArgString(
+        "-fbuild-session-timestamp=" +
+        Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
   }
 
   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
@@ -3921,21 +4030,11 @@
                    false))
     CmdArgs.push_back("-fno-elide-constructors");
 
-  // -frtti is default.
-  if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
-      KernelOrKext) {
-    CmdArgs.push_back("-fno-rtti");
+  ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
 
-    // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
-    if (Sanitize.sanitizesVptr()) {
-      std::string NoRttiArg =
-        Args.getLastArg(options::OPT_mkernel,
-                        options::OPT_fapple_kext,
-                        options::OPT_fno_rtti)->getAsString(Args);
-      D.Diag(diag::err_drv_argument_not_allowed_with)
-        << "-fsanitize=vptr" << NoRttiArg;
-    }
-  }
+  if (RTTIMode == ToolChain::RM_DisabledExplicitly ||
+      RTTIMode == ToolChain::RM_DisabledImplicitly)
+    CmdArgs.push_back("-fno-rtti");
 
   // -fshort-enums=0 is default for all architectures except Hexagon.
   if (Args.hasFlag(options::OPT_fshort_enums,
@@ -3968,6 +4067,11 @@
                    IsWindowsMSVC))
     CmdArgs.push_back("-fms-extensions");
 
+  // -fno-use-line-directives is default.
+  if (Args.hasFlag(options::OPT_fuse_line_directives,
+                   options::OPT_fno_use_line_directives, false))
+    CmdArgs.push_back("-fuse-line-directives");
+
   // -fms-compatibility=0 is default.
   if (Args.hasFlag(options::OPT_fms_compatibility, 
                    options::OPT_fno_ms_compatibility,
@@ -3996,7 +4100,7 @@
       Ver = getMSCompatibilityVersion(MSCVersion->getValue());
 
     if (Ver.empty())
-      CmdArgs.push_back("-fms-compatibility-version=17.00");
+      CmdArgs.push_back("-fms-compatibility-version=18.00");
     else
       CmdArgs.push_back(Args.MakeArgString("-fms-compatibility-version=" + Ver));
   }
@@ -4113,7 +4217,7 @@
 
   // Handle GCC-style exception args.
   if (!C.getDriver().IsCLMode())
-    addExceptionArgs(Args, InputType, getToolChain().getTriple(), KernelOrKext,
+    addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext,
                      objcRuntime, CmdArgs);
 
   if (getToolChain().UseSjLjExceptions())
@@ -4307,6 +4411,11 @@
                    false))
     CmdArgs.push_back("-fasm-blocks");
 
+  // -fgnu-inline-asm is default.
+  if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
+                    options::OPT_fno_gnu_inline_asm, true))
+    CmdArgs.push_back("-fno-gnu-inline-asm");
+
   // Enable vectorization per default according to the optimization level
   // selected. For optimization levels that want vectorization we use the alias
   // option to simplify the hasFlag logic.
@@ -4414,18 +4523,27 @@
   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
   // parser.
   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
+  bool OptDisabled = false;
   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
          ie = Args.filtered_end(); it != ie; ++it) {
     (*it)->claim();
 
     // We translate this by hand to the -cc1 argument, since nightly test uses
     // it and developers have been trained to spell it with -mllvm.
-    if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
+    if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns") {
       CmdArgs.push_back("-disable-llvm-optzns");
-    else
+      OptDisabled = true;
+    } else
       (*it)->render(Args, CmdArgs);
   }
 
+  // With -save-temps, we want to save the unoptimized bitcode output from the
+  // CompileJobAction, so disable optimizations if they are not already
+  // disabled.
+  if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
+      isa<CompileJobAction>(JA))
+    CmdArgs.push_back("-disable-llvm-optzns");
+
   if (Output.getType() == types::TY_Dependencies) {
     // Handled with other dependency code.
   } else if (Output.isFilename()) {
@@ -4471,7 +4589,8 @@
   // can propagate it to the backend.
   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
     getToolChain().getTriple().isOSLinux() &&
-    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA));
+    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
+     isa<BackendJobAction>(JA));
   const char *SplitDwarfOut;
   if (SplitDwarf) {
     CmdArgs.push_back("-split-dwarf-file");
@@ -4495,7 +4614,7 @@
   // Handle the debug info splitting at object creation time if we're
   // creating an object.
   // TODO: Currently only works on linux with newer objcopy.
-  if (SplitDwarf && !isa<CompileJobAction>(JA))
+  if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
 
   if (Arg *A = Args.getLastArg(options::OPT_pg))
@@ -4743,8 +4862,8 @@
   EHFlags EH = parseClangCLEHFlags(D, Args);
   // FIXME: Do something with NoExceptC.
   if (EH.Synch || EH.Asynch) {
-    CmdArgs.push_back("-fexceptions");
     CmdArgs.push_back("-fcxx-exceptions");
+    CmdArgs.push_back("-fexceptions");
   }
 
   // /EP should expand to -E -P.
@@ -4753,6 +4872,19 @@
     CmdArgs.push_back("-P");
   }
 
+  unsigned VolatileOptionID;
+  if (getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
+      getToolChain().getTriple().getArch() == llvm::Triple::x86)
+    VolatileOptionID = options::OPT__SLASH_volatile_ms;
+  else
+    VolatileOptionID = options::OPT__SLASH_volatile_iso;
+
+  if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
+    VolatileOptionID = A->getOption().getID();
+
+  if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
+    CmdArgs.push_back("-fms-volatile");
+
   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
   if (MostGeneralArg && BestCaseArg)
@@ -4797,6 +4929,17 @@
   return CLFallback.get();
 }
 
+void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
+                                ArgStringList &CmdArgs) const {
+  StringRef CPUName;
+  StringRef ABIName;
+  const llvm::Triple &Triple = getToolChain().getTriple();
+  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
+
+  CmdArgs.push_back("-target-abi");
+  CmdArgs.push_back(ABIName.data());
+}
+
 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
                            const InputInfo &Output,
                            const InputInfoList &Inputs,
@@ -4812,6 +4955,8 @@
   // and "clang -emit-llvm -c foo.s"
   Args.ClaimAllArgs(options::OPT_emit_llvm);
 
+  claimNoWarnArgs(Args);
+
   // Invoke ourselves in -cc1as mode.
   //
   // FIXME: Implement custom jobs for internal actions.
@@ -4902,6 +5047,19 @@
 
   // FIXME: Add -static support, once we have it.
 
+  // Add target specific flags.
+  switch(getToolChain().getArch()) {
+  default:
+    break;
+
+  case llvm::Triple::mips:
+  case llvm::Triple::mipsel:
+  case llvm::Triple::mips64:
+  case llvm::Triple::mips64el:
+    AddMIPSTargetArgs(Args, CmdArgs);
+    break;
+  }
+
   // Consume all the warning flags. Usually this would be handled more
   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
   // doesn't handle that so rather than warning about unused flags that are
@@ -5064,16 +5222,22 @@
                                        ArgStringList &CmdArgs) const {
   const Driver &D = getToolChain().getDriver();
 
+  switch (JA.getType()) {
   // If -flto, etc. are present then make sure not to force assembly output.
-  if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
-      JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
+  case types::TY_LLVM_IR:
+  case types::TY_LTO_IR:
+  case types::TY_LLVM_BC:
+  case types::TY_LTO_BC:
     CmdArgs.push_back("-c");
-  else {
-    if (JA.getType() != types::TY_PP_Asm)
-      D.Diag(diag::err_drv_invalid_gcc_output_type)
-        << getTypeName(JA.getType());
-
+    break;
+  case types::TY_PP_Asm:
     CmdArgs.push_back("-S");
+    break;
+  case types::TY_Nothing:
+    CmdArgs.push_back("-fsyntax-only");
+    break;
+  default:
+    D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
   }
 }
 
@@ -5092,6 +5256,7 @@
                                const InputInfoList &Inputs,
                                const ArgList &Args,
                                const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
 
   const Driver &D = getToolChain().getDriver();
   ArgStringList CmdArgs;
@@ -5382,16 +5547,30 @@
     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "v7")
-    .Cases("cortex-r4", "cortex-r5", "v7r")
-    .Case("cortex-m0", "v6m")
-    .Case("cortex-m3", "v7m")
+    .Cases("cortex-r4", "cortex-r5", "cortex-r7", "v7r")
+    .Cases("sc000", "cortex-m0", "cortex-m0plus", "cortex-m1", "v6m")
+    .Cases("sc300", "cortex-m3", "v7m")
     .Cases("cortex-m4", "cortex-m7", "v7em")
     .Case("swift", "v7s")
     .Case("cyclone", "v8")
-    .Cases("cortex-a53", "cortex-a57", "v8")
+    .Cases("cortex-a53", "cortex-a57", "cortex-a72", "v8")
     .Default("");
 }
 
+void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple) {
+  if (Args.hasArg(options::OPT_r))
+    return;
+
+  StringRef Suffix = getLLVMArchSuffixForARM(getARMCPUForMArch(Args, Triple));
+  const char *LinkFlag = llvm::StringSwitch<const char *>(Suffix)
+    .Cases("v4", "v4t", "v5", "v5e", nullptr)
+    .Cases("v6", "v6t2", nullptr)
+    .Default("--be8");
+
+  if (LinkFlag)
+    CmdArgs.push_back(LinkFlag);
+}
+
 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
   return A && (A->getValue() == StringRef(Value));
@@ -5428,8 +5607,8 @@
 
   return llvm::StringSwitch<bool>(CPUName)
              .Cases("mips2", "mips3", "mips4", "mips5", true)
-             .Cases("mips32", "mips32r2", true)
-             .Cases("mips64", "mips64r2", true)
+             .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
+             .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
              .Default(false);
 }
 
@@ -5460,6 +5639,7 @@
     .Cases("armv7s", "xscale", llvm::Triple::arm)
     .Case("arm64", llvm::Triple::aarch64)
     .Case("r600", llvm::Triple::r600)
+    .Case("amdgcn", llvm::Triple::amdgcn)
     .Case("nvptx", llvm::Triple::nvptx)
     .Case("nvptx64", llvm::Triple::nvptx64)
     .Case("amdil", llvm::Triple::amdil)
@@ -5633,7 +5813,8 @@
   // If we are using LTO, then automatically create a temporary file path for
   // the linker to use, so that it's lifetime will extend past a possible
   // dsymutil step.
-  if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
+  if (Version[0] >= 116 && D.IsUsingLTO(getToolChain(), Args) &&
+      NeedsTempPath(Inputs)) {
     const char *TmpPath = C.getArgs().MakeArgString(
       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
     C.addTempFile(TmpPath);
@@ -5923,6 +6104,12 @@
   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   Args.AddAllArgs(CmdArgs, options::OPT_F);
 
+  // -iframework should be forwarded as -F.
+  for (auto it = Args.filtered_begin(options::OPT_iframework),
+         ie = Args.filtered_end(); it != ie; ++it)
+    CmdArgs.push_back(Args.MakeArgString(std::string("-F") +
+                                         (*it)->getValue()));
+
   const char *Exec =
     Args.MakeArgString(getToolChain().GetLinkerPath());
   std::unique_ptr<Command> Cmd =
@@ -6001,6 +6188,7 @@
                                       const InputInfoList &Inputs,
                                       const ArgList &Args,
                                       const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
@@ -6126,6 +6314,7 @@
                                      const InputInfoList &Inputs,
                                      const ArgList &Args,
                                      const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
   bool NeedsKPIC = false;
 
@@ -6328,6 +6517,7 @@
                                     const InputInfoList &Inputs,
                                     const ArgList &Args,
                                     const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
@@ -6464,6 +6654,7 @@
                                      const InputInfoList &Inputs,
                                      const ArgList &Args,
                                      const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
@@ -6646,7 +6837,7 @@
   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
   Args.AddAllArgs(CmdArgs, options::OPT_r);
 
-  if (D.IsUsingLTO(Args))
+  if (D.IsUsingLTO(getToolChain(), Args))
     AddGoldPlugin(ToolChain, Args, CmdArgs);
 
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
@@ -6729,6 +6920,7 @@
                                      const InputInfoList &Inputs,
                                      const ArgList &Args,
                                      const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   // GNU as needs different flags for creating the correct output format
@@ -6849,6 +7041,7 @@
     break;
   case llvm::Triple::armeb:
   case llvm::Triple::thumbeb:
+    arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getTriple());
     CmdArgs.push_back("-m");
     switch (getToolChain().getTriple().getEnvironment()) {
     case llvm::Triple::EABI:
@@ -7011,6 +7204,8 @@
                                       const InputInfoList &Inputs,
                                       const ArgList &Args,
                                       const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
+
   ArgStringList CmdArgs;
   bool NeedsKPIC = false;
 
@@ -7289,19 +7484,17 @@
 }
 
 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
-                      ArgStringList &CmdArgs, const ArgList &Args) {
+                           ArgStringList &CmdArgs, const ArgList &Args) {
   // Make use of compiler-rt if --rtlib option is used
   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
 
-  switch(RLT) {
+  switch (RLT) {
   case ToolChain::RLT_CompilerRT:
     switch (TC.getTriple().getOS()) {
     default: llvm_unreachable("unsupported OS");
     case llvm::Triple::Win32:
-      addClangRTWindows(TC, Args, CmdArgs);
-      break;
     case llvm::Triple::Linux:
-      addClangRTLinux(TC, Args, CmdArgs);
+      addClangRT(TC, Args, CmdArgs);
       break;
     }
     break;
@@ -7399,6 +7592,10 @@
   if (Args.hasArg(options::OPT_s))
     CmdArgs.push_back("-s");
 
+  if (ToolChain.getArch() == llvm::Triple::armeb ||
+      ToolChain.getArch() == llvm::Triple::thumbeb)
+    arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getTriple());
+
   for (const auto &Opt : ToolChain.ExtraOpts)
     CmdArgs.push_back(Opt.c_str());
 
@@ -7476,7 +7673,7 @@
   for (const auto &Path : Paths)
     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
 
-  if (D.IsUsingLTO(Args))
+  if (D.IsUsingLTO(getToolChain(), Args))
     AddGoldPlugin(ToolChain, Args, CmdArgs);
 
   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
@@ -7573,6 +7770,7 @@
                                    const InputInfoList &Inputs,
                                    const ArgList &Args,
                                    const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
@@ -7650,6 +7848,7 @@
                                        const InputInfoList &Inputs,
                                        const ArgList &Args,
                                        const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   // When building 32-bit code on DragonFly/pc64, we have to explicitly
@@ -7816,15 +8015,6 @@
   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
 }
 
-static void addSanitizerRTWindows(const ToolChain &TC, const ArgList &Args,
-                                  ArgStringList &CmdArgs,
-                                  StringRef RTName) {
-  SmallString<128> LibSanitizer(getCompilerRTLibDir(TC));
-  llvm::sys::path::append(LibSanitizer,
-                          Twine("clang_rt.") + RTName + ".lib");
-  CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
-}
-
 // Try to find Exe from a Visual Studio distribution.  This first tries to find
 // an installed copy of Visual Studio and, failing that, looks in the PATH,
 // making sure that whatever executable that's found is not a same-named exe
@@ -7851,19 +8041,16 @@
                                       const ArgList &Args,
                                       const char *LinkingOutput) const {
   ArgStringList CmdArgs;
+  const ToolChain &TC = getToolChain();
 
-  if (Output.isFilename()) {
+  assert((Output.isFilename() || Output.isNothing()) && "invalid output");
+  if (Output.isFilename())
     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
                                          Output.getFilename()));
-  } else {
-    assert(Output.isNothing() && "Invalid output.");
-  }
 
   if (!Args.hasArg(options::OPT_nostdlib) &&
-      !Args.hasArg(options::OPT_nostartfiles) &&
-      !C.getDriver().IsCLMode()) {
+      !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
     CmdArgs.push_back("-defaultlib:libcmt");
-  }
 
   if (!llvm::sys::Process::GetEnv("LIB")) {
     // If the VC environment hasn't been configured (perhaps because the user
@@ -7871,7 +8058,7 @@
     // the environment variable is set however, assume the user knows what he's
     // doing.
     std::string VisualStudioDir;
-    const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(getToolChain());
+    const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
       SmallString<128> LibDir(VisualStudioDir);
       llvm::sys::path::append(LibDir, "VC", "lib");
@@ -7900,12 +8087,10 @@
 
   CmdArgs.push_back("-nologo");
 
-  if (Args.hasArg(options::OPT_g_Group)) {
+  if (Args.hasArg(options::OPT_g_Group))
     CmdArgs.push_back("-debug");
-  }
 
   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
-
   if (DLL) {
     CmdArgs.push_back(Args.MakeArgString("-dll"));
 
@@ -7915,23 +8100,28 @@
                                          ImplibName.str()));
   }
 
-  if (getToolChain().getSanitizerArgs().needsAsanRt()) {
+  if (TC.getSanitizerArgs().needsAsanRt()) {
     CmdArgs.push_back(Args.MakeArgString("-debug"));
     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
-    // FIXME: Handle 64-bit.
     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
-      addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan_dynamic-i386");
-      addSanitizerRTWindows(getToolChain(), Args, CmdArgs,
-                            "asan_dynamic_runtime_thunk-i386");
+      static const char *CompilerRTComponents[] = {
+        "asan_dynamic",
+        "asan_dynamic_runtime_thunk",
+      };
+      for (const auto &Component : CompilerRTComponents)
+        CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
       // Make sure the dynamic runtime thunk is not optimized out at link time
       // to ensure proper SEH handling.
       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
     } else if (DLL) {
-      addSanitizerRTWindows(getToolChain(), Args, CmdArgs,
-                            "asan_dll_thunk-i386");
+      CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
     } else {
-      addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan-i386");
-      addSanitizerRTWindows(getToolChain(), Args, CmdArgs, "asan_cxx-i386");
+      static const char *CompilerRTComponents[] = {
+        "asan",
+        "asan_cxx",
+      };
+      for (const auto &Component : CompilerRTComponents)
+        CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
     }
   }
 
@@ -7963,10 +8153,26 @@
     A.renderAsInput(Args, CmdArgs);
   }
 
-  // It's not sufficient to just use link from the program PATH, because other
-  // environments like GnuWin32 install their own link.exe which may come first.
-  llvm::SmallString<128> linkPath(FindVisualStudioExecutable(
-      getToolChain(), "link.exe", C.getDriver().getClangProgramPath()));
+  // We need to special case some linker paths.  In the case of lld, we need to
+  // translate 'lld' into 'lld-link', and in the case of the regular msvc
+  // linker, we need to use a special search algorithm.
+  llvm::SmallString<128> linkPath;
+  StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
+  if (Linker.equals_lower("lld"))
+    Linker = "lld-link";
+
+  if (Linker.equals_lower("link")) {
+    // If we're using the MSVC linker, it's not sufficient to just use link
+    // from the program PATH, because other environments like GnuWin32 install
+    // their own link.exe which may come first.
+    linkPath = FindVisualStudioExecutable(TC, "link.exe",
+                                          C.getDriver().getClangProgramPath());
+  } else {
+    linkPath = Linker;
+    llvm::sys::path::replace_extension(linkPath, "exe");
+    linkPath = TC.GetProgramPath(linkPath.c_str());
+  }
+
   const char *Exec = Args.MakeArgString(linkPath);
   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
 }
@@ -8075,6 +8281,7 @@
                                        const InputInfoList &Inputs,
                                        const ArgList &Args,
                                        const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   ArgStringList CmdArgs;
 
   CmdArgs.push_back("-o");
@@ -8120,8 +8327,7 @@
   if (Args.hasArg(options::OPT_v))
     CmdArgs.push_back("-v");
 
-  ExceptionSettings EH = exceptionSettings(Args, getToolChain().getTriple());
-  if (EH.ShouldUseExceptionTables)
+  if (exceptionSettings(Args, getToolChain().getTriple()))
     CmdArgs.push_back("-fexceptions");
 
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
@@ -8135,6 +8341,7 @@
                                           const InputInfoList &Inputs,
                                           const ArgList &Args,
                                           const char *LinkingOutput) const {
+  claimNoWarnArgs(Args);
   const auto &TC =
       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
   ArgStringList CmdArgs;
@@ -8306,4 +8513,3 @@
 
   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
 }
-
diff --git a/lib/Driver/Tools.h b/lib/Driver/Tools.h
index 59af8a0..93a19fb 100644
--- a/lib/Driver/Tools.h
+++ b/lib/Driver/Tools.h
@@ -95,6 +95,7 @@
     bool hasGoodDiagnostics() const override { return true; }
     bool hasIntegratedAssembler() const override { return true; }
     bool hasIntegratedCPP() const override { return true; }
+    bool canEmitIR() const override { return true; }
 
     void ConstructJob(Compilation &C, const JobAction &JA,
                       const InputInfo &Output, const InputInfoList &Inputs,
@@ -108,7 +109,8 @@
     ClangAs(const ToolChain &TC) : Tool("clang::as",
                                         "clang integrated assembler", TC,
                                         RF_Full) {}
-
+    void AddMIPSTargetArgs(const llvm::opt::ArgList &Args,
+                           llvm::opt::ArgStringList &CmdArgs) const;
     bool hasGoodDiagnostics() const override { return true; }
     bool hasIntegratedAssembler() const override { return false; }
     bool hasIntegratedCPP() const override { return false; }
@@ -227,6 +229,8 @@
   const char* getARMCPUForMArch(const llvm::opt::ArgList &Args,
                                 const llvm::Triple &Triple);
   const char* getLLVMArchSuffixForARM(StringRef CPU);
+
+  void appendEBLinkFlags(const llvm::opt::ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple);
 }
 
 namespace mips {
diff --git a/lib/Driver/Types.cpp b/lib/Driver/Types.cpp
index 4a22dcf..6ee764c 100644
--- a/lib/Driver/Types.cpp
+++ b/lib/Driver/Types.cpp
@@ -203,6 +203,7 @@
     } else {
       if (!onlyAssembleType(Id)) {
         P.push_back(phases::Compile);
+        P.push_back(phases::Backend);
       }
       P.push_back(phases::Assemble);
     }
diff --git a/lib/Format/BreakableToken.cpp b/lib/Format/BreakableToken.cpp
index 1bea0e5..c84d9af 100644
--- a/lib/Format/BreakableToken.cpp
+++ b/lib/Format/BreakableToken.cpp
@@ -106,7 +106,7 @@
           Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
     }
 
-    if (Chars > MaxSplit || Text.size() == Advance)
+    if (Chars > MaxSplit || Text.size() <= Advance)
       break;
 
     if (IsBlank(Text[0]))
@@ -303,7 +303,8 @@
     StartOfLineColumn[i] += Decoration.size();
     Lines[i] = Lines[i].substr(Decoration.size());
     LeadingWhitespace[i] += Decoration.size();
-    IndentAtLineBreak = std::min<int>(IndentAtLineBreak, StartOfLineColumn[i]);
+    IndentAtLineBreak =
+        std::min<int>(IndentAtLineBreak, std::max(0, StartOfLineColumn[i]));
   }
   IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
   DEBUG({
diff --git a/lib/Format/BreakableToken.h b/lib/Format/BreakableToken.h
index 6f49ed2..eb1f9fd 100644
--- a/lib/Format/BreakableToken.h
+++ b/lib/Format/BreakableToken.h
@@ -212,6 +212,11 @@
   // StartOfLineColumn[i] is the target column at which Line[i] should be.
   // Note that this excludes a leading "* " or "*" in case all lines have
   // a "*" prefix.
+  // The first line's target column is always positive. The remaining lines'
+  // target columns are relative to the first line to allow correct indentation
+  // of comments in \c WhitespaceManager. Thus they can be negative as well (in
+  // case the first line needs to be unindented more than there's actual
+  // whitespace in another line).
   SmallVector<int, 16> StartOfLineColumn;
 
   // The column at which the text of a broken line should start.
diff --git a/lib/Format/CMakeLists.txt b/lib/Format/CMakeLists.txt
index 3f08d9d..2ce3834 100644
--- a/lib/Format/CMakeLists.txt
+++ b/lib/Format/CMakeLists.txt
@@ -6,6 +6,7 @@
   Format.cpp
   FormatToken.cpp
   TokenAnnotator.cpp
+  UnwrappedLineFormatter.cpp
   UnwrappedLineParser.cpp
   WhitespaceManager.cpp
 
diff --git a/lib/Format/ContinuationIndenter.cpp b/lib/Format/ContinuationIndenter.cpp
index 40b50dd..7c2d916 100644
--- a/lib/Format/ContinuationIndenter.cpp
+++ b/lib/Format/ContinuationIndenter.cpp
@@ -48,11 +48,11 @@
 static bool startsNextParameter(const FormatToken &Current,
                                 const FormatStyle &Style) {
   const FormatToken &Previous = *Current.Previous;
-  if (Current.Type == TT_CtorInitializerComma &&
+  if (Current.is(TT_CtorInitializerComma) &&
       Style.BreakConstructorInitializersBeforeComma)
     return true;
   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
-         (Previous.Type != TT_CtorInitializerComma ||
+         (Previous.isNot(TT_CtorInitializerComma) ||
           !Style.BreakConstructorInitializersBeforeComma);
 }
 
@@ -93,13 +93,14 @@
   const FormatToken &Current = *State.NextToken;
   const FormatToken &Previous = *Current.Previous;
   assert(&Previous == Current.Previous);
-  if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
-                                   Current.closesBlockTypeList(Style)))
+  if (!Current.CanBreakBefore &&
+      !(State.Stack.back().BreakBeforeClosingBrace &&
+        Current.closesBlockTypeList(Style)))
     return false;
   // The opening "{" of a braced list has to be on the same line as the first
   // element if it is nested in another braced init list or function call.
   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
-      Previous.Type != TT_DictLiteral && Previous.BlockKind == BK_BracedInit &&
+      Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
       Previous.Previous &&
       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
     return false;
@@ -117,15 +118,14 @@
 
   // Don't create a 'hanging' indent if there are multiple blocks in a single
   // statement.
-  if (Style.Language == FormatStyle::LK_JavaScript &&
-      Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
-      State.Stack[State.Stack.size() - 2].JSFunctionInlined &&
+  if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
+      State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
       State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
     return false;
 
   // Don't break after very short return types (e.g. "void") as that is often
   // unexpected.
-  if (Current.Type == TT_FunctionDeclarationName &&
+  if (Current.is(TT_FunctionDeclarationName) &&
       !Style.AlwaysBreakAfterDefinitionReturnType && State.Column < 6)
     return false;
 
@@ -135,7 +135,7 @@
 bool ContinuationIndenter::mustBreak(const LineState &State) {
   const FormatToken &Current = *State.NextToken;
   const FormatToken &Previous = *Current.Previous;
-  if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
+  if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
     return true;
   if (State.Stack.back().BreakBeforeClosingBrace &&
       Current.closesBlockTypeList(Style))
@@ -144,32 +144,32 @@
     return true;
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
        (Style.BreakBeforeTernaryOperators &&
-        (Current.is(tok::question) || (Current.Type == TT_ConditionalExpr &&
-                                       Previous.isNot(tok::question)))) ||
+        (Current.is(tok::question) ||
+         (Current.is(TT_ConditionalExpr) && Previous.isNot(tok::question)))) ||
        (!Style.BreakBeforeTernaryOperators &&
-        (Previous.is(tok::question) || Previous.Type == TT_ConditionalExpr))) &&
+        (Previous.is(tok::question) || Previous.is(TT_ConditionalExpr)))) &&
       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
       !Current.isOneOf(tok::r_paren, tok::r_brace))
     return true;
   if (Style.AlwaysBreakBeforeMultilineStrings &&
       State.Column > State.Stack.back().Indent && // Breaking saves columns.
       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
-      Previous.Type != TT_InlineASMColon &&
-      Previous.Type != TT_ConditionalExpr && nextIsMultilineString(State))
+      !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
+      nextIsMultilineString(State))
     return true;
-  if (((Previous.Type == TT_DictLiteral && Previous.is(tok::l_brace)) ||
-       Previous.Type == TT_ArrayInitializerLSquare) &&
+  if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
+       Previous.is(TT_ArrayInitializerLSquare)) &&
       Style.ColumnLimit > 0 &&
       getLengthToMatchingParen(Previous) + State.Column > getColumnLimit(State))
     return true;
-  if (Current.Type == TT_CtorInitializerColon &&
+  if (Current.is(TT_CtorInitializerColon) &&
       ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
        Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
     return true;
 
   if (State.Column < getNewLineColumn(State))
     return false;
-  if (!Style.BreakBeforeBinaryOperators) {
+  if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None) {
     // If we need to break somewhere inside the LHS of a binary expression, we
     // should also break after the operator. Otherwise, the formatting would
     // hide the operator precedence, e.g. in:
@@ -179,41 +179,43 @@
     // expression itself as otherwise, the line breaks seem superfluous.
     // We need special cases for ">>" which we have split into two ">" while
     // lexing in order to make template parsing easier.
-    //
-    // FIXME: We'll need something similar for styles that break before binary
-    // operators.
     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
                          Previous.getPrecedence() == prec::Equality) &&
                         Previous.Previous &&
-                        Previous.Previous->Type != TT_BinaryOperator; // For >>.
+                        Previous.Previous->isNot(TT_BinaryOperator); // For >>.
     bool LHSIsBinaryExpr =
         Previous.Previous && Previous.Previous->EndsBinaryExpression;
-    if (Previous.Type == TT_BinaryOperator &&
-        (!IsComparison || LHSIsBinaryExpr) &&
-        Current.Type != TT_BinaryOperator && // For >>.
+    if (Previous.is(TT_BinaryOperator) && (!IsComparison || LHSIsBinaryExpr) &&
+        Current.isNot(TT_BinaryOperator) && // For >>.
         !Current.isTrailingComment() && !Previous.is(tok::lessless) &&
         Previous.getPrecedence() != prec::Assignment &&
         State.Stack.back().BreakBeforeParameter)
       return true;
+  } else {
+    if (Current.is(TT_BinaryOperator) && Previous.EndsBinaryExpression &&
+        State.Stack.back().BreakBeforeParameter)
+      return true;
   }
 
   // Same as above, but for the first "<<" operator.
-  if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator &&
+  if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
       State.Stack.back().BreakBeforeParameter &&
       State.Stack.back().FirstLessLess == 0)
     return true;
 
-  if (Current.Type == TT_SelectorName &&
-      State.Stack.back().ObjCSelectorNameFound &&
+  if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
       State.Stack.back().BreakBeforeParameter)
     return true;
-  if (Previous.ClosesTemplateDeclaration && Current.NestingLevel == 0 &&
-      !Current.isTrailingComment())
-    return true;
+  if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
+    if (Previous.ClosesTemplateDeclaration)
+      return true;
+    if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
+        Current.isNot(TT_LeadingJavaAnnotation))
+      return true;
+  }
 
   // If the return type spans multiple lines, wrap before the function name.
-  if ((Current.Type == TT_FunctionDeclarationName ||
-       Current.is(tok::kw_operator)) &&
+  if (Current.isOneOf(TT_FunctionDeclarationName, tok::kw_operator) &&
       State.Stack.back().BreakBeforeParameter)
     return true;
 
@@ -230,6 +232,10 @@
       Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
     return true;
 
+  if (Current.is(tok::lessless) && Previous.is(tok::identifier) &&
+      Previous.TokenText == "endl")
+    return true;
+
   return false;
 }
 
@@ -239,16 +245,22 @@
   const FormatToken &Current = *State.NextToken;
 
   assert(!State.Stack.empty());
-  if ((Current.Type == TT_ImplicitStringLiteral &&
+  if ((Current.is(TT_ImplicitStringLiteral) &&
        (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
             tok::pp_not_keyword))) {
-    // FIXME: Is this correct?
-    int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
-                               State.NextToken->WhitespaceRange.getEnd()) -
-                           SourceMgr.getSpellingColumnNumber(
-                               State.NextToken->WhitespaceRange.getBegin());
-    State.Column += WhitespaceLength;
+    unsigned EndColumn =
+        SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
+    if (Current.LastNewlineOffset != 0) {
+      // If there is a newline within this token, the final column will solely
+      // determined by the current end column.
+      State.Column = EndColumn;
+    } else {
+      unsigned StartColumn =
+          SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
+      assert(EndColumn >= StartColumn);
+      State.Column += EndColumn - StartColumn;
+    }
     moveStateToNextToken(State, DryRun, /*Newline=*/false);
     return 0;
   }
@@ -288,7 +300,7 @@
     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
                                   Spaces, State.Column + Spaces);
 
-  if (Current.Type == TT_SelectorName &&
+  if (Current.is(TT_SelectorName) &&
       !State.Stack.back().ObjCSelectorNameFound) {
     if (Current.LongestObjCSelectorName == 0)
       State.Stack.back().AlignColons = false;
@@ -300,9 +312,9 @@
       State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
   }
 
-  if (Style.AlignAfterOpenBracket &&
-      Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
-      (Current.Type != TT_LineComment || Previous.BlockKind == BK_BracedInit))
+  if (Style.AlignAfterOpenBracket && Previous.opensScope() &&
+      Previous.isNot(TT_ObjCMethodExpr) &&
+      (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
     State.Stack.back().Indent = State.Column + Spaces;
   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
     State.Stack.back().NoLineBreak = true;
@@ -323,26 +335,27 @@
 
   State.Column += Spaces;
   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
-      Previous.Previous && Previous.Previous->isOneOf(tok::kw_if, tok::kw_for))
+      Previous.Previous &&
+      Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
     // Treat the condition inside an if as if it was a second function
     // parameter, i.e. let nested calls have a continuation indent.
     State.Stack.back().LastSpace = State.Column;
-  else if (!Current.isOneOf(tok::comment, tok::caret) &&
-           (Previous.is(tok::comma) ||
-            (Previous.is(tok::colon) && Previous.Type == TT_ObjCMethodExpr)))
+    State.Stack.back().NestedBlockIndent = State.Column;
+  } else if (!Current.isOneOf(tok::comment, tok::caret) &&
+             (Previous.is(tok::comma) ||
+              (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
     State.Stack.back().LastSpace = State.Column;
-  else if ((Previous.Type == TT_BinaryOperator ||
-            Previous.Type == TT_ConditionalExpr ||
-            Previous.Type == TT_CtorInitializerColon) &&
-           ((Previous.getPrecedence() != prec::Assignment &&
-             (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
-              !Previous.LastOperator)) ||
-            Current.StartsBinaryExpression))
+  } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
+                               TT_CtorInitializerColon)) &&
+             ((Previous.getPrecedence() != prec::Assignment &&
+               (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
+                !Previous.LastOperator)) ||
+              Current.StartsBinaryExpression)) {
     // Always indent relative to the RHS of the expression unless this is a
     // simple assignment without binary expression on the RHS. Also indent
     // relative to unary operators and the colons of constructor initializers.
     State.Stack.back().LastSpace = State.Column;
-  else if (Previous.Type == TT_InheritanceColon) {
+  } else if (Previous.is(TT_InheritanceColon)) {
     State.Stack.back().Indent = State.Column;
     State.Stack.back().LastSpace = State.Column;
   } else if (Previous.opensScope()) {
@@ -356,7 +369,7 @@
       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
       HasTrailingCall = Next && Next->isMemberAccess();
     }
-    if (HasTrailingCall &&
+    if (HasTrailingCall && State.Stack.size() > 1 &&
         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
       State.Stack.back().LastSpace = State.Column;
   }
@@ -393,10 +406,11 @@
     Penalty += Style.PenaltyBreakFirstLessLess;
 
   State.Column = getNewLineColumn(State);
+  State.Stack.back().NestedBlockIndent = State.Column;
   if (NextNonComment->isMemberAccess()) {
     if (State.Stack.back().CallContinuation == 0)
       State.Stack.back().CallContinuation = State.Column;
-  } else if (NextNonComment->Type == TT_SelectorName) {
+  } else if (NextNonComment->is(TT_SelectorName)) {
     if (!State.Stack.back().ObjCSelectorNameFound) {
       if (NextNonComment->LongestObjCSelectorName == 0) {
         State.Stack.back().AlignColons = false;
@@ -409,8 +423,7 @@
       State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
     }
   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
-             (PreviousNonComment->Type == TT_ObjCMethodExpr ||
-              PreviousNonComment->Type == TT_DictLiteral)) {
+             PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
     // method expression, the block should be aligned to the line starting it,
     // e.g.:
@@ -428,10 +441,9 @@
 
   if ((Previous.isOneOf(tok::comma, tok::semi) &&
        !State.Stack.back().AvoidBinPacking) ||
-      Previous.Type == TT_BinaryOperator)
+      Previous.is(TT_BinaryOperator))
     State.Stack.back().BreakBeforeParameter = false;
-  if ((Previous.Type == TT_TemplateCloser ||
-       Previous.Type == TT_JavaAnnotation) &&
+  if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
       Current.NestingLevel == 0)
     State.Stack.back().BreakBeforeParameter = false;
   if (NextNonComment->is(tok::question) ||
@@ -453,11 +465,10 @@
 
   // Any break on this level means that the parent level has been broken
   // and we need to avoid bin packing there.
-  bool JavaScriptFormat = Style.Language == FormatStyle::LK_JavaScript &&
-                          Current.is(tok::r_brace) &&
-                          State.Stack.size() > 1 &&
-                          State.Stack[State.Stack.size() - 2].JSFunctionInlined;
-  if (!JavaScriptFormat) {
+  bool NestedBlockSpecialCase =
+      Current.is(tok::r_brace) && State.Stack.size() > 1 &&
+      State.Stack[State.Stack.size() - 2].NestedBlockInlined;
+  if (!NestedBlockSpecialCase) {
     for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
       State.Stack[i].BreakBeforeParameter = true;
     }
@@ -465,30 +476,27 @@
 
   if (PreviousNonComment &&
       !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
-      (PreviousNonComment->Type != TT_TemplateCloser ||
+      (PreviousNonComment->isNot(TT_TemplateCloser) ||
        Current.NestingLevel != 0) &&
-      PreviousNonComment->Type != TT_BinaryOperator &&
-      PreviousNonComment->Type != TT_JavaAnnotation &&
-      PreviousNonComment->Type != TT_LeadingJavaAnnotation &&
-      Current.Type != TT_BinaryOperator && !PreviousNonComment->opensScope())
+      !PreviousNonComment->isOneOf(TT_BinaryOperator, TT_JavaAnnotation,
+                                   TT_LeadingJavaAnnotation) &&
+      Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
     State.Stack.back().BreakBeforeParameter = true;
 
   // If we break after { or the [ of an array initializer, we should also break
   // before the corresponding } or ].
   if (PreviousNonComment &&
-      (PreviousNonComment->is(tok::l_brace) ||
-       PreviousNonComment->Type == TT_ArrayInitializerLSquare))
+      (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
     State.Stack.back().BreakBeforeClosingBrace = true;
 
   if (State.Stack.back().AvoidBinPacking) {
     // If we are breaking after '(', '{', '<', this is not bin packing
     // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
     // dict/object literal.
-    if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
-          Previous.Type == TT_BinaryOperator) ||
+    if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
          State.Line->MustBeDeclaration) ||
-        Previous.Type == TT_DictLiteral)
+        Previous.is(TT_DictLiteral))
       State.Stack.back().BreakBeforeParameter = true;
   }
 
@@ -518,19 +526,16 @@
   if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
     return Current.NestingLevel == 0 ? State.FirstIndent
                                      : State.Stack.back().Indent;
-  if (Current.isOneOf(tok::r_brace, tok::r_square)) {
-    if (State.Stack.size() > 1 &&
-        State.Stack[State.Stack.size() - 2].JSFunctionInlined)
-      return State.FirstIndent;
-    if (Current.closesBlockTypeList(Style) ||
-        (Current.MatchingParen &&
-         Current.MatchingParen->BlockKind == BK_BracedInit))
+  if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
+    if (Current.closesBlockTypeList(Style))
+      return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
+    if (Current.MatchingParen &&
+        Current.MatchingParen->BlockKind == BK_BracedInit)
       return State.Stack[State.Stack.size() - 2].LastSpace;
-    else
-      return State.FirstIndent;
+    return State.FirstIndent;
   }
   if (Current.is(tok::identifier) && Current.Next &&
-      Current.Next->Type == TT_DictLiteral)
+      Current.Next->is(TT_DictLiteral))
     return State.Stack.back().Indent;
   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
     return State.StartOfStringLiteral;
@@ -538,62 +543,53 @@
       State.Stack.back().FirstLessLess != 0)
     return State.Stack.back().FirstLessLess;
   if (NextNonComment->isMemberAccess()) {
-    if (State.Stack.back().CallContinuation == 0) {
+    if (State.Stack.back().CallContinuation == 0)
       return ContinuationIndent;
-    } else {
-      return State.Stack.back().CallContinuation;
-    }
+    return State.Stack.back().CallContinuation;
   }
   if (State.Stack.back().QuestionColumn != 0 &&
       ((NextNonComment->is(tok::colon) &&
-        NextNonComment->Type == TT_ConditionalExpr) ||
-       Previous.Type == TT_ConditionalExpr))
+        NextNonComment->is(TT_ConditionalExpr)) ||
+       Previous.is(TT_ConditionalExpr)))
     return State.Stack.back().QuestionColumn;
   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
     return State.Stack.back().VariablePos;
   if ((PreviousNonComment &&
        (PreviousNonComment->ClosesTemplateDeclaration ||
-        PreviousNonComment->Type == TT_AttributeParen ||
-        PreviousNonComment->Type == TT_JavaAnnotation ||
-        PreviousNonComment->Type == TT_LeadingJavaAnnotation)) ||
+        PreviousNonComment->isOneOf(TT_AttributeParen, TT_JavaAnnotation,
+                                    TT_LeadingJavaAnnotation))) ||
       (!Style.IndentWrappedFunctionNames &&
-       (NextNonComment->is(tok::kw_operator) ||
-        NextNonComment->Type == TT_FunctionDeclarationName)))
+       NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
-  if (NextNonComment->Type == TT_SelectorName) {
+  if (NextNonComment->is(TT_SelectorName)) {
     if (!State.Stack.back().ObjCSelectorNameFound) {
-      if (NextNonComment->LongestObjCSelectorName == 0) {
+      if (NextNonComment->LongestObjCSelectorName == 0)
         return State.Stack.back().Indent;
-      } else {
-        return State.Stack.back().Indent +
-               NextNonComment->LongestObjCSelectorName -
-               NextNonComment->ColumnWidth;
-      }
-    } else if (!State.Stack.back().AlignColons) {
-      return State.Stack.back().Indent;
-    } else if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) {
-      return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
-    } else {
-      return State.Stack.back().Indent;
+      return State.Stack.back().Indent +
+             NextNonComment->LongestObjCSelectorName -
+             NextNonComment->ColumnWidth;
     }
+    if (!State.Stack.back().AlignColons)
+      return State.Stack.back().Indent;
+    if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
+      return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
+    return State.Stack.back().Indent;
   }
-  if (NextNonComment->Type == TT_ArraySubscriptLSquare) {
+  if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
     if (State.Stack.back().StartOfArraySubscripts != 0)
       return State.Stack.back().StartOfArraySubscripts;
-    else
-      return ContinuationIndent;
+    return ContinuationIndent;
   }
-  if (NextNonComment->Type == TT_StartOfName ||
+  if (NextNonComment->is(TT_StartOfName) ||
       Previous.isOneOf(tok::coloncolon, tok::equal)) {
     return ContinuationIndent;
   }
   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
-      (PreviousNonComment->Type == TT_ObjCMethodExpr ||
-       PreviousNonComment->Type == TT_DictLiteral))
+      PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
     return ContinuationIndent;
-  if (NextNonComment->Type == TT_CtorInitializerColon)
+  if (NextNonComment->is(TT_CtorInitializerColon))
     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
-  if (NextNonComment->Type == TT_CtorInitializerComma)
+  if (NextNonComment->is(TT_CtorInitializerComma))
     return State.Stack.back().Indent;
   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
       !Current.isOneOf(tok::colon, tok::comment))
@@ -611,18 +607,18 @@
   assert(State.Stack.size());
   const FormatToken &Current = *State.NextToken;
 
-  if (Current.Type == TT_InheritanceColon)
+  if (Current.is(TT_InheritanceColon))
     State.Stack.back().AvoidBinPacking = true;
-  if (Current.is(tok::lessless) && Current.Type != TT_OverloadedOperator) {
+  if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
     if (State.Stack.back().FirstLessLess == 0)
       State.Stack.back().FirstLessLess = State.Column;
     else
       State.Stack.back().LastOperatorWrapped = Newline;
   }
-  if ((Current.Type == TT_BinaryOperator && Current.isNot(tok::lessless)) ||
-      Current.Type == TT_ConditionalExpr)
+  if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
+      Current.is(TT_ConditionalExpr))
     State.Stack.back().LastOperatorWrapped = Newline;
-  if (Current.Type == TT_ArraySubscriptLSquare &&
+  if (Current.is(TT_ArraySubscriptLSquare) &&
       State.Stack.back().StartOfArraySubscripts == 0)
     State.Stack.back().StartOfArraySubscripts = State.Column;
   if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
@@ -636,9 +632,9 @@
   if (Current.isMemberAccess())
     State.Stack.back().StartOfFunctionCall =
         Current.LastOperator ? 0 : State.Column + Current.ColumnWidth;
-  if (Current.Type == TT_SelectorName)
+  if (Current.is(TT_SelectorName))
     State.Stack.back().ObjCSelectorNameFound = true;
-  if (Current.Type == TT_CtorInitializerColon) {
+  if (Current.is(TT_CtorInitializerColon)) {
     // Indent 2 from the column, so:
     // SomeClass::SomeClass()
     //     : First(...), ...
@@ -646,6 +642,7 @@
     //       ^ line up here.
     State.Stack.back().Indent =
         State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
+    State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
       State.Stack.back().AvoidBinPacking = true;
     State.Stack.back().BreakBeforeParameter = false;
@@ -654,7 +651,7 @@
   // In ObjC method declaration we align on the ":" of parameters, but we need
   // to ensure that we indent parameters on subsequent lines by at least our
   // continuation indent width.
-  if (Current.Type == TT_ObjCMethodSpecifier)
+  if (Current.is(TT_ObjCMethodSpecifier))
     State.Stack.back().Indent += Style.ContinuationIndentWidth;
 
   // Insert scopes created by fake parenthesis.
@@ -666,22 +663,21 @@
   //     foo();
   //     bar();
   //   }, a, b, c);
-  if (Style.Language == FormatStyle::LK_JavaScript) {
-    if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
-        State.Stack.size() > 1) {
-      if (State.Stack[State.Stack.size() - 2].JSFunctionInlined && Newline) {
-        for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
-          State.Stack[i].NoLineBreak = true;
-        }
+  if (Current.isNot(tok::comment) && Previous && Previous->is(tok::l_brace) &&
+      State.Stack.size() > 1) {
+    if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) {
+      for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
+        State.Stack[i].NoLineBreak = true;
       }
-      State.Stack[State.Stack.size() - 2].JSFunctionInlined = false;
     }
-    if (Current.is(Keywords.kw_function))
-      State.Stack.back().JSFunctionInlined =
-          !Newline && Previous && Previous->Type != TT_DictLiteral &&
-          // If the unnamed function is the only parameter to another function,
-          // we can likely inline it and come up with a good format.
-          (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
+    State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
+  }
+  if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
+                   Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
+      !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
+    State.Stack.back().NestedBlockInlined =
+        !Newline &&
+        (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
   }
 
   moveStatePastFakeLParens(State, Newline);
@@ -727,8 +723,9 @@
   // is special cased.
   bool SkipFirstExtraIndent =
       (Previous && (Previous->opensScope() || Previous->is(tok::kw_return) ||
-                    Previous->getPrecedence() == prec::Assignment ||
-                    Previous->Type == TT_ObjCMethodExpr));
+                    (Previous->getPrecedence() == prec::Assignment &&
+                     Style.AlignOperands) ||
+                    Previous->is(TT_ObjCMethodExpr)));
   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
            I = Current.FakeLParens.rbegin(),
            E = Current.FakeLParens.rend();
@@ -740,6 +737,7 @@
     // a builder type call after 'return' or, if the alignment after opening
     // brackets is disabled.
     if (!Current.isTrailingComment() &&
+        (Style.AlignOperands || *I < prec::Assignment) &&
         (!Previous || Previous->isNot(tok::kw_return) ||
          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
         (Style.AlignAfterOpenBracket || *I != prec::Comma ||
@@ -753,14 +751,14 @@
     // Exclude relational operators, as there, it is always more desirable to
     // have the LHS 'left' of the RHS.
     if (Previous && Previous->getPrecedence() > prec::Assignment &&
-        (Previous->Type == TT_BinaryOperator ||
-         Previous->Type == TT_ConditionalExpr) &&
+        Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
         Previous->getPrecedence() != prec::Relational) {
-      bool BreakBeforeOperator = Previous->is(tok::lessless) ||
-                                 (Previous->Type == TT_BinaryOperator &&
-                                  Style.BreakBeforeBinaryOperators) ||
-                                 (Previous->Type == TT_ConditionalExpr &&
-                                  Style.BreakBeforeTernaryOperators);
+      bool BreakBeforeOperator =
+          Previous->is(tok::lessless) ||
+          (Previous->is(TT_BinaryOperator) &&
+           Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
+          (Previous->is(TT_ConditionalExpr) &&
+           Style.BreakBeforeTernaryOperators);
       if ((!Newline && !BreakBeforeOperator) ||
           (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
         NewParenState.NoLineBreak = true;
@@ -774,7 +772,8 @@
     //       ParameterToInnerFunction));
     if (*I > prec::Unknown)
       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
-    NewParenState.StartOfFunctionCall = State.Column;
+    if (*I != prec::Conditional)
+      NewParenState.StartOfFunctionCall = State.Column;
 
     // Always indent conditional expressions. Never indent expression where
     // the 'operator' is ',', ';' or an assignment (i.e. *I <=
@@ -782,7 +781,7 @@
     // other expression, unless the indentation needs to be skipped.
     if (*I == prec::Conditional ||
         (!SkipFirstExtraIndent && *I > prec::Assignment &&
-         !Current.isTrailingComment() && !Style.BreakBeforeBinaryOperators))
+         !Current.isTrailingComment()))
       NewParenState.Indent += Style.ContinuationIndentWidth;
     if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
       NewParenState.BreakBeforeParameter = false;
@@ -791,11 +790,9 @@
   }
 }
 
-// Remove the fake r_parens after 'Tok'.
-static void consumeRParens(LineState& State, const FormatToken &Tok) {
-  for (unsigned i = 0, e = Tok.FakeRParens; i != e; ++i) {
+void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
+  for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
     unsigned VariablePos = State.Stack.back().VariablePos;
-    assert(State.Stack.size() > 1);
     if (State.Stack.size() == 1) {
       // Do not pop the last element.
       break;
@@ -805,46 +802,6 @@
   }
 }
 
-// Returns whether 'Tok' opens or closes a scope requiring special handling
-// of the subsequent fake r_parens.
-//
-// For example, if this is an l_brace starting a nested block, we pretend (wrt.
-// to indentation) that we already consumed the corresponding r_brace. Thus, we
-// remove all ParenStates caused by fake parentheses that end at the r_brace.
-// The net effect of this is that we don't indent relative to the l_brace, if
-// the nested block is the last parameter of a function. This formats:
-//
-//   SomeFunction(a, [] {
-//     f();  // break
-//   });
-//
-// instead of:
-//   SomeFunction(a, [] {
-//                     f();  // break
-//                   });
-static bool fakeRParenSpecialCase(const LineState &State) {
-  const FormatToken &Tok = *State.NextToken;
-  if (!Tok.MatchingParen)
-    return false;
-  const FormatToken *Left = &Tok;
-  if (Tok.isOneOf(tok::r_brace, tok::r_square))
-    Left = Tok.MatchingParen;
-  return !State.Stack.back().HasMultipleNestedBlocks &&
-         Left->isOneOf(tok::l_brace, tok::l_square) &&
-         (Left->BlockKind == BK_Block ||
-          Left->Type == TT_ArrayInitializerLSquare ||
-          Left->Type == TT_DictLiteral);
-}
-
-void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
-  // Don't remove FakeRParens attached to r_braces that surround nested blocks
-  // as they will have been removed early (see above).
-  if (fakeRParenSpecialCase(State))
-    return;
-
-  consumeRParens(State, *State.NextToken);
-}
-
 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
                                                     bool Newline) {
   const FormatToken &Current = *State.NextToken;
@@ -860,26 +817,19 @@
   unsigned NewIndentLevel = State.Stack.back().IndentLevel;
   bool AvoidBinPacking;
   bool BreakBeforeParameter = false;
-  if (Current.is(tok::l_brace) || Current.Type == TT_ArrayInitializerLSquare) {
-    if (fakeRParenSpecialCase(State))
-      consumeRParens(State, *Current.MatchingParen);
-
-    NewIndent = State.Stack.back().LastSpace;
+  if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
     if (Current.opensBlockTypeList(Style)) {
-      NewIndent += Style.IndentWidth;
+      NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
       NewIndent = std::min(State.Column + 2, NewIndent);
       ++NewIndentLevel;
     } else {
-      NewIndent += Style.ContinuationIndentWidth;
-      NewIndent = std::min(State.Column + 1, NewIndent);
+      NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
     }
     const FormatToken *NextNoComment = Current.getNextNonComment();
-    AvoidBinPacking = Current.Type == TT_ArrayInitializerLSquare ||
-                      Current.Type == TT_DictLiteral ||
-                      Style.Language == FormatStyle::LK_Proto ||
-                      !Style.BinPackParameters ||
-                      (NextNoComment &&
-                       NextNoComment->Type == TT_DesignatedInitializerPeriod);
+    AvoidBinPacking =
+        Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
+        Style.Language == FormatStyle::LK_Proto || !Style.BinPackParameters ||
+        (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
   } else {
     NewIndent = Style.ContinuationIndentWidth +
                 std::max(State.Stack.back().LastSpace,
@@ -893,17 +843,19 @@
            Current.PackingKind == PPK_Inconclusive)));
     // If this '[' opens an ObjC call, determine whether all parameters fit
     // into one line and put one per line if they don't.
-    if (Current.Type == TT_ObjCMethodExpr && Style.ColumnLimit != 0 &&
+    if (Current.is(TT_ObjCMethodExpr) && Style.ColumnLimit != 0 &&
         getLengthToMatchingParen(Current) + State.Column >
             getColumnLimit(State))
       BreakBeforeParameter = true;
   }
   bool NoLineBreak = State.Stack.back().NoLineBreak ||
-                     (Current.Type == TT_TemplateOpener &&
+                     (Current.is(TT_TemplateOpener) &&
                       State.Stack.back().ContainsUnwrappedBuilder);
+  unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
   State.Stack.push_back(ParenState(NewIndent, NewIndentLevel,
                                    State.Stack.back().LastSpace,
                                    AvoidBinPacking, NoLineBreak));
+  State.Stack.back().NestedBlockIndent = NestedBlockIndent;
   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
   State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
 }
@@ -918,7 +870,7 @@
   if (State.Stack.size() > 1 &&
       (Current.isOneOf(tok::r_paren, tok::r_square) ||
        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
-       State.NextToken->Type == TT_TemplateCloser))
+       State.NextToken->is(TT_TemplateCloser)))
     State.Stack.pop_back();
 
   if (Current.is(tok::r_square)) {
@@ -930,20 +882,17 @@
 }
 
 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
-  // If we have already found more than one lambda introducers on this level, we
-  // opt out of this because similarity between the lambdas is more important.
-  if (fakeRParenSpecialCase(State))
-    consumeRParens(State, *State.NextToken->MatchingParen);
-
+  unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
   // ObjC block sometimes follow special indentation rules.
-  unsigned NewIndent = State.Stack.back().LastSpace +
-                       (State.NextToken->Type == TT_ObjCBlockLBrace
-                            ? Style.ObjCBlockIndentWidth
-                            : Style.IndentWidth);
+  unsigned NewIndent =
+      NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
+                               ? Style.ObjCBlockIndentWidth
+                               : Style.IndentWidth);
   State.Stack.push_back(ParenState(
       NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
       State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
       State.Stack.back().NoLineBreak));
+  State.Stack.back().NestedBlockIndent = NestedBlockIndent;
   State.Stack.back().BreakBeforeParameter = true;
 }
 
@@ -963,34 +912,17 @@
   return 0;
 }
 
-static bool getRawStringLiteralPrefixPostfix(StringRef Text, StringRef &Prefix,
-                                             StringRef &Postfix) {
-  if (Text.startswith(Prefix = "R\"") || Text.startswith(Prefix = "uR\"") ||
-      Text.startswith(Prefix = "UR\"") || Text.startswith(Prefix = "u8R\"") ||
-      Text.startswith(Prefix = "LR\"")) {
-    size_t ParenPos = Text.find('(');
-    if (ParenPos != StringRef::npos) {
-      StringRef Delimiter =
-          Text.substr(Prefix.size(), ParenPos - Prefix.size());
-      Prefix = Text.substr(0, ParenPos + 1);
-      Postfix = Text.substr(Text.size() - 2 - Delimiter.size());
-      return Postfix.front() == ')' && Postfix.back() == '"' &&
-             Postfix.substr(1).startswith(Delimiter);
-    }
-  }
-  return false;
-}
-
 unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
                                                     LineState &State,
                                                     bool DryRun) {
   // Don't break multi-line tokens other than block comments. Instead, just
   // update the state.
-  if (Current.Type != TT_BlockComment && Current.IsMultiline)
+  if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
     return addMultilineToken(Current, State);
 
-  // Don't break implicit string literals.
-  if (Current.Type == TT_ImplicitStringLiteral)
+  // Don't break implicit string literals or import statements.
+  if (Current.is(TT_ImplicitStringLiteral) ||
+      State.Line->Type == LT_ImportStatement)
     return 0;
 
   if (!Current.isStringLiteral() && !Current.is(tok::comment))
@@ -1001,6 +933,12 @@
   unsigned ColumnLimit = getColumnLimit(State);
 
   if (Current.isStringLiteral()) {
+    // FIXME: String literal breaking is currently disabled for Java and JS, as
+    // it requires strings to be merged using "+" which we don't support.
+    if (Style.Language == FormatStyle::LK_Java ||
+        Style.Language == FormatStyle::LK_JavaScript)
+      return 0;
+
     // Don't break string literals inside preprocessor directives (except for
     // #define directives, as their contents are stored in separate lines and
     // are not affected by this check).
@@ -1031,23 +969,22 @@
           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
           Text.startswith(Prefix = "u8\"") ||
           Text.startswith(Prefix = "L\""))) ||
-        (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")")) ||
-        getRawStringLiteralPrefixPostfix(Text, Prefix, Postfix)) {
+        (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
       Token.reset(new BreakableStringLiteral(
           Current, State.Line->Level, StartColumn, Prefix, Postfix,
           State.Line->InPPDirective, Encoding, Style));
     } else {
       return 0;
     }
-  } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
+  } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
       return 0;
     Token.reset(new BreakableBlockComment(
         Current, State.Line->Level, StartColumn, Current.OriginalColumn,
         !Current.Previous, State.Line->InPPDirective, Encoding, Style));
-  } else if (Current.Type == TT_LineComment &&
+  } else if (Current.is(TT_LineComment) &&
              (Current.Previous == nullptr ||
-              Current.Previous->Type != TT_ImplicitStringLiteral)) {
+              Current.Previous->isNot(TT_ImplicitStringLiteral))) {
     if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
       return 0;
     Token.reset(new BreakableLineComment(Current, State.Line->Level,
@@ -1121,7 +1058,7 @@
     // If we break the token inside a parameter list, we need to break before
     // the next parameter on all levels, so that the next parameter is clearly
     // visible. Line comments already introduce a break.
-    if (Current.Type != TT_LineComment) {
+    if (Current.isNot(TT_LineComment)) {
       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
         State.Stack[i].BreakBeforeParameter = true;
     }
@@ -1141,7 +1078,7 @@
 
 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
   const FormatToken &Current = *State.NextToken;
-  if (!Current.isStringLiteral() || Current.Type == TT_ImplicitStringLiteral)
+  if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
     return false;
   // We never consider raw string literals "multiline" for the purpose of
   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
@@ -1153,8 +1090,9 @@
   if (Current.getNextNonComment() &&
       Current.getNextNonComment()->isStringLiteral())
     return true; // Implicit concatenation.
-  if (State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
-      Style.ColumnLimit)
+  if (Style.ColumnLimit != 0 &&
+      State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
+          Style.ColumnLimit)
     return true; // String will be split.
   return false;
 }
diff --git a/lib/Format/ContinuationIndenter.h b/lib/Format/ContinuationIndenter.h
index 5abbe7e..36691d9 100644
--- a/lib/Format/ContinuationIndenter.h
+++ b/lib/Format/ContinuationIndenter.h
@@ -148,14 +148,15 @@
   ParenState(unsigned Indent, unsigned IndentLevel, unsigned LastSpace,
              bool AvoidBinPacking, bool NoLineBreak)
       : Indent(Indent), IndentLevel(IndentLevel), LastSpace(LastSpace),
-        FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
+        NestedBlockIndent(Indent), FirstLessLess(0),
+        BreakBeforeClosingBrace(false), QuestionColumn(0),
         AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
         NoLineBreak(NoLineBreak), LastOperatorWrapped(true), ColonPos(0),
         StartOfFunctionCall(0), StartOfArraySubscripts(0),
         NestedNameSpecifierContinuation(0), CallContinuation(0), VariablePos(0),
         ContainsLineBreak(false), ContainsUnwrappedBuilder(0),
         AlignColons(true), ObjCSelectorNameFound(false),
-        HasMultipleNestedBlocks(false), JSFunctionInlined(false) {}
+        HasMultipleNestedBlocks(false), NestedBlockInlined(false) {}
 
   /// \brief The position to which a specific parenthesis level needs to be
   /// indented.
@@ -171,6 +172,10 @@
   ///                             OtherParameter));
   unsigned LastSpace;
 
+  /// \brief If a block relative to this parenthesis level gets wrapped, indent
+  /// it this much.
+  unsigned NestedBlockIndent;
+
   /// \brief The position the first "<<" operator encountered on each level.
   ///
   /// Used to align "<<" operators. 0 if no such operator has been encountered
@@ -256,15 +261,17 @@
   /// the same token.
   bool HasMultipleNestedBlocks;
 
-  // \brief The previous JavaScript 'function' keyword is not wrapped to a new
-  // line.
-  bool JSFunctionInlined;
+  // \brief The start of a nested block (e.g. lambda introducer in C++ or
+  // "function" in JavaScript) is not wrapped to a new line.
+  bool NestedBlockInlined;
 
   bool operator<(const ParenState &Other) const {
     if (Indent != Other.Indent)
       return Indent < Other.Indent;
     if (LastSpace != Other.LastSpace)
       return LastSpace < Other.LastSpace;
+    if (NestedBlockIndent != Other.NestedBlockIndent)
+      return NestedBlockIndent < Other.NestedBlockIndent;
     if (FirstLessLess != Other.FirstLessLess)
       return FirstLessLess < Other.FirstLessLess;
     if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
@@ -293,8 +300,8 @@
       return ContainsLineBreak < Other.ContainsLineBreak;
     if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
       return ContainsUnwrappedBuilder < Other.ContainsUnwrappedBuilder;
-    if (JSFunctionInlined != Other.JSFunctionInlined)
-      return JSFunctionInlined < Other.JSFunctionInlined;
+    if (NestedBlockInlined != Other.NestedBlockInlined)
+      return NestedBlockInlined < Other.NestedBlockInlined;
     return false;
   }
 };
diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp
index 729ca97..035dc73 100644
--- a/lib/Format/Format.cpp
+++ b/lib/Format/Format.cpp
@@ -15,6 +15,7 @@
 
 #include "ContinuationIndenter.h"
 #include "TokenAnnotator.h"
+#include "UnwrappedLineFormatter.h"
 #include "UnwrappedLineParser.h"
 #include "WhitespaceManager.h"
 #include "clang/Basic/Diagnostic.h"
@@ -74,6 +75,7 @@
     IO.enumCase(Value, "All", FormatStyle::SFS_All);
     IO.enumCase(Value, "true", FormatStyle::SFS_All);
     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
+    IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
   }
 };
 
@@ -107,10 +109,8 @@
   }
 };
 
-template <>
-struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
-  static void enumeration(IO &IO,
-                          FormatStyle::PointerAlignmentStyle &Value) {
+template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
+  static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
@@ -142,8 +142,8 @@
     IO.mapOptional("Language", Style.Language);
 
     if (IO.outputting()) {
-      StringRef StylesArray[] = { "LLVM",    "Google", "Chromium",
-                                  "Mozilla", "WebKit", "GNU" };
+      StringRef StylesArray[] = {"LLVM",    "Google", "Chromium",
+                                 "Mozilla", "WebKit", "GNU"};
       ArrayRef<StringRef> Styles(StylesArray);
       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
         StringRef StyleName(Styles[i]);
@@ -172,6 +172,7 @@
     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
     IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
+    IO.mapOptional("AlignOperands", Style.AlignOperands);
     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
                    Style.AllowAllParametersOfDeclarationOnNextLine);
@@ -270,7 +271,7 @@
 // will be used to get default values for missing keys.
 // If the first element has no Language specified, it will be treated as the
 // default one for the following elements.
-template <> struct DocumentListTraits<std::vector<FormatStyle> > {
+template <> struct DocumentListTraits<std::vector<FormatStyle>> {
   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
     return Seq.size();
   }
@@ -326,6 +327,7 @@
   LLVMStyle.AccessModifierOffset = -2;
   LLVMStyle.AlignEscapedNewlinesLeft = false;
   LLVMStyle.AlignAfterOpenBracket = true;
+  LLVMStyle.AlignOperands = true;
   LLVMStyle.AlignTrailingComments = true;
   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
@@ -414,7 +416,11 @@
 
   if (Language == FormatStyle::LK_Java) {
     GoogleStyle.AlignAfterOpenBracket = false;
-    GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+    GoogleStyle.AlignOperands = false;
+    GoogleStyle.AlignTrailingComments = false;
+    GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
+    GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
+    GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
     GoogleStyle.ColumnLimit = 100;
     GoogleStyle.SpaceAfterCStyleCast = true;
@@ -424,6 +430,7 @@
     GoogleStyle.MaxEmptyLinesToKeep = 3;
     GoogleStyle.SpacesInContainerLiterals = false;
     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+    GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
   } else if (Language == FormatStyle::LK_Proto) {
     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
     GoogleStyle.SpacesInContainerLiterals = false;
@@ -434,12 +441,18 @@
 
 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
   FormatStyle ChromiumStyle = getGoogleStyle(Language);
-  ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
-  ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
-  ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
-  ChromiumStyle.AllowShortLoopsOnASingleLine = false;
-  ChromiumStyle.BinPackParameters = false;
-  ChromiumStyle.DerivePointerAlignment = false;
+  if (Language == FormatStyle::LK_Java) {
+    ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
+    ChromiumStyle.IndentWidth = 4;
+    ChromiumStyle.ContinuationIndentWidth = 8;
+  } else {
+    ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
+    ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
+    ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
+    ChromiumStyle.AllowShortLoopsOnASingleLine = false;
+    ChromiumStyle.BinPackParameters = false;
+    ChromiumStyle.DerivePointerAlignment = false;
+  }
   return ChromiumStyle;
 }
 
@@ -462,6 +475,7 @@
   FormatStyle Style = getLLVMStyle();
   Style.AccessModifierOffset = -4;
   Style.AlignAfterOpenBracket = false;
+  Style.AlignOperands = false;
   Style.AlignTrailingComments = false;
   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
@@ -579,779 +593,15 @@
 
 namespace {
 
-bool startsExternCBlock(const AnnotatedLine &Line) {
-  const FormatToken *Next = Line.First->getNextNonComment();
-  const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
-  return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
-         NextNext && NextNext->is(tok::l_brace);
-}
-
-class NoColumnLimitFormatter {
-public:
-  NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
-
-  /// \brief Formats the line starting at \p State, simply keeping all of the
-  /// input's line breaking decisions.
-  void format(unsigned FirstIndent, const AnnotatedLine *Line) {
-    LineState State =
-        Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
-    while (State.NextToken) {
-      bool Newline =
-          Indenter->mustBreak(State) ||
-          (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
-      Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
-    }
-  }
-
-private:
-  ContinuationIndenter *Indenter;
-};
-
-class LineJoiner {
-public:
-  LineJoiner(const FormatStyle &Style) : Style(Style) {}
-
-  /// \brief Calculates how many lines can be merged into 1 starting at \p I.
-  unsigned
-  tryFitMultipleLinesInOne(unsigned Indent,
-                           SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-                           SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
-    // We can never merge stuff if there are trailing line comments.
-    const AnnotatedLine *TheLine = *I;
-    if (TheLine->Last->Type == TT_LineComment)
-      return 0;
-
-    if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
-      return 0;
-
-    unsigned Limit =
-        Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
-    // If we already exceed the column limit, we set 'Limit' to 0. The different
-    // tryMerge..() functions can then decide whether to still do merging.
-    Limit = TheLine->Last->TotalLength > Limit
-                ? 0
-                : Limit - TheLine->Last->TotalLength;
-
-    if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
-      return 0;
-
-    // FIXME: TheLine->Level != 0 might or might not be the right check to do.
-    // If necessary, change to something smarter.
-    bool MergeShortFunctions =
-        Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
-        (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
-         TheLine->Level != 0);
-
-    if (TheLine->Last->Type == TT_FunctionLBrace &&
-        TheLine->First != TheLine->Last) {
-      return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
-    }
-    if (TheLine->Last->is(tok::l_brace)) {
-      return Style.BreakBeforeBraces == FormatStyle::BS_Attach
-                 ? tryMergeSimpleBlock(I, E, Limit)
-                 : 0;
-    }
-    if (I[1]->First->Type == TT_FunctionLBrace &&
-        Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
-      // Check for Limit <= 2 to account for the " {".
-      if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
-        return 0;
-      Limit -= 2;
-
-      unsigned MergedLines = 0;
-      if (MergeShortFunctions) {
-        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
-        // If we managed to merge the block, count the function header, which is
-        // on a separate line.
-        if (MergedLines > 0)
-          ++MergedLines;
-      }
-      return MergedLines;
-    }
-    if (TheLine->First->is(tok::kw_if)) {
-      return Style.AllowShortIfStatementsOnASingleLine
-                 ? tryMergeSimpleControlStatement(I, E, Limit)
-                 : 0;
-    }
-    if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
-      return Style.AllowShortLoopsOnASingleLine
-                 ? tryMergeSimpleControlStatement(I, E, Limit)
-                 : 0;
-    }
-    if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
-      return Style.AllowShortCaseLabelsOnASingleLine
-                 ? tryMergeShortCaseLabels(I, E, Limit)
-                 : 0;
-    }
-    if (TheLine->InPPDirective &&
-        (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
-      return tryMergeSimplePPDirective(I, E, Limit);
-    }
-    return 0;
-  }
-
-private:
-  unsigned
-  tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-                            SmallVectorImpl<AnnotatedLine *>::const_iterator E,
-                            unsigned Limit) {
-    if (Limit == 0)
-      return 0;
-    if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
-      return 0;
-    if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
-      return 0;
-    if (1 + I[1]->Last->TotalLength > Limit)
-      return 0;
-    return 1;
-  }
-
-  unsigned tryMergeSimpleControlStatement(
-      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
-    if (Limit == 0)
-      return 0;
-    if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
-         Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
-        (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
-      return 0;
-    if (I[1]->InPPDirective != (*I)->InPPDirective ||
-        (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
-      return 0;
-    Limit = limitConsideringMacros(I + 1, E, Limit);
-    AnnotatedLine &Line = **I;
-    if (Line.Last->isNot(tok::r_paren))
-      return 0;
-    if (1 + I[1]->Last->TotalLength > Limit)
-      return 0;
-    if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
-                             tok::kw_while) ||
-        I[1]->First->Type == TT_LineComment)
-      return 0;
-    // Only inline simple if's (no nested if or else).
-    if (I + 2 != E && Line.First->is(tok::kw_if) &&
-        I[2]->First->is(tok::kw_else))
-      return 0;
-    return 1;
-  }
-
-  unsigned tryMergeShortCaseLabels(
-      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
-    if (Limit == 0 || I + 1 == E ||
-        I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
-      return 0;
-    unsigned NumStmts = 0;
-    unsigned Length = 0;
-    for (; NumStmts < 3; ++NumStmts) {
-      if (I + 1 + NumStmts == E)
-        break;
-      const AnnotatedLine *Line = I[1 + NumStmts];
-      if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
-        break;
-      if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
-                               tok::kw_while))
-        return 0;
-      Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
-    }
-    if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
-      return 0;
-    return NumStmts;
-  }
-
-  unsigned
-  tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-                      SmallVectorImpl<AnnotatedLine *>::const_iterator E,
-                      unsigned Limit) {
-    AnnotatedLine &Line = **I;
-
-    // Don't merge ObjC @ keywords and methods.
-    if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
-      return 0;
-
-    // Check that the current line allows merging. This depends on whether we
-    // are in a control flow statements as well as several style flags.
-    if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
-      return 0;
-    if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
-                            tok::kw_catch, tok::kw_for, tok::r_brace)) {
-      if (!Style.AllowShortBlocksOnASingleLine)
-        return 0;
-      if (!Style.AllowShortIfStatementsOnASingleLine &&
-          Line.First->is(tok::kw_if))
-        return 0;
-      if (!Style.AllowShortLoopsOnASingleLine &&
-          Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
-        return 0;
-      // FIXME: Consider an option to allow short exception handling clauses on
-      // a single line.
-      if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
-        return 0;
-    }
-
-    FormatToken *Tok = I[1]->First;
-    if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
-        (Tok->getNextNonComment() == nullptr ||
-         Tok->getNextNonComment()->is(tok::semi))) {
-      // We merge empty blocks even if the line exceeds the column limit.
-      Tok->SpacesRequiredBefore = 0;
-      Tok->CanBreakBefore = true;
-      return 1;
-    } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
-               !startsExternCBlock(Line)) {
-      // We don't merge short records.
-      if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
-        return 0;
-
-      // Check that we still have three lines and they fit into the limit.
-      if (I + 2 == E || I[2]->Type == LT_Invalid)
-        return 0;
-      Limit = limitConsideringMacros(I + 2, E, Limit);
-
-      if (!nextTwoLinesFitInto(I, Limit))
-        return 0;
-
-      // Second, check that the next line does not contain any braces - if it
-      // does, readability declines when putting it into a single line.
-      if (I[1]->Last->Type == TT_LineComment)
-        return 0;
-      do {
-        if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
-          return 0;
-        Tok = Tok->Next;
-      } while (Tok);
-
-      // Last, check that the third line starts with a closing brace.
-      Tok = I[2]->First;
-      if (Tok->isNot(tok::r_brace))
-        return 0;
-
-      return 2;
-    }
-    return 0;
-  }
-
-  /// Returns the modified column limit for \p I if it is inside a macro and
-  /// needs a trailing '\'.
-  unsigned
-  limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-                         SmallVectorImpl<AnnotatedLine *>::const_iterator E,
-                         unsigned Limit) {
-    if (I[0]->InPPDirective && I + 1 != E &&
-        !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
-      return Limit < 2 ? 0 : Limit - 2;
-    }
-    return Limit;
-  }
-
-  bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
-                           unsigned Limit) {
-    if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
-      return false;
-    return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
-  }
-
-  bool containsMustBreak(const AnnotatedLine *Line) {
-    for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-      if (Tok->MustBreakBefore)
-        return true;
-    }
-    return false;
-  }
-
-  const FormatStyle &Style;
-};
-
-class UnwrappedLineFormatter {
-public:
-  UnwrappedLineFormatter(ContinuationIndenter *Indenter,
-                         WhitespaceManager *Whitespaces,
-                         const FormatStyle &Style)
-      : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
-        Joiner(Style) {}
-
-  unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
-                  int AdditionalIndent = 0, bool FixBadIndentation = false) {
-    // Try to look up already computed penalty in DryRun-mode.
-    std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
-        &Lines, AdditionalIndent);
-    auto CacheIt = PenaltyCache.find(CacheKey);
-    if (DryRun && CacheIt != PenaltyCache.end())
-      return CacheIt->second;
-
-    assert(!Lines.empty());
-    unsigned Penalty = 0;
-    std::vector<int> IndentForLevel;
-    for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
-      IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
-    const AnnotatedLine *PreviousLine = nullptr;
-    for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
-                                                          E = Lines.end();
-         I != E; ++I) {
-      const AnnotatedLine &TheLine = **I;
-      const FormatToken *FirstTok = TheLine.First;
-      int Offset = getIndentOffset(*FirstTok);
-
-      // Determine indent and try to merge multiple unwrapped lines.
-      unsigned Indent;
-      if (TheLine.InPPDirective) {
-        Indent = TheLine.Level * Style.IndentWidth;
-      } else {
-        while (IndentForLevel.size() <= TheLine.Level)
-          IndentForLevel.push_back(-1);
-        IndentForLevel.resize(TheLine.Level + 1);
-        Indent = getIndent(IndentForLevel, TheLine.Level);
-      }
-      unsigned LevelIndent = Indent;
-      if (static_cast<int>(Indent) + Offset >= 0)
-        Indent += Offset;
-
-      // Merge multiple lines if possible.
-      unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
-      if (MergedLines > 0 && Style.ColumnLimit == 0) {
-        // Disallow line merging if there is a break at the start of one of the
-        // input lines.
-        for (unsigned i = 0; i < MergedLines; ++i) {
-          if (I[i + 1]->First->NewlinesBefore > 0)
-            MergedLines = 0;
-        }
-      }
-      if (!DryRun) {
-        for (unsigned i = 0; i < MergedLines; ++i) {
-          join(*I[i], *I[i + 1]);
-        }
-      }
-      I += MergedLines;
-
-      bool FixIndentation =
-          FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
-      if (TheLine.First->is(tok::eof)) {
-        if (PreviousLine && PreviousLine->Affected && !DryRun) {
-          // Remove the file's trailing whitespace.
-          unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
-          Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
-                                         /*IndentLevel=*/0, /*Spaces=*/0,
-                                         /*TargetColumn=*/0);
-        }
-      } else if (TheLine.Type != LT_Invalid &&
-                 (TheLine.Affected || FixIndentation)) {
-        if (FirstTok->WhitespaceRange.isValid()) {
-          if (!DryRun)
-            formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
-                             Indent, TheLine.InPPDirective);
-        } else {
-          Indent = LevelIndent = FirstTok->OriginalColumn;
-        }
-
-        // If everything fits on a single line, just put it there.
-        unsigned ColumnLimit = Style.ColumnLimit;
-        if (I + 1 != E) {
-          AnnotatedLine *NextLine = I[1];
-          if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
-            ColumnLimit = getColumnLimit(TheLine.InPPDirective);
-        }
-
-        if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
-          LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
-          while (State.NextToken) {
-            formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
-            Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
-          }
-        } else if (Style.ColumnLimit == 0) {
-          // FIXME: Implement nested blocks for ColumnLimit = 0.
-          NoColumnLimitFormatter Formatter(Indenter);
-          if (!DryRun)
-            Formatter.format(Indent, &TheLine);
-        } else {
-          Penalty += format(TheLine, Indent, DryRun);
-        }
-
-        if (!TheLine.InPPDirective)
-          IndentForLevel[TheLine.Level] = LevelIndent;
-      } else if (TheLine.ChildrenAffected) {
-        format(TheLine.Children, DryRun);
-      } else {
-        // Format the first token if necessary, and notify the WhitespaceManager
-        // about the unchanged whitespace.
-        for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
-          if (Tok == TheLine.First &&
-              (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
-            unsigned LevelIndent = Tok->OriginalColumn;
-            if (!DryRun) {
-              // Remove trailing whitespace of the previous line.
-              if ((PreviousLine && PreviousLine->Affected) ||
-                  TheLine.LeadingEmptyLinesAffected) {
-                formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
-                                 TheLine.InPPDirective);
-              } else {
-                Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
-              }
-            }
-
-            if (static_cast<int>(LevelIndent) - Offset >= 0)
-              LevelIndent -= Offset;
-            if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
-              IndentForLevel[TheLine.Level] = LevelIndent;
-          } else if (!DryRun) {
-            Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
-          }
-        }
-      }
-      if (!DryRun) {
-        for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
-          Tok->Finalized = true;
-        }
-      }
-      PreviousLine = *I;
-    }
-    PenaltyCache[CacheKey] = Penalty;
-    return Penalty;
-  }
-
-private:
-  /// \brief Formats an \c AnnotatedLine and returns the penalty.
-  ///
-  /// If \p DryRun is \c false, directly applies the changes.
-  unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
-                  bool DryRun) {
-    LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
-
-    // If the ObjC method declaration does not fit on a line, we should format
-    // it with one arg per line.
-    if (State.Line->Type == LT_ObjCMethodDecl)
-      State.Stack.back().BreakBeforeParameter = true;
-
-    // Find best solution in solution space.
-    return analyzeSolutionSpace(State, DryRun);
-  }
-
-  /// \brief An edge in the solution space from \c Previous->State to \c State,
-  /// inserting a newline dependent on the \c NewLine.
-  struct StateNode {
-    StateNode(const LineState &State, bool NewLine, StateNode *Previous)
-        : State(State), NewLine(NewLine), Previous(Previous) {}
-    LineState State;
-    bool NewLine;
-    StateNode *Previous;
-  };
-
-  /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
-  ///
-  /// In case of equal penalties, we want to prefer states that were inserted
-  /// first. During state generation we make sure that we insert states first
-  /// that break the line as late as possible.
-  typedef std::pair<unsigned, unsigned> OrderedPenalty;
-
-  /// \brief An item in the prioritized BFS search queue. The \c StateNode's
-  /// \c State has the given \c OrderedPenalty.
-  typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
-
-  /// \brief The BFS queue type.
-  typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
-                              std::greater<QueueItem> > QueueType;
-
-  /// \brief Get the offset of the line relatively to the level.
-  ///
-  /// For example, 'public:' labels in classes are offset by 1 or 2
-  /// characters to the left from their level.
-  int getIndentOffset(const FormatToken &RootToken) {
-    if (Style.Language == FormatStyle::LK_Java)
-      return 0;
-    if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
-      return Style.AccessModifierOffset;
-    return 0;
-  }
-
-  /// \brief Add a new line and the required indent before the first Token
-  /// of the \c UnwrappedLine if there was no structural parsing error.
-  void formatFirstToken(FormatToken &RootToken,
-                        const AnnotatedLine *PreviousLine, unsigned IndentLevel,
-                        unsigned Indent, bool InPPDirective) {
-    unsigned Newlines =
-        std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
-    // Remove empty lines before "}" where applicable.
-    if (RootToken.is(tok::r_brace) &&
-        (!RootToken.Next ||
-         (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
-      Newlines = std::min(Newlines, 1u);
-    if (Newlines == 0 && !RootToken.IsFirst)
-      Newlines = 1;
-    if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
-      Newlines = 0;
-
-    // Remove empty lines after "{".
-    if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
-        PreviousLine->Last->is(tok::l_brace) &&
-        PreviousLine->First->isNot(tok::kw_namespace) &&
-        !startsExternCBlock(*PreviousLine))
-      Newlines = 1;
-
-    // Insert extra new line before access specifiers.
-    if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
-        RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
-      ++Newlines;
-
-    // Remove empty lines after access specifiers.
-    if (PreviousLine && PreviousLine->First->isAccessSpecifier())
-      Newlines = std::min(1u, Newlines);
-
-    Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
-                                   Indent, InPPDirective &&
-                                               !RootToken.HasUnescapedNewline);
-  }
-
-  /// \brief Get the indent of \p Level from \p IndentForLevel.
-  ///
-  /// \p IndentForLevel must contain the indent for the level \c l
-  /// at \p IndentForLevel[l], or a value < 0 if the indent for
-  /// that level is unknown.
-  unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
-    if (IndentForLevel[Level] != -1)
-      return IndentForLevel[Level];
-    if (Level == 0)
-      return 0;
-    return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
-  }
-
-  void join(AnnotatedLine &A, const AnnotatedLine &B) {
-    assert(!A.Last->Next);
-    assert(!B.First->Previous);
-    if (B.Affected)
-      A.Affected = true;
-    A.Last->Next = B.First;
-    B.First->Previous = A.Last;
-    B.First->CanBreakBefore = true;
-    unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
-    for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
-      Tok->TotalLength += LengthA;
-      A.Last = Tok;
-    }
-  }
-
-  unsigned getColumnLimit(bool InPPDirective) const {
-    // In preprocessor directives reserve two chars for trailing " \"
-    return Style.ColumnLimit - (InPPDirective ? 2 : 0);
-  }
-
-  struct CompareLineStatePointers {
-    bool operator()(LineState *obj1, LineState *obj2) const {
-      return *obj1 < *obj2;
-    }
-  };
-
-  /// \brief Analyze the entire solution space starting from \p InitialState.
-  ///
-  /// This implements a variant of Dijkstra's algorithm on the graph that spans
-  /// the solution space (\c LineStates are the nodes). The algorithm tries to
-  /// find the shortest path (the one with lowest penalty) from \p InitialState
-  /// to a state where all tokens are placed. Returns the penalty.
-  ///
-  /// If \p DryRun is \c false, directly applies the changes.
-  unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
-    std::set<LineState *, CompareLineStatePointers> Seen;
-
-    // Increasing count of \c StateNode items we have created. This is used to
-    // create a deterministic order independent of the container.
-    unsigned Count = 0;
-    QueueType Queue;
-
-    // Insert start element into queue.
-    StateNode *Node =
-        new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
-    Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
-    ++Count;
-
-    unsigned Penalty = 0;
-
-    // While not empty, take first element and follow edges.
-    while (!Queue.empty()) {
-      Penalty = Queue.top().first.first;
-      StateNode *Node = Queue.top().second;
-      if (!Node->State.NextToken) {
-        DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
-        break;
-      }
-      Queue.pop();
-
-      // Cut off the analysis of certain solutions if the analysis gets too
-      // complex. See description of IgnoreStackForComparison.
-      if (Count > 10000)
-        Node->State.IgnoreStackForComparison = true;
-
-      if (!Seen.insert(&Node->State).second)
-        // State already examined with lower penalty.
-        continue;
-
-      FormatDecision LastFormat = Node->State.NextToken->Decision;
-      if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
-        addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
-      if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
-        addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
-    }
-
-    if (Queue.empty()) {
-      // We were unable to find a solution, do nothing.
-      // FIXME: Add diagnostic?
-      DEBUG(llvm::dbgs() << "Could not find a solution.\n");
-      return 0;
-    }
-
-    // Reconstruct the solution.
-    if (!DryRun)
-      reconstructPath(InitialState, Queue.top().second);
-
-    DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
-    DEBUG(llvm::dbgs() << "---\n");
-
-    return Penalty;
-  }
-
-  void reconstructPath(LineState &State, StateNode *Current) {
-    std::deque<StateNode *> Path;
-    // We do not need a break before the initial token.
-    while (Current->Previous) {
-      Path.push_front(Current);
-      Current = Current->Previous;
-    }
-    for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
-         I != E; ++I) {
-      unsigned Penalty = 0;
-      formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
-      Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
-
-      DEBUG({
-        if ((*I)->NewLine) {
-          llvm::dbgs() << "Penalty for placing "
-                       << (*I)->Previous->State.NextToken->Tok.getName() << ": "
-                       << Penalty << "\n";
-        }
-      });
-    }
-  }
-
-  /// \brief Add the following state to the analysis queue \c Queue.
-  ///
-  /// Assume the current state is \p PreviousNode and has been reached with a
-  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
-  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
-                           bool NewLine, unsigned *Count, QueueType *Queue) {
-    if (NewLine && !Indenter->canBreak(PreviousNode->State))
-      return;
-    if (!NewLine && Indenter->mustBreak(PreviousNode->State))
-      return;
-
-    StateNode *Node = new (Allocator.Allocate())
-        StateNode(PreviousNode->State, NewLine, PreviousNode);
-    if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
-      return;
-
-    Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
-
-    Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
-    ++(*Count);
-  }
-
-  /// \brief If the \p State's next token is an r_brace closing a nested block,
-  /// format the nested block before it.
-  ///
-  /// Returns \c true if all children could be placed successfully and adapts
-  /// \p Penalty as well as \p State. If \p DryRun is false, also directly
-  /// creates changes using \c Whitespaces.
-  ///
-  /// The crucial idea here is that children always get formatted upon
-  /// encountering the closing brace right after the nested block. Now, if we
-  /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
-  /// \c false), the entire block has to be kept on the same line (which is only
-  /// possible if it fits on the line, only contains a single statement, etc.
-  ///
-  /// If \p NewLine is true, we format the nested block on separate lines, i.e.
-  /// break after the "{", format all lines with correct indentation and the put
-  /// the closing "}" on yet another new line.
-  ///
-  /// This enables us to keep the simple structure of the
-  /// \c UnwrappedLineFormatter, where we only have two options for each token:
-  /// break or don't break.
-  bool formatChildren(LineState &State, bool NewLine, bool DryRun,
-                      unsigned &Penalty) {
-    FormatToken &Previous = *State.NextToken->Previous;
-    const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
-    if (!LBrace || LBrace->isNot(tok::l_brace) ||
-        LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
-      // The previous token does not open a block. Nothing to do. We don't
-      // assert so that we can simply call this function for all tokens.
-      return true;
-
-    if (NewLine) {
-      int AdditionalIndent =
-          State.FirstIndent - State.Line->Level * Style.IndentWidth;
-      if (State.Stack.size() < 2 ||
-          !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
-        AdditionalIndent = State.Stack.back().Indent -
-                           Previous.Children[0]->Level * Style.IndentWidth;
-      }
-
-      Penalty += format(Previous.Children, DryRun, AdditionalIndent,
-                        /*FixBadIndentation=*/true);
-      return true;
-    }
-
-    if (Previous.Children[0]->First->MustBreakBefore)
-      return false;
-
-    // Cannot merge multiple statements into a single line.
-    if (Previous.Children.size() > 1)
-      return false;
-
-    // Cannot merge into one line if this line ends on a comment.
-    if (Previous.is(tok::comment))
-      return false;
-
-    // We can't put the closing "}" on a line with a trailing comment.
-    if (Previous.Children[0]->Last->isTrailingComment())
-      return false;
-
-    // If the child line exceeds the column limit, we wouldn't want to merge it.
-    // We add +2 for the trailing " }".
-    if (Style.ColumnLimit > 0 &&
-        Previous.Children[0]->Last->TotalLength + State.Column + 2 >
-            Style.ColumnLimit)
-      return false;
-
-    if (!DryRun) {
-      Whitespaces->replaceWhitespace(
-          *Previous.Children[0]->First,
-          /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
-          /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
-    }
-    Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
-
-    State.Column += 1 + Previous.Children[0]->Last->TotalLength;
-    return true;
-  }
-
-  ContinuationIndenter *Indenter;
-  WhitespaceManager *Whitespaces;
-  FormatStyle Style;
-  LineJoiner Joiner;
-
-  llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
-
-  // Cache to store the penalty of formatting a vector of AnnotatedLines
-  // starting from a specific additional offset. Improves performance if there
-  // are many nested blocks.
-  std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
-           unsigned> PenaltyCache;
-};
-
 class FormatTokenLexer {
 public:
   FormatTokenLexer(SourceManager &SourceMgr, FileID ID, FormatStyle &Style,
                    encoding::Encoding Encoding)
       : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
-        Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
-        Style(Style), IdentTable(getFormattingLangOpts(Style)),
-        Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
-        FormattingDisabled(false) {
+        LessStashed(false), Column(0), TrailingWhitespace(0),
+        SourceMgr(SourceMgr), ID(ID), Style(Style),
+        IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
+        Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false) {
     Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
                         getFormattingLangOpts(Style)));
     Lex->SetKeepWhitespaceMode(true);
@@ -1367,7 +617,7 @@
     do {
       Tokens.push_back(getNextToken());
       tryMergePreviousTokens();
-      if (Tokens.back()->NewlinesBefore > 0)
+      if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
         FirstInLineIndex = Tokens.size() - 1;
     } while (Tokens.back()->Tok.isNot(tok::eof));
     return Tokens;
@@ -1381,18 +631,22 @@
       return;
     if (tryMergeConflictMarkers())
       return;
+    if (tryMergeLessLess())
+      return;
 
     if (Style.Language == FormatStyle::LK_JavaScript) {
       if (tryMergeJSRegexLiteral())
         return;
       if (tryMergeEscapeSequence())
         return;
+      if (tryMergeTemplateString())
+        return;
 
-      static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
-      static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
-      static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
-                                               tok::greaterequal };
-      static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
+      static tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
+      static tok::TokenKind JSNotIdentity[] = {tok::exclaimequal, tok::equal};
+      static tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
+                                              tok::greaterequal};
+      static tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
       // FIXME: We probably need to change token type to mimic operator with the
       // correct priority.
       if (tryMergeTokens(JSIdentity))
@@ -1406,6 +660,32 @@
     }
   }
 
+  bool tryMergeLessLess() {
+    // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
+    if (Tokens.size() < 3)
+      return false;
+
+    bool FourthTokenIsLess = false;
+    if (Tokens.size() > 3)
+      FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
+
+    auto First = Tokens.end() - 3;
+    if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
+        First[0]->isNot(tok::less) || FourthTokenIsLess)
+      return false;
+
+    // Only merge if there currently is no whitespace between the two "<".
+    if (First[1]->WhitespaceRange.getBegin() !=
+        First[1]->WhitespaceRange.getEnd())
+      return false;
+
+    First[0]->Tok.setKind(tok::lessless);
+    First[0]->TokenText = "<<";
+    First[0]->ColumnWidth += 1;
+    Tokens.erase(Tokens.end() - 2);
+    return true;
+  }
+
   bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
     if (Tokens.size() < Kinds.size())
       return false;
@@ -1416,8 +696,9 @@
       return false;
     unsigned AddLength = 0;
     for (unsigned i = 1; i < Kinds.size(); ++i) {
-      if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
-                                         First[i]->WhitespaceRange.getEnd())
+      if (!First[i]->is(Kinds[i]) ||
+          First[i]->WhitespaceRange.getBegin() !=
+              First[i]->WhitespaceRange.getEnd())
         return false;
       AddLength += First[i]->TokenText.size();
     }
@@ -1493,6 +774,66 @@
     return false;
   }
 
+  bool tryMergeTemplateString() {
+    if (Tokens.size() < 2)
+      return false;
+
+    FormatToken *EndBacktick = Tokens.back();
+    if (!(EndBacktick->is(tok::unknown) && EndBacktick->TokenText == "`"))
+      return false;
+
+    unsigned TokenCount = 0;
+    bool IsMultiline = false;
+    unsigned EndColumnInFirstLine = 0;
+    for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; I++) {
+      ++TokenCount;
+      if (I[0]->NewlinesBefore > 0 || I[0]->IsMultiline)
+        IsMultiline = true;
+
+      // If there was a preceding template string, this must be the start of a
+      // template string, not the end.
+      if (I[0]->is(TT_TemplateString))
+        return false;
+
+      if (I[0]->isNot(tok::unknown) || I[0]->TokenText != "`") {
+        // Keep track of the rhs offset of the last token to wrap across lines -
+        // its the rhs offset of the first line of the template string, used to
+        // determine its width.
+        if (I[0]->IsMultiline)
+          EndColumnInFirstLine = I[0]->OriginalColumn + I[0]->ColumnWidth;
+        // If the token has newlines, the token before it (if it exists) is the
+        // rhs end of the previous line.
+        if (I[0]->NewlinesBefore > 0 && (I + 1 != E))
+          EndColumnInFirstLine = I[1]->OriginalColumn + I[1]->ColumnWidth;
+
+        continue;
+      }
+
+      Tokens.resize(Tokens.size() - TokenCount);
+      Tokens.back()->Type = TT_TemplateString;
+      const char *EndOffset = EndBacktick->TokenText.data() + 1;
+      Tokens.back()->TokenText =
+          StringRef(Tokens.back()->TokenText.data(),
+                    EndOffset - Tokens.back()->TokenText.data());
+      if (IsMultiline) {
+        // ColumnWidth is from backtick to last token in line.
+        // LastLineColumnWidth is 0 to backtick.
+        // x = `some content
+        //     until here`;
+        Tokens.back()->ColumnWidth =
+            EndColumnInFirstLine - Tokens.back()->OriginalColumn;
+        Tokens.back()->LastLineColumnWidth = EndBacktick->OriginalColumn;
+        Tokens.back()->IsMultiline = true;
+      } else {
+        // Token simply spans from start to end, +1 for the ` itself.
+        Tokens.back()->ColumnWidth =
+            EndBacktick->OriginalColumn - Tokens.back()->OriginalColumn + 1;
+      }
+      return true;
+    }
+    return false;
+  }
+
   bool tryMerge_TMacro() {
     if (Tokens.size() < 4)
       return false;
@@ -1590,21 +931,33 @@
     return false;
   }
 
+  FormatToken *getStashedToken() {
+    // Create a synthesized second '>' or '<' token.
+    Token Tok = FormatTok->Tok;
+    StringRef TokenText = FormatTok->TokenText;
+
+    unsigned OriginalColumn = FormatTok->OriginalColumn;
+    FormatTok = new (Allocator.Allocate()) FormatToken;
+    FormatTok->Tok = Tok;
+    SourceLocation TokLocation =
+        FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
+    FormatTok->Tok.setLocation(TokLocation);
+    FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
+    FormatTok->TokenText = TokenText;
+    FormatTok->ColumnWidth = 1;
+    FormatTok->OriginalColumn = OriginalColumn + 1;
+
+    return FormatTok;
+  }
+
   FormatToken *getNextToken() {
     if (GreaterStashed) {
-      // Create a synthesized second '>' token.
-      // FIXME: Increment Column and set OriginalColumn.
-      Token Greater = FormatTok->Tok;
-      FormatTok = new (Allocator.Allocate()) FormatToken;
-      FormatTok->Tok = Greater;
-      SourceLocation GreaterLocation =
-          FormatTok->Tok.getLocation().getLocWithOffset(1);
-      FormatTok->WhitespaceRange =
-          SourceRange(GreaterLocation, GreaterLocation);
-      FormatTok->TokenText = ">";
-      FormatTok->ColumnWidth = 1;
       GreaterStashed = false;
-      return FormatTok;
+      return getStashedToken();
+    }
+    if (LessStashed) {
+      LessStashed = false;
+      return getStashedToken();
     }
 
     FormatTok = new (Allocator.Allocate()) FormatToken;
@@ -1617,6 +970,8 @@
     // Consume and record whitespace until we find a significant token.
     unsigned WhitespaceLength = TrailingWhitespace;
     while (FormatTok->Tok.is(tok::unknown)) {
+      // FIXME: This miscounts tok:unknown tokens that are not just
+      // whitespace, e.g. a '`' character.
       for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
         switch (FormatTok->TokenText[i]) {
         case '\n':
@@ -1631,6 +986,9 @@
           Column = 0;
           break;
         case '\r':
+          FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
+          Column = 0;
+          break;
         case '\f':
         case '\v':
           Column = 0;
@@ -1642,7 +1000,6 @@
           Column += Style.TabWidth - Column % Style.TabWidth;
           break;
         case '\\':
-          ++Column;
           if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
                              FormatTok->TokenText[i + 1] != '\n'))
             FormatTok->Type = TT_ImplicitStringLiteral;
@@ -1654,7 +1011,7 @@
         }
       }
 
-      if (FormatTok->Type == TT_ImplicitStringLiteral)
+      if (FormatTok->is(TT_ImplicitStringLiteral))
         break;
       WhitespaceLength += FormatTok->Tok.getLength();
 
@@ -1697,6 +1054,10 @@
       FormatTok->Tok.setKind(tok::greater);
       FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
       GreaterStashed = true;
+    } else if (FormatTok->Tok.is(tok::lessless)) {
+      FormatTok->Tok.setKind(tok::less);
+      FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
+      LessStashed = true;
     }
 
     // Now FormatTok is the next non-whitespace token.
@@ -1733,7 +1094,7 @@
 
   FormatToken *FormatTok;
   bool IsFirstToken;
-  bool GreaterStashed;
+  bool GreaterStashed, LessStashed;
   unsigned Column;
   unsigned TrailingWhitespace;
   std::unique_ptr<Lexer> Lex;
@@ -1871,7 +1232,8 @@
     ContinuationIndenter Indenter(Style, Tokens.getKeywords(), SourceMgr,
                                   Whitespaces, Encoding,
                                   BinPackInconclusiveFunctions);
-    UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
+    UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style,
+                                     Tokens.getKeywords());
     Formatter.format(AnnotatedLines, /*DryRun=*/false);
     return Whitespaces.generateReplacements();
   }
@@ -2026,7 +1388,7 @@
         continue;
       FormatToken *Tok = AnnotatedLines[i]->First->Next;
       while (Tok->Next) {
-        if (Tok->Type == TT_PointerOrReference) {
+        if (Tok->is(TT_PointerOrReference)) {
           bool SpacesBefore =
               Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
           bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
@@ -2038,11 +1400,10 @@
         }
 
         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
-          if (Tok->is(tok::coloncolon) &&
-              Tok->Previous->Type == TT_TemplateOpener)
+          if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
             HasCpp03IncompatibleFormat = true;
-          if (Tok->Type == TT_TemplateCloser &&
-              Tok->Previous->Type == TT_TemplateCloser)
+          if (Tok->is(TT_TemplateCloser) &&
+              Tok->Previous->is(TT_TemplateCloser))
             HasCpp03IncompatibleFormat = true;
         }
 
@@ -2148,6 +1509,7 @@
   LangOpts.Bool = 1;
   LangOpts.ObjC1 = 1;
   LangOpts.ObjC2 = 1;
+  LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
   return LangOpts;
 }
 
diff --git a/lib/Format/FormatToken.cpp b/lib/Format/FormatToken.cpp
index 677f1a0..0addbfe 100644
--- a/lib/Format/FormatToken.cpp
+++ b/lib/Format/FormatToken.cpp
@@ -59,7 +59,8 @@
 unsigned CommaSeparatedList::formatAfterToken(LineState &State,
                                               ContinuationIndenter *Indenter,
                                               bool DryRun) {
-  if (!State.NextToken->Previous || !State.NextToken->Previous->Previous)
+  if (State.NextToken == nullptr || !State.NextToken->Previous ||
+      !State.NextToken->Previous->Previous)
     return 0;
 
   // Ensure that we start on the opening brace.
@@ -138,6 +139,10 @@
       Commas.size() < 19)
     return;
 
+  // Column format doesn't really make sense if we don't align after brackets.
+  if (!Style.AlignAfterOpenBracket)
+    return;
+
   FormatToken *ItemBegin = Token->Next;
   SmallVector<bool, 8> MustBreakBeforeItem;
 
diff --git a/lib/Format/FormatToken.h b/lib/Format/FormatToken.h
index 0ef563b..14f45a4 100644
--- a/lib/Format/FormatToken.h
+++ b/lib/Format/FormatToken.h
@@ -48,6 +48,8 @@
   TT_InheritanceColon,
   TT_InlineASMColon,
   TT_JavaAnnotation,
+  TT_JsTypeColon,
+  TT_LambdaArrow,
   TT_LambdaLSquare,
   TT_LeadingJavaAnnotation,
   TT_LineComment,
@@ -68,6 +70,7 @@
   TT_StartOfName,
   TT_TemplateCloser,
   TT_TemplateOpener,
+  TT_TemplateString,
   TT_TrailingAnnotation,
   TT_TrailingReturnArrow,
   TT_TrailingUnaryOperator,
@@ -270,36 +273,18 @@
   bool IsForEachMacro;
 
   bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
-
+  bool is(TokenType TT) const { return Type == TT; }
   bool is(const IdentifierInfo *II) const {
     return II && II == Tok.getIdentifierInfo();
   }
-
-  template <typename T>
-  bool isOneOf(T K1, T K2) const {
+  template <typename A, typename B> bool isOneOf(A K1, B K2) const {
     return is(K1) || is(K2);
   }
-
-  template <typename T>
-  bool isOneOf(T K1, T K2, T K3) const {
-    return is(K1) || is(K2) || is(K3);
+  template <typename A, typename B, typename... Ts>
+  bool isOneOf(A K1, B K2, Ts... Ks) const {
+    return is(K1) || isOneOf(K2, Ks...);
   }
-
-  template <typename T>
-  bool isOneOf(T K1, T K2, T K3, T K4, T K5 = tok::NUM_TOKENS,
-               T K6 = tok::NUM_TOKENS, T K7 = tok::NUM_TOKENS,
-               T K8 = tok::NUM_TOKENS, T K9 = tok::NUM_TOKENS,
-               T K10 = tok::NUM_TOKENS, T K11 = tok::NUM_TOKENS,
-               T K12 = tok::NUM_TOKENS) const {
-    return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
-           is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
-  }
-
-  template <typename T>
-  bool isNot(T Kind) const {
-    return Tok.isNot(Kind);
-  }
-  bool isNot(IdentifierInfo *II) const { return II != Tok.getIdentifierInfo(); }
+  template <typename T> bool isNot(T Kind) const { return !is(Kind); }
 
   bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
 
@@ -324,20 +309,19 @@
 
   /// \brief Returns whether \p Tok is ([{ or a template opening <.
   bool opensScope() const {
-    return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
-           Type == TT_TemplateOpener;
+    return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
+                   TT_TemplateOpener);
   }
   /// \brief Returns whether \p Tok is )]} or a template closing >.
   bool closesScope() const {
-    return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
-           Type == TT_TemplateCloser;
+    return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
+                   TT_TemplateCloser);
   }
 
   /// \brief Returns \c true if this is a "." or "->" accessing a member.
   bool isMemberAccess() const {
     return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
-           Type != TT_DesignatedInitializerPeriod &&
-           Type != TT_TrailingReturnArrow;
+           !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow);
   }
 
   bool isUnaryOperator() const {
@@ -363,7 +347,7 @@
 
   bool isTrailingComment() const {
     return is(tok::comment) &&
-           (Type == TT_LineComment || !Next || Next->NewlinesBefore > 0);
+           (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
   }
 
   /// \brief Returns \c true if this is a keyword that can be used
@@ -409,10 +393,10 @@
   /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
   /// list that should be indented with a block indent.
   bool opensBlockTypeList(const FormatStyle &Style) const {
-    return Type == TT_ArrayInitializerLSquare ||
+    return is(TT_ArrayInitializerLSquare) ||
            (is(tok::l_brace) &&
-            (BlockKind == BK_Block || Type == TT_DictLiteral ||
-             !Style.Cpp11BracedListStyle));
+            (BlockKind == BK_Block || is(TT_DictLiteral) ||
+             (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
   }
 
   /// \brief Same as opensBlockTypeList, but for the closing token.
@@ -437,8 +421,8 @@
 
 private:
   // Disallow copying.
-  FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
-  void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
+  FormatToken(const FormatToken &) = delete;
+  void operator=(const FormatToken &) = delete;
 };
 
 class ContinuationIndenter;
@@ -537,17 +521,27 @@
 struct AdditionalKeywords {
   AdditionalKeywords(IdentifierTable &IdentTable) {
     kw_in = &IdentTable.get("in");
+    kw_CF_ENUM = &IdentTable.get("CF_ENUM");
+    kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
     kw_NS_ENUM = &IdentTable.get("NS_ENUM");
+    kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
 
     kw_finally = &IdentTable.get("finally");
     kw_function = &IdentTable.get("function");
+    kw_import = &IdentTable.get("import");
     kw_var = &IdentTable.get("var");
 
+    kw_abstract = &IdentTable.get("abstract");
     kw_extends = &IdentTable.get("extends");
+    kw_final = &IdentTable.get("final");
     kw_implements = &IdentTable.get("implements");
+    kw_instanceof = &IdentTable.get("instanceof");
     kw_interface = &IdentTable.get("interface");
+    kw_native = &IdentTable.get("native");
+    kw_package = &IdentTable.get("package");
     kw_synchronized = &IdentTable.get("synchronized");
     kw_throws = &IdentTable.get("throws");
+    kw___except = &IdentTable.get("__except");
 
     kw_option = &IdentTable.get("option");
     kw_optional = &IdentTable.get("optional");
@@ -556,19 +550,29 @@
     kw_returns = &IdentTable.get("returns");
   }
 
-  // ObjC context sensitive keywords.
+  // Context sensitive keywords.
   IdentifierInfo *kw_in;
+  IdentifierInfo *kw_CF_ENUM;
+  IdentifierInfo *kw_CF_OPTIONS;
   IdentifierInfo *kw_NS_ENUM;
+  IdentifierInfo *kw_NS_OPTIONS;
+  IdentifierInfo *kw___except;
 
   // JavaScript keywords.
   IdentifierInfo *kw_finally;
   IdentifierInfo *kw_function;
+  IdentifierInfo *kw_import;
   IdentifierInfo *kw_var;
 
   // Java keywords.
+  IdentifierInfo *kw_abstract;
   IdentifierInfo *kw_extends;
+  IdentifierInfo *kw_final;
   IdentifierInfo *kw_implements;
+  IdentifierInfo *kw_instanceof;
   IdentifierInfo *kw_interface;
+  IdentifierInfo *kw_native;
+  IdentifierInfo *kw_package;
   IdentifierInfo *kw_synchronized;
   IdentifierInfo *kw_throws;
 
diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp
index 1afdb19..fa086a9 100644
--- a/lib/Format/TokenAnnotator.cpp
+++ b/lib/Format/TokenAnnotator.cpp
@@ -33,8 +33,8 @@
 public:
   AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
                    const AdditionalKeywords &Keywords)
-      : Style(Style), Line(Line), CurrentToken(Line.First),
-        KeywordVirtualFound(false), AutoFound(false), Keywords(Keywords) {
+      : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
+        Keywords(Keywords) {
     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
     resetTokenMetadata(CurrentToken);
   }
@@ -78,7 +78,7 @@
       // parameters.
       // FIXME: This is getting out of hand, write a decent parser.
       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
-          CurrentToken->Previous->Type == TT_BinaryOperator &&
+          CurrentToken->Previous->is(TT_BinaryOperator) &&
           Contexts[Contexts.size() - 2].IsExpression &&
           Line.First->isNot(tok::kw_template))
         return false;
@@ -114,17 +114,17 @@
     if (Left->Previous &&
         (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
                                  tok::kw_while, tok::l_paren, tok::comma) ||
-         Left->Previous->Type == TT_BinaryOperator)) {
+         Left->Previous->is(TT_BinaryOperator))) {
       // static_assert, if and while usually contain expressions.
       Contexts.back().IsExpression = true;
     } else if (Line.InPPDirective &&
                (!Left->Previous ||
-                (Left->Previous->isNot(tok::identifier) &&
-                 Left->Previous->Type != TT_OverloadedOperator))) {
+                !Left->Previous->isOneOf(tok::identifier,
+                                         TT_OverloadedOperator))) {
       Contexts.back().IsExpression = true;
     } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
                Left->Previous->MatchingParen &&
-               Left->Previous->MatchingParen->Type == TT_LambdaLSquare) {
+               Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
       // This is a parameter list of a lambda expression.
       Contexts.back().IsExpression = false;
     } else if (Contexts[Contexts.size() - 2].CaretFound) {
@@ -137,7 +137,7 @@
       Contexts.back().IsForEachMacro = true;
       Contexts.back().IsExpression = false;
     } else if (Left->Previous && Left->Previous->MatchingParen &&
-               Left->Previous->MatchingParen->Type == TT_ObjCBlockLParen) {
+               Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
       Contexts.back().IsExpression = false;
     }
 
@@ -168,11 +168,11 @@
         }
       }
 
-      if (CurrentToken->Previous->Type == TT_PointerOrReference &&
+      if (CurrentToken->Previous->is(TT_PointerOrReference) &&
           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
                                                     tok::coloncolon))
         MightBeFunctionType = true;
-      if (CurrentToken->Previous->Type == TT_BinaryOperator)
+      if (CurrentToken->Previous->is(TT_BinaryOperator))
         Contexts.back().IsExpression = true;
       if (CurrentToken->is(tok::r_paren)) {
         if (MightBeFunctionType && CurrentToken->Next &&
@@ -191,11 +191,11 @@
           }
         }
 
-        if (Left->Type == TT_AttributeParen)
+        if (Left->is(TT_AttributeParen))
           CurrentToken->Type = TT_AttributeParen;
-        if (Left->Previous && Left->Previous->Type == TT_JavaAnnotation)
+        if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
           CurrentToken->Type = TT_JavaAnnotation;
-        if (Left->Previous && Left->Previous->Type == TT_LeadingJavaAnnotation)
+        if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
           CurrentToken->Type = TT_LeadingJavaAnnotation;
 
         if (!HasMultipleLines)
@@ -239,12 +239,13 @@
     FormatToken *Left = CurrentToken->Previous;
     FormatToken *Parent = Left->getPreviousNonComment();
     bool StartsObjCMethodExpr =
-        Contexts.back().CanBeExpression && Left->Type != TT_LambdaLSquare &&
+        Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
         CurrentToken->isNot(tok::l_brace) &&
-        (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
-                                    tok::kw_return, tok::kw_throw) ||
-         Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
-         Parent->Type == TT_CastRParen ||
+        (!Parent ||
+         Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
+                         tok::kw_return, tok::kw_throw) ||
+         Parent->isUnaryOperator() ||
+         Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
          getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
     ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
     Contexts.back().IsExpression = true;
@@ -255,14 +256,14 @@
       Left->Type = TT_ObjCMethodExpr;
     } else if (Parent && Parent->is(tok::at)) {
       Left->Type = TT_ArrayInitializerLSquare;
-    } else if (Left->Type == TT_Unknown) {
+    } else if (Left->is(TT_Unknown)) {
       Left->Type = TT_ArraySubscriptLSquare;
     }
 
     while (CurrentToken) {
       if (CurrentToken->is(tok::r_square)) {
         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
-            Left->Type == TT_ObjCMethodExpr) {
+            Left->is(TT_ObjCMethodExpr)) {
           // An ObjC method call is rarely followed by an open parenthesis.
           // FIXME: Do we incorrectly label ":" with this?
           StartsObjCMethodExpr = false;
@@ -273,7 +274,7 @@
           // determineStarAmpUsage() thinks that '*' '[' is allocating an
           // array of pointers, but if '[' starts a selector then '*' is a
           // binary operator.
-          if (Parent && Parent->Type == TT_PointerOrReference)
+          if (Parent && Parent->is(TT_PointerOrReference))
             Parent->Type = TT_BinaryOperator;
         }
         Left->MatchingParen = CurrentToken;
@@ -290,7 +291,7 @@
       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
         return false;
       if (CurrentToken->is(tok::colon)) {
-        if (Left->Type == TT_ArraySubscriptLSquare) {
+        if (Left->is(TT_ArraySubscriptLSquare)) {
           Left->Type = TT_ObjCMethodExpr;
           StartsObjCMethodExpr = true;
           Contexts.back().ColonIsObjCMethodExpr = true;
@@ -301,10 +302,10 @@
       }
       if (CurrentToken->is(tok::comma) &&
           Style.Language != FormatStyle::LK_Proto &&
-          (Left->Type == TT_ArraySubscriptLSquare ||
-           (Left->Type == TT_ObjCMethodExpr && !ColonFound)))
+          (Left->is(TT_ArraySubscriptLSquare) ||
+           (Left->is(TT_ObjCMethodExpr) && !ColonFound)))
         Left->Type = TT_ArrayInitializerLSquare;
-      FormatToken* Tok = CurrentToken;
+      FormatToken *Tok = CurrentToken;
       if (!consumeToken())
         return false;
       updateParameterCount(Left, Tok);
@@ -352,8 +353,8 @@
   }
 
   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
-    if (Current->Type == TT_LambdaLSquare ||
-        (Current->is(tok::caret) && Current->Type == TT_UnaryOperator) ||
+    if (Current->is(TT_LambdaLSquare) ||
+        (Current->is(tok::caret) && Current->is(TT_UnaryOperator)) ||
         (Style.Language == FormatStyle::LK_JavaScript &&
          Current->is(Keywords.kw_function))) {
       ++Left->BlockParameterCount;
@@ -407,13 +408,10 @@
       if (!Tok->Previous)
         return false;
       // Colons from ?: are handled in parseConditional().
-      if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1 &&
-          Line.First->isNot(tok::kw_case)) {
-        Tok->Type = TT_CtorInitializerColon;
-      } else if (Contexts.back().ColonIsDictLiteral) {
+      if (Contexts.back().ColonIsDictLiteral) {
         Tok->Type = TT_DictLiteral;
       } else if (Contexts.back().ColonIsObjCMethodExpr ||
-                 Line.First->Type == TT_ObjCMethodSpecifier) {
+                 Line.First->is(TT_ObjCMethodSpecifier)) {
         Tok->Type = TT_ObjCMethodExpr;
         Tok->Previous->Type = TT_SelectorName;
         if (Tok->Previous->ColumnWidth >
@@ -423,19 +421,28 @@
         if (!Contexts.back().FirstObjCSelectorName)
           Contexts.back().FirstObjCSelectorName = Tok->Previous;
       } else if (Contexts.back().ColonIsForRangeExpr) {
-        Tok->Type = TT_RangeBasedForLoopColon;
+        Tok->Type = Style.Language == FormatStyle::LK_JavaScript
+                        ? TT_JsTypeColon
+                        : TT_RangeBasedForLoopColon;
       } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
         Tok->Type = TT_BitFieldColon;
       } else if (Contexts.size() == 1 &&
                  !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
-        Tok->Type = TT_InheritanceColon;
+        if (Style.Language == FormatStyle::LK_JavaScript)
+          Tok->Type = TT_JsTypeColon;
+        else if (Tok->Previous->is(tok::r_paren))
+          Tok->Type = TT_CtorInitializerColon;
+        else
+          Tok->Type = TT_InheritanceColon;
       } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
                  Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
         // This handles a special macro in ObjC code where selectors including
         // the colon are passed as macro arguments.
         Tok->Type = TT_ObjCMethodExpr;
       } else if (Contexts.back().ContextKind == tok::l_paren) {
-        Tok->Type = TT_InlineASMColon;
+        Tok->Type = Style.Language == FormatStyle::LK_JavaScript
+                        ? TT_JsTypeColon
+                        : TT_InlineASMColon;
       }
       break;
     case tok::kw_if:
@@ -456,9 +463,9 @@
       if (!parseParens())
         return false;
       if (Line.MustBeDeclaration && Contexts.size() == 1 &&
-          !Contexts.back().IsExpression &&
-          Line.First->Type != TT_ObjCProperty &&
-          (!Tok->Previous || Tok->Previous->isNot(tok::kw_decltype)))
+          !Contexts.back().IsExpression && Line.First->isNot(TT_ObjCProperty) &&
+          (!Tok->Previous ||
+           !Tok->Previous->isOneOf(tok::kw_decltype, TT_LeadingJavaAnnotation)))
         Line.MightBeFunctionDecl = true;
       break;
     case tok::l_square:
@@ -470,9 +477,12 @@
         return false;
       break;
     case tok::less:
-      if ((!Tok->Previous || !Tok->Previous->Tok.isLiteral()) && parseAngle())
+      if ((!Tok->Previous ||
+           (!Tok->Previous->Tok.isLiteral() &&
+            !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
+          parseAngle()) {
         Tok->Type = TT_TemplateOpener;
-      else {
+      } else {
         Tok->Type = TT_BinaryOperator;
         CurrentToken = Tok;
         next();
@@ -495,12 +505,12 @@
         if (CurrentToken->isOneOf(tok::star, tok::amp))
           CurrentToken->Type = TT_PointerOrReference;
         consumeToken();
-        if (CurrentToken && CurrentToken->Previous->Type == TT_BinaryOperator)
+        if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
           CurrentToken->Previous->Type = TT_OverloadedOperator;
       }
       if (CurrentToken) {
         CurrentToken->Type = TT_OverloadedOperatorLParen;
-        if (CurrentToken->Previous->Type == TT_BinaryOperator)
+        if (CurrentToken->Previous->is(TT_BinaryOperator))
           CurrentToken->Previous->Type = TT_OverloadedOperator;
       }
       break;
@@ -511,7 +521,8 @@
       parseTemplateDeclaration();
       break;
     case tok::identifier:
-      if (Line.First->is(tok::kw_for) && Tok->is(Keywords.kw_in))
+      if (Line.First->is(tok::kw_for) && Tok->is(Keywords.kw_in) &&
+          Tok->Previous->isNot(tok::colon))
         Tok->Type = TT_ObjCForIn;
       break;
     case tok::comma:
@@ -536,14 +547,6 @@
           CurrentToken->Type = TT_ImplicitStringLiteral;
         next();
       }
-    } else {
-      while (CurrentToken) {
-        if (CurrentToken->isNot(tok::comment))
-          // Mark these tokens as "implicit" string literals, so that
-          // they are not split or line-wrapped.
-          CurrentToken->Type = TT_ImplicitStringLiteral;
-        next();
-      }
     }
   }
 
@@ -570,23 +573,25 @@
     }
   }
 
-  void parsePreprocessorDirective() {
+  LineType parsePreprocessorDirective() {
+    LineType Type = LT_PreprocessorDirective;
     next();
     if (!CurrentToken)
-      return;
+      return Type;
     if (CurrentToken->Tok.is(tok::numeric_constant)) {
       CurrentToken->SpacesRequiredBefore = 1;
-      return;
+      return Type;
     }
     // Hashes in the middle of a line can lead to any strange token
     // sequence.
     if (!CurrentToken->Tok.getIdentifierInfo())
-      return;
+      return Type;
     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
     case tok::pp_include:
     case tok::pp_import:
       next();
       parseIncludeDirective();
+      Type = LT_ImportStatement;
       break;
     case tok::pp_error:
     case tok::pp_warning:
@@ -605,43 +610,53 @@
     }
     while (CurrentToken)
       next();
+    return Type;
   }
 
 public:
   LineType parseLine() {
     if (CurrentToken->is(tok::hash)) {
-      parsePreprocessorDirective();
-      return LT_PreprocessorDirective;
+      return parsePreprocessorDirective();
     }
 
     // Directly allow to 'import <string-literal>' to support protocol buffer
     // definitions (code.google.com/p/protobuf) or missing "#" (either way we
     // should not break the line).
     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
-    if (Info && Info->getPPKeywordID() == tok::pp_import &&
-        CurrentToken->Next) {
+    if ((Style.Language == FormatStyle::LK_Java &&
+         CurrentToken->is(Keywords.kw_package)) ||
+        (Info && Info->getPPKeywordID() == tok::pp_import &&
+         CurrentToken->Next &&
+         CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
+                                     tok::kw_static))) {
       next();
       parseIncludeDirective();
-      return LT_Other;
+      return LT_ImportStatement;
     }
 
     // If this line starts and ends in '<' and '>', respectively, it is likely
     // part of "#define <a/b.h>".
     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
       parseIncludeDirective();
-      return LT_Other;
+      return LT_ImportStatement;
     }
 
+    bool KeywordVirtualFound = false;
+    bool ImportStatement = false;
     while (CurrentToken) {
       if (CurrentToken->is(tok::kw_virtual))
         KeywordVirtualFound = true;
+      if (IsImportStatement(*CurrentToken))
+        ImportStatement = true;
       if (!consumeToken())
         return LT_Invalid;
     }
     if (KeywordVirtualFound)
       return LT_VirtualFunctionDecl;
+    if (ImportStatement)
+      return LT_ImportStatement;
 
-    if (Line.First->Type == TT_ObjCMethodSpecifier) {
+    if (Line.First->is(TT_ObjCMethodSpecifier)) {
       if (Contexts.back().FirstObjCSelectorName)
         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
             Contexts.back().LongestObjCSelectorName;
@@ -652,19 +667,29 @@
   }
 
 private:
+  bool IsImportStatement(const FormatToken &Tok) {
+    // FIXME: Closure-library specific stuff should not be hard-coded but be
+    // configurable.
+    return Style.Language == FormatStyle::LK_JavaScript &&
+           Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
+           Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
+                              Tok.Next->Next->TokenText == "require" ||
+                              Tok.Next->Next->TokenText == "provide") &&
+           Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
+  }
+
   void resetTokenMetadata(FormatToken *Token) {
     if (!Token)
       return;
 
     // Reset token type in case we have already looked at it and then
     // recovered from an error (e.g. failure to find the matching >).
-    if (CurrentToken->Type != TT_LambdaLSquare &&
-        CurrentToken->Type != TT_FunctionLBrace &&
-        CurrentToken->Type != TT_ImplicitStringLiteral &&
-        CurrentToken->Type != TT_RegexLiteral &&
-        CurrentToken->Type != TT_TrailingReturnArrow)
+    if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_FunctionLBrace,
+                               TT_ImplicitStringLiteral, TT_RegexLiteral,
+                               TT_TrailingReturnArrow))
       CurrentToken->Type = TT_Unknown;
     CurrentToken->Role.reset();
+    CurrentToken->MatchingParen = nullptr;
     CurrentToken->FakeLParens.clear();
     CurrentToken->FakeRParens = 0;
   }
@@ -673,6 +698,7 @@
     if (CurrentToken) {
       CurrentToken->NestingLevel = Contexts.size() - 1;
       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
+      modifyContext(*CurrentToken);
       determineTokenType(*CurrentToken);
       CurrentToken = CurrentToken->Next;
     }
@@ -725,28 +751,30 @@
     ~ScopedContextCreator() { P.Contexts.pop_back(); }
   };
 
-  void determineTokenType(FormatToken &Current) {
+  void modifyContext(const FormatToken &Current) {
     if (Current.getPrecedence() == prec::Assignment &&
         !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
       Contexts.back().IsExpression = true;
-      for (FormatToken *Previous = Current.Previous;
-           Previous && !Previous->isOneOf(tok::comma, tok::semi);
-           Previous = Previous->Previous) {
-        if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
-          Previous = Previous->MatchingParen;
-          if (!Previous)
-            break;
-        }
-        if ((Previous->Type == TT_BinaryOperator ||
-             Previous->Type == TT_UnaryOperator) &&
-            Previous->isOneOf(tok::star, tok::amp) && Previous->Previous &&
-            Previous->Previous->isNot(tok::equal)) {
-          Previous->Type = TT_PointerOrReference;
+      if (!Line.First->is(TT_UnaryOperator)) {
+        for (FormatToken *Previous = Current.Previous;
+             Previous && !Previous->isOneOf(tok::comma, tok::semi);
+             Previous = Previous->Previous) {
+          if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
+            Previous = Previous->MatchingParen;
+            if (!Previous)
+              break;
+          }
+          if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
+              Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
+              Previous->Previous && Previous->Previous->isNot(tok::equal))
+            Previous->Type = TT_PointerOrReference;
         }
       }
     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
       Contexts.back().IsExpression = true;
+    } else if (Current.is(TT_TrailingReturnArrow)) {
+      Contexts.back().IsExpression = false;
     } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
                !Line.InPPDirective &&
                (!Current.Previous ||
@@ -754,7 +782,7 @@
       bool ParametersOfFunctionType =
           Current.Previous && Current.Previous->is(tok::r_paren) &&
           Current.Previous->MatchingParen &&
-          Current.Previous->MatchingParen->Type == TT_FunctionTypeLParen;
+          Current.Previous->MatchingParen->is(TT_FunctionTypeLParen);
       bool IsForOrCatch = Current.Previous &&
                           Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
       Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
@@ -766,7 +794,7 @@
       if (Line.MustBeDeclaration)
         Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
     } else if (Current.Previous &&
-               Current.Previous->Type == TT_CtorInitializerColon) {
+               Current.Previous->is(TT_CtorInitializerColon)) {
       Contexts.back().IsExpression = true;
       Contexts.back().InCtorInitializer = true;
     } else if (Current.is(tok::kw_new)) {
@@ -775,81 +803,99 @@
       // This should be the condition or increment in a for-loop.
       Contexts.back().IsExpression = true;
     }
+  }
 
-    if (Current.Type == TT_Unknown) {
+  void determineTokenType(FormatToken &Current) {
+    if (!Current.is(TT_Unknown))
+      // The token type is already known.
+      return;
+
+    // Line.MightBeFunctionDecl can only be true after the parentheses of a
+    // function declaration have been found. In this case, 'Current' is a
+    // trailing token of this declaration and thus cannot be a name.
+    if (Current.is(Keywords.kw_instanceof)) {
+      Current.Type = TT_BinaryOperator;
+    } else if (isStartOfName(Current) &&
+               (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
+      Contexts.back().FirstStartOfName = &Current;
+      Current.Type = TT_StartOfName;
+    } else if (Current.is(tok::kw_auto)) {
+      AutoFound = true;
+    } else if (Current.is(tok::arrow) &&
+               Style.Language == FormatStyle::LK_Java) {
+      Current.Type = TT_LambdaArrow;
+    } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
+               Current.NestingLevel == 0) {
+      Current.Type = TT_TrailingReturnArrow;
+    } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
+      Current.Type =
+          determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
+                                             Contexts.back().IsExpression,
+                                Contexts.back().InTemplateArgument);
+    } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
+      Current.Type = determinePlusMinusCaretUsage(Current);
+      if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
+        Contexts.back().CaretFound = true;
+    } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
+      Current.Type = determineIncrementUsage(Current);
+    } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
+      Current.Type = TT_UnaryOperator;
+    } else if (Current.is(tok::question)) {
+      Current.Type = TT_ConditionalExpr;
+    } else if (Current.isBinaryOperator() &&
+               (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
+      Current.Type = TT_BinaryOperator;
+    } else if (Current.is(tok::comment)) {
+      Current.Type =
+          Current.TokenText.startswith("/*") ? TT_BlockComment : TT_LineComment;
+    } else if (Current.is(tok::r_paren)) {
+      if (rParenEndsCast(Current))
+        Current.Type = TT_CastRParen;
+    } else if (Current.is(tok::at) && Current.Next) {
+      switch (Current.Next->Tok.getObjCKeywordID()) {
+      case tok::objc_interface:
+      case tok::objc_implementation:
+      case tok::objc_protocol:
+        Current.Type = TT_ObjCDecl;
+        break;
+      case tok::objc_property:
+        Current.Type = TT_ObjCProperty;
+        break;
+      default:
+        break;
+      }
+    } else if (Current.is(tok::period)) {
+      FormatToken *PreviousNoComment = Current.getPreviousNonComment();
+      if (PreviousNoComment &&
+          PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
+        Current.Type = TT_DesignatedInitializerPeriod;
+      else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
+               Current.Previous->isOneOf(TT_JavaAnnotation,
+                                         TT_LeadingJavaAnnotation)) {
+        Current.Type = Current.Previous->Type;
+      }
+    } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
+               Current.Previous &&
+               !Current.Previous->isOneOf(tok::equal, tok::at) &&
+               Line.MightBeFunctionDecl && Contexts.size() == 1) {
       // Line.MightBeFunctionDecl can only be true after the parentheses of a
-      // function declaration have been found. In this case, 'Current' is a
-      // trailing token of this declaration and thus cannot be a name.
-      if (isStartOfName(Current) &&
-          (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
-        Contexts.back().FirstStartOfName = &Current;
-        Current.Type = TT_StartOfName;
-      } else if (Current.is(tok::kw_auto)) {
-        AutoFound = true;
-      } else if (Current.is(tok::arrow) && AutoFound &&
-                 Line.MustBeDeclaration && Current.NestingLevel == 0) {
-        Current.Type = TT_TrailingReturnArrow;
-      } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
-        Current.Type =
-            determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
-                                               Contexts.back().IsExpression,
-                                  Contexts.back().InTemplateArgument);
-      } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
-        Current.Type = determinePlusMinusCaretUsage(Current);
-        if (Current.Type == TT_UnaryOperator && Current.is(tok::caret))
-          Contexts.back().CaretFound = true;
-      } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
-        Current.Type = determineIncrementUsage(Current);
-      } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
-        Current.Type = TT_UnaryOperator;
-      } else if (Current.is(tok::question)) {
-        Current.Type = TT_ConditionalExpr;
-      } else if (Current.isBinaryOperator() &&
-                 (!Current.Previous ||
-                  Current.Previous->isNot(tok::l_square))) {
-        Current.Type = TT_BinaryOperator;
-      } else if (Current.is(tok::comment)) {
-        if (Current.TokenText.startswith("//"))
-          Current.Type = TT_LineComment;
-        else
-          Current.Type = TT_BlockComment;
-      } else if (Current.is(tok::r_paren)) {
-        if (rParenEndsCast(Current))
-          Current.Type = TT_CastRParen;
-      } else if (Current.is(tok::at) && Current.Next) {
-        switch (Current.Next->Tok.getObjCKeywordID()) {
-        case tok::objc_interface:
-        case tok::objc_implementation:
-        case tok::objc_protocol:
-          Current.Type = TT_ObjCDecl;
-          break;
-        case tok::objc_property:
-          Current.Type = TT_ObjCProperty;
-          break;
-        default:
-          break;
-        }
-      } else if (Current.is(tok::period)) {
-        FormatToken *PreviousNoComment = Current.getPreviousNonComment();
-        if (PreviousNoComment &&
-            PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
-          Current.Type = TT_DesignatedInitializerPeriod;
-      } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
-                 Current.Previous &&
-                 !Current.Previous->isOneOf(tok::equal, tok::at) &&
-                 Line.MightBeFunctionDecl && Contexts.size() == 1) {
-        // Line.MightBeFunctionDecl can only be true after the parentheses of a
-        // function declaration have been found.
-        Current.Type = TT_TrailingAnnotation;
-      } else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
-                 Current.Previous->is(tok::at) &&
-                 Current.isNot(Keywords.kw_interface)) {
-        const FormatToken& AtToken = *Current.Previous;
-        if (!AtToken.Previous ||
-            AtToken.Previous->Type == TT_LeadingJavaAnnotation)
+      // function declaration have been found.
+      Current.Type = TT_TrailingAnnotation;
+    } else if ((Style.Language == FormatStyle::LK_Java ||
+                Style.Language == FormatStyle::LK_JavaScript) &&
+               Current.Previous) {
+      if (Current.Previous->is(tok::at) &&
+          Current.isNot(Keywords.kw_interface)) {
+        const FormatToken &AtToken = *Current.Previous;
+        const FormatToken *Previous = AtToken.getPreviousNonComment();
+        if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
           Current.Type = TT_LeadingJavaAnnotation;
         else
           Current.Type = TT_JavaAnnotation;
+      } else if (Current.Previous->is(tok::period) &&
+                 Current.Previous->isOneOf(TT_JavaAnnotation,
+                                           TT_LeadingJavaAnnotation)) {
+        Current.Type = Current.Previous->Type;
       }
     }
   }
@@ -863,6 +909,9 @@
     if (Tok.isNot(tok::identifier) || !Tok.Previous)
       return false;
 
+    if (Tok.Previous->is(TT_LeadingJavaAnnotation))
+      return false;
+
     // Skip "const" as it does not have an influence on whether this is a name.
     FormatToken *PreviousNotConst = Tok.Previous;
     while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
@@ -875,7 +924,7 @@
                        PreviousNotConst->Previous &&
                        PreviousNotConst->Previous->is(tok::hash);
 
-    if (PreviousNotConst->Type == TT_TemplateCloser)
+    if (PreviousNotConst->is(TT_TemplateCloser))
       return PreviousNotConst && PreviousNotConst->MatchingParen &&
              PreviousNotConst->MatchingParen->Previous &&
              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
@@ -887,7 +936,7 @@
       return true;
 
     return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
-           PreviousNotConst->Type == TT_PointerOrReference ||
+           PreviousNotConst->is(TT_PointerOrReference) ||
            PreviousNotConst->isSimpleTypeSpecifier();
   }
 
@@ -901,24 +950,29 @@
       LeftOfParens = LeftOfParens->MatchingParen->Previous;
     if (LeftOfParens && LeftOfParens->is(tok::r_square) &&
         LeftOfParens->MatchingParen &&
-        LeftOfParens->MatchingParen->Type == TT_LambdaLSquare)
+        LeftOfParens->MatchingParen->is(TT_LambdaLSquare))
       return false;
+    if (Tok.Next) {
+      if (Tok.Next->is(tok::question))
+        return false;
+      if (Style.Language == FormatStyle::LK_JavaScript &&
+          Tok.Next->is(Keywords.kw_in))
+        return false;
+      if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
+        return true;
+    }
     bool IsCast = false;
     bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
-    bool ParensAreType = !Tok.Previous ||
-                         Tok.Previous->Type == TT_PointerOrReference ||
-                         Tok.Previous->Type == TT_TemplateCloser ||
-                         Tok.Previous->isSimpleTypeSpecifier();
-    if (Style.Language == FormatStyle::LK_JavaScript && Tok.Next &&
-        Tok.Next->is(Keywords.kw_in))
-      return false;
+    bool ParensAreType =
+        !Tok.Previous ||
+        Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
+        Tok.Previous->isSimpleTypeSpecifier();
     bool ParensCouldEndDecl =
         Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
     bool IsSizeOfOrAlignOf =
         LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
     if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
-        ((Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression) ||
-         (Tok.Next && Tok.Next->isBinaryOperator())))
+        (Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression))
       IsCast = true;
     else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
              (Tok.Next->Tok.isLiteral() ||
@@ -926,12 +980,11 @@
       IsCast = true;
     // If there is an identifier after the (), it is likely a cast, unless
     // there is also an identifier before the ().
-    else if (LeftOfParens &&
+    else if (LeftOfParens && Tok.Next &&
              (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
               LeftOfParens->is(tok::kw_return)) &&
-             LeftOfParens->Type != TT_OverloadedOperator &&
-             LeftOfParens->isNot(tok::at) &&
-             LeftOfParens->Type != TT_TemplateCloser && Tok.Next) {
+             !LeftOfParens->isOneOf(TT_OverloadedOperator, tok::at,
+                                    TT_TemplateCloser)) {
       if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
         IsCast = true;
       } else {
@@ -970,7 +1023,8 @@
       return TT_UnaryOperator;
 
     const FormatToken *NextToken = Tok.getNextNonComment();
-    if (!NextToken || NextToken->is(tok::l_brace))
+    if (!NextToken ||
+        (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
       return TT_Unknown;
 
     if (PrevToken->is(tok::coloncolon))
@@ -979,14 +1033,13 @@
     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
                            tok::comma, tok::semi, tok::kw_return, tok::colon,
                            tok::equal, tok::kw_delete, tok::kw_sizeof) ||
-        PrevToken->Type == TT_BinaryOperator ||
-        PrevToken->Type == TT_ConditionalExpr ||
-        PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
+        PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
+                           TT_UnaryOperator, TT_CastRParen))
       return TT_UnaryOperator;
 
-    if (NextToken->is(tok::l_square) && NextToken->Type != TT_LambdaLSquare)
+    if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
       return TT_PointerOrReference;
-    if (NextToken->isOneOf(tok::kw_operator, tok::comma))
+    if (NextToken->isOneOf(tok::kw_operator, tok::comma, tok::semi))
       return TT_PointerOrReference;
 
     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
@@ -1019,7 +1072,7 @@
 
     // It is very unlikely that we are going to find a pointer or reference type
     // definition on the RHS of an assignment.
-    if (IsExpression)
+    if (IsExpression && !Contexts.back().CaretFound)
       return TT_BinaryOperator;
 
     return TT_PointerOrReference;
@@ -1027,7 +1080,7 @@
 
   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
     const FormatToken *PrevToken = Tok.getPreviousNonComment();
-    if (!PrevToken || PrevToken->Type == TT_CastRParen)
+    if (!PrevToken || PrevToken->is(TT_CastRParen))
       return TT_UnaryOperator;
 
     // Use heuristics to recognize unary operators.
@@ -1037,7 +1090,7 @@
       return TT_UnaryOperator;
 
     // There can't be two consecutive binary operators.
-    if (PrevToken->Type == TT_BinaryOperator)
+    if (PrevToken->is(TT_BinaryOperator))
       return TT_UnaryOperator;
 
     // Fall back to marking the token as binary operator.
@@ -1047,7 +1100,7 @@
   /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
   TokenType determineIncrementUsage(const FormatToken &Tok) {
     const FormatToken *PrevToken = Tok.getPreviousNonComment();
-    if (!PrevToken || PrevToken->Type == TT_CastRParen)
+    if (!PrevToken || PrevToken->is(TT_CastRParen))
       return TT_UnaryOperator;
     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
       return TT_TrailingUnaryOperator;
@@ -1060,7 +1113,6 @@
   const FormatStyle &Style;
   AnnotatedLine &Line;
   FormatToken *CurrentToken;
-  bool KeywordVirtualFound;
   bool AutoFound;
   const AdditionalKeywords &Keywords;
 };
@@ -1080,10 +1132,9 @@
   void parse(int Precedence = 0) {
     // Skip 'return' and ObjC selector colons as they are not part of a binary
     // expression.
-    while (Current &&
-           (Current->is(tok::kw_return) ||
-            (Current->is(tok::colon) && (Current->Type == TT_ObjCMethodExpr ||
-                                         Current->Type == TT_DictLiteral))))
+    while (Current && (Current->is(tok::kw_return) ||
+                       (Current->is(tok::colon) &&
+                        Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
       next();
 
     if (!Current || Precedence > PrecedenceArrowAndPeriod)
@@ -1112,7 +1163,7 @@
 
       int CurrentPrecedence = getCurrentPrecedence();
 
-      if (Current && Current->Type == TT_SelectorName &&
+      if (Current && Current->is(TT_SelectorName) &&
           Precedence == CurrentPrecedence) {
         if (LatestOperator)
           addFakeParenthesis(Start, prec::Level(Precedence));
@@ -1125,16 +1176,7 @@
           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
           (CurrentPrecedence == prec::Conditional &&
            Precedence == prec::Assignment && Current->is(tok::colon))) {
-        if (LatestOperator) {
-          LatestOperator->LastOperator = true;
-          if (Precedence == PrecedenceArrowAndPeriod) {
-            // Call expressions don't have a binary operator precedence.
-            addFakeParenthesis(Start, prec::Unknown);
-          } else {
-            addFakeParenthesis(Start, prec::Level(Precedence));
-          }
-        }
-        return;
+        break;
       }
 
       // Consume scopes: (), [], <> and {}
@@ -1154,6 +1196,16 @@
         next(/*SkipPastLeadingComments=*/Precedence > 0);
       }
     }
+
+    if (LatestOperator && (Current || Precedence > 0)) {
+      LatestOperator->LastOperator = true;
+      if (Precedence == PrecedenceArrowAndPeriod) {
+        // Call expressions don't have a binary operator precedence.
+        addFakeParenthesis(Start, prec::Unknown);
+      } else {
+        addFakeParenthesis(Start, prec::Level(Precedence));
+      }
+    }
   }
 
 private:
@@ -1162,24 +1214,27 @@
   int getCurrentPrecedence() {
     if (Current) {
       const FormatToken *NextNonComment = Current->getNextNonComment();
-      if (Current->Type == TT_ConditionalExpr)
+      if (Current->is(TT_ConditionalExpr))
         return prec::Conditional;
       else if (NextNonComment && NextNonComment->is(tok::colon) &&
-               NextNonComment->Type == TT_DictLiteral)
+               NextNonComment->is(TT_DictLiteral))
         return prec::Comma;
-      else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
-               Current->Type == TT_SelectorName ||
+      else if (Current->is(TT_LambdaArrow))
+        return prec::Comma;
+      else if (Current->isOneOf(tok::semi, TT_InlineASMColon,
+                                TT_SelectorName) ||
                (Current->is(tok::comment) && NextNonComment &&
-                NextNonComment->Type == TT_SelectorName))
+                NextNonComment->is(TT_SelectorName)))
         return 0;
-      else if (Current->Type == TT_RangeBasedForLoopColon)
+      else if (Current->is(TT_RangeBasedForLoopColon))
         return prec::Comma;
-      else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
+      else if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
         return Current->getPrecedence();
       else if (Current->isOneOf(tok::period, tok::arrow))
         return PrecedenceArrowAndPeriod;
       else if (Style.Language == FormatStyle::LK_Java &&
-               Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements))
+               Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
+                                Keywords.kw_throws))
         return 0;
     }
     return -1;
@@ -1191,7 +1246,7 @@
       Start->StartsBinaryExpression = true;
     if (Current) {
       FormatToken *Previous = Current->Previous;
-      if (Previous->is(tok::comment) && Previous->Previous)
+      while (Previous->is(tok::comment) && Previous->Previous)
         Previous = Previous->Previous;
       ++Previous->FakeRParens;
       if (Precedence > prec::Unknown)
@@ -1202,7 +1257,7 @@
   /// \brief Parse unary operator expressions and surround them with fake
   /// parentheses if appropriate.
   void parseUnaryOperator() {
-    if (!Current || Current->Type != TT_UnaryOperator) {
+    if (!Current || Current->isNot(TT_UnaryOperator)) {
       parse(PrecedenceArrowAndPeriod);
       return;
     }
@@ -1225,7 +1280,7 @@
       return;
     next();
     parse(prec::Assignment);
-    if (!Current || Current->Type != TT_ConditionalExpr)
+    if (!Current || Current->isNot(TT_ConditionalExpr))
       return;
     next();
     parse(prec::Assignment);
@@ -1248,8 +1303,8 @@
 
 } // end anonymous namespace
 
-void
-TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
+void TokenAnnotator::setCommentLineLevels(
+    SmallVectorImpl<AnnotatedLine *> &Lines) {
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
                                                           E = Lines.rend();
@@ -1278,11 +1333,11 @@
   ExpressionParser ExprParser(Style, Keywords, Line);
   ExprParser.parse();
 
-  if (Line.First->Type == TT_ObjCMethodSpecifier)
+  if (Line.First->is(TT_ObjCMethodSpecifier))
     Line.Type = LT_ObjCMethodDecl;
-  else if (Line.First->Type == TT_ObjCDecl)
+  else if (Line.First->is(TT_ObjCDecl))
     Line.Type = LT_ObjCDecl;
-  else if (Line.First->Type == TT_ObjCProperty)
+  else if (Line.First->is(TT_ObjCProperty))
     Line.Type = LT_ObjCProperty;
 
   Line.First->SpacesRequiredBefore = 1;
@@ -1292,12 +1347,11 @@
 // This function heuristically determines whether 'Current' starts the name of a
 // function declaration.
 static bool isFunctionDeclarationName(const FormatToken &Current) {
-  if (Current.Type != TT_StartOfName ||
-      Current.NestingLevel != 0)
+  if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
     return false;
   const FormatToken *Next = Current.Next;
   for (; Next; Next = Next->Next) {
-    if (Next->Type == TT_TemplateOpener) {
+    if (Next->is(TT_TemplateOpener)) {
       Next = Next->MatchingParen;
     } else if (Next->is(tok::coloncolon)) {
       Next = Next->Next;
@@ -1314,10 +1368,10 @@
   assert(Next->is(tok::l_paren));
   if (Next->Next == Next->MatchingParen)
     return true;
-  for (const FormatToken *Tok = Next->Next; Tok != Next->MatchingParen;
+  for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
        Tok = Tok->Next) {
     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
-        Tok->Type == TT_PointerOrReference || Tok->Type == TT_StartOfName)
+        Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
       return true;
     if (Tok->isOneOf(tok::l_brace, tok::string_literal) || Tok->Tok.isLiteral())
       return false;
@@ -1341,7 +1395,7 @@
   while (Current) {
     if (isFunctionDeclarationName(*Current))
       Current->Type = TT_FunctionDeclarationName;
-    if (Current->Type == TT_LineComment) {
+    if (Current->is(TT_LineComment)) {
       if (Current->Previous->BlockKind == BK_BracedInit &&
           Current->Previous->opensScope())
         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
@@ -1361,7 +1415,7 @@
           if (Parameter->isOneOf(tok::comment, tok::r_brace))
             break;
           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
-            if (Parameter->Previous->Type != TT_CtorInitializerComma &&
+            if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
                 Parameter->HasUnescapedNewline)
               Parameter->MustBreakBefore = true;
             break;
@@ -1376,9 +1430,9 @@
     Current->MustBreakBefore =
         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
 
-    if (Style.AlwaysBreakAfterDefinitionReturnType &&
-        InFunctionDecl && Current->Type == TT_FunctionDeclarationName &&
-        !Line.Last->isOneOf(tok::semi, tok::comment))  // Only for definitions.
+    if (Style.AlwaysBreakAfterDefinitionReturnType && InFunctionDecl &&
+        Current->is(TT_FunctionDeclarationName) &&
+        !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
       // FIXME: Line.Last points to other characters than tok::semi
       // and tok::lbrace.
       Current->MustBreakBefore = true;
@@ -1391,7 +1445,7 @@
       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
                                                   : LastOfChild.TotalLength + 1;
     }
-    const FormatToken *Prev= Current->Previous;
+    const FormatToken *Prev = Current->Previous;
     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
         (Prev->Children.size() == 1 &&
          Prev->Children[0]->First->MustBreakBefore) ||
@@ -1401,7 +1455,7 @@
       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
                              ChildSize + Current->SpacesRequiredBefore;
 
-    if (Current->Type == TT_CtorInitializerColon)
+    if (Current->is(TT_CtorInitializerColon))
       InFunctionDecl = false;
 
     // FIXME: Only calculate this if CanBreakBefore is true once static
@@ -1448,31 +1502,32 @@
     return 0;
 
   if (Style.Language == FormatStyle::LK_Java) {
-    if (Left.Type == TT_LeadingJavaAnnotation)
-      return 1;
-    if (Right.is(Keywords.kw_extends))
+    if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
       return 1;
     if (Right.is(Keywords.kw_implements))
       return 2;
     if (Left.is(tok::comma) && Left.NestingLevel == 0)
       return 3;
+  } else if (Style.Language == FormatStyle::LK_JavaScript) {
+    if (Right.is(Keywords.kw_function))
+      return 100;
   }
 
   if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
-                              Right.Next->Type == TT_DictLiteral))
+                              Right.Next->is(TT_DictLiteral)))
     return 1;
   if (Right.is(tok::l_square)) {
     if (Style.Language == FormatStyle::LK_Proto)
       return 1;
-    if (Right.Type != TT_ObjCMethodExpr && Right.Type != TT_LambdaLSquare)
+    if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare))
       return 500;
   }
 
-  if (Right.Type == TT_StartOfName ||
-      Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator)) {
+  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
+      Right.is(tok::kw_operator)) {
     if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
       return 3;
-    if (Left.Type == TT_StartOfName)
+    if (Left.is(TT_StartOfName))
       return 20;
     if (InFunctionDecl && Right.NestingLevel == 0)
       return Style.PenaltyReturnTypeOnItsOwnLine;
@@ -1480,7 +1535,7 @@
   }
   if (Left.is(tok::equal) && Right.is(tok::l_brace))
     return 150;
-  if (Left.Type == TT_CastRParen)
+  if (Left.is(TT_CastRParen))
     return 100;
   if (Left.is(tok::coloncolon) ||
       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
@@ -1488,8 +1543,7 @@
   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
     return 5000;
 
-  if (Left.Type == TT_RangeBasedForLoopColon ||
-      Left.Type == TT_InheritanceColon)
+  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
     return 2;
 
   if (Right.isMemberAccess()) {
@@ -1499,11 +1553,11 @@
     return 150;
   }
 
-  if (Right.Type == TT_TrailingAnnotation &&
+  if (Right.is(TT_TrailingAnnotation) &&
       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
     // Moving trailing annotations to the next line is fine for ObjC method
     // declarations.
-    if (Line.First->Type == TT_ObjCMethodSpecifier)
+    if (Line.First->is(TT_ObjCMethodSpecifier))
 
       return 10;
     // Generally, breaking before a trailing annotation is bad unless it is
@@ -1521,18 +1575,20 @@
 
   // In Objective-C method expressions, prefer breaking before "param:" over
   // breaking after it.
-  if (Right.Type == TT_SelectorName)
+  if (Right.is(TT_SelectorName))
     return 0;
-  if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
+  if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
     return Line.MightBeFunctionDecl ? 50 : 500;
 
   if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
     return 100;
+  if (Left.is(tok::l_paren) && Left.Previous && Left.Previous->is(tok::kw_if))
+    return 1000;
   if (Left.is(tok::equal) && InFunctionDecl)
     return 110;
   if (Right.is(tok::r_brace))
     return 1;
-  if (Left.Type == TT_TemplateOpener)
+  if (Left.is(TT_TemplateOpener))
     return 100;
   if (Left.opensScope()) {
     if (!Style.AlignAfterOpenBracket)
@@ -1540,6 +1596,8 @@
     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
                                    : 19;
   }
+  if (Left.is(TT_JavaAnnotation))
+    return 50;
 
   if (Right.is(tok::lessless)) {
     if (Left.is(tok::string_literal)) {
@@ -1555,7 +1613,7 @@
     }
     return 1; // Breaking at a << is really cheap.
   }
-  if (Left.Type == TT_ConditionalExpr)
+  if (Left.is(TT_ConditionalExpr))
     return prec::Conditional;
   prec::Level Level = Left.getPrecedence();
 
@@ -1580,8 +1638,8 @@
   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
     return Style.SpaceInEmptyParentheses;
   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
-    return (Right.Type == TT_CastRParen ||
-            (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
+    return (Right.is(TT_CastRParen) ||
+            (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
                ? Style.SpacesInCStyleCastParentheses
                : Style.SpacesInParentheses;
   if (Right.isOneOf(tok::semi, tok::comma))
@@ -1605,56 +1663,60 @@
     return Left.Tok.isLiteral();
   if (Left.is(tok::l_square) && Right.is(tok::amp))
     return false;
-  if (Right.Type == TT_PointerOrReference)
-    return Left.Tok.isLiteral() ||
-           ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
-            Style.PointerAlignment != FormatStyle::PAS_Left);
-  if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
-      (Left.Type != TT_PointerOrReference ||
+  if (Right.is(TT_PointerOrReference))
+    return !(Left.is(tok::r_paren) && Left.MatchingParen &&
+             (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
+              (Left.MatchingParen->Previous &&
+               Left.MatchingParen->Previous->is(
+                   TT_FunctionDeclarationName)))) &&
+           (Left.Tok.isLiteral() ||
+            (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
+             Style.PointerAlignment != FormatStyle::PAS_Left));
+  if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
+      (!Left.is(TT_PointerOrReference) ||
        Style.PointerAlignment != FormatStyle::PAS_Right))
     return true;
-  if (Left.Type == TT_PointerOrReference)
-    return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
-           ((Right.Type != TT_PointerOrReference) &&
-            Right.isNot(tok::l_paren) &&
+  if (Left.is(TT_PointerOrReference))
+    return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
+           (!Right.isOneOf(TT_PointerOrReference, tok::l_paren) &&
             Style.PointerAlignment != FormatStyle::PAS_Right && Left.Previous &&
             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
   if (Right.is(tok::star) && Left.is(tok::l_paren))
     return false;
   if (Left.is(tok::l_square))
-    return (Left.Type == TT_ArrayInitializerLSquare &&
+    return (Left.is(TT_ArrayInitializerLSquare) &&
             Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
-           (Left.Type == TT_ArraySubscriptLSquare &&
-            Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
+           (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
+            Right.isNot(tok::r_square));
   if (Right.is(tok::r_square))
     return Right.MatchingParen &&
            ((Style.SpacesInContainerLiterals &&
-             Right.MatchingParen->Type == TT_ArrayInitializerLSquare) ||
+             Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
             (Style.SpacesInSquareBrackets &&
-             Right.MatchingParen->Type == TT_ArraySubscriptLSquare));
-  if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
-      Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant) &&
-      Left.Type != TT_DictLiteral)
+             Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
+  if (Right.is(tok::l_square) &&
+      !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
+      !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
     return false;
   if (Left.is(tok::colon))
-    return Left.Type != TT_ObjCMethodExpr;
+    return !Left.is(TT_ObjCMethodExpr);
   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
     return !Left.Children.empty(); // No spaces in "{}".
   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
       (Right.is(tok::r_brace) && Right.MatchingParen &&
        Right.MatchingParen->BlockKind != BK_Block))
     return !Style.Cpp11BracedListStyle;
-  if (Left.Type == TT_BlockComment)
+  if (Left.is(TT_BlockComment))
     return !Left.TokenText.endswith("=*/");
   if (Right.is(tok::l_paren)) {
-    if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
+    if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
       return true;
-    return Line.Type == LT_ObjCDecl ||
-           Left.isOneOf(tok::kw_new, tok::kw_delete, tok::semi) ||
+    return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
             (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
                           tok::kw_switch, tok::kw_case) ||
-             (Left.is(tok::kw_catch) &&
+             (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
+                           tok::kw_new, tok::kw_delete) &&
               (!Left.Previous || Left.Previous->isNot(tok::period))) ||
              Left.IsForEachMacro)) ||
            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
@@ -1663,9 +1725,9 @@
   }
   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
     return false;
-  if (Right.Type == TT_UnaryOperator)
+  if (Right.is(TT_UnaryOperator))
     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
-           (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
+           (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
                     tok::r_paren) ||
        Left.isSimpleTypeSpecifier()) &&
@@ -1676,12 +1738,12 @@
     return false;
   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
     return false;
-  if (Left.Type == TT_TemplateCloser && Left.MatchingParen &&
+  if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
       Left.MatchingParen->Previous &&
       Left.MatchingParen->Previous->is(tok::period))
     // A.<B>DoSomething();
     return false;
-  if (Left.Type == TT_TemplateCloser && Right.is(tok::l_square))
+  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
     return false;
   return true;
 }
@@ -1700,20 +1762,31 @@
   } else if (Style.Language == FormatStyle::LK_JavaScript) {
     if (Left.is(Keywords.kw_var))
       return true;
+    if (Right.is(TT_JsTypeColon))
+      return false;
+    if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
+        Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
+      return false;
   } else if (Style.Language == FormatStyle::LK_Java) {
+    if (Left.is(tok::r_square) && Right.is(tok::l_brace))
+      return true;
+    if (Left.is(TT_LambdaArrow) || Right.is(TT_LambdaArrow))
+      return true;
     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
-    if (Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
-                     tok::kw_protected) &&
-        Right.Type == TT_TemplateOpener)
+    if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
+                      tok::kw_protected) ||
+         Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
+                      Keywords.kw_native)) &&
+        Right.is(TT_TemplateOpener))
       return true;
   }
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
     return true; // Never ever merge two identifiers.
-  if (Left.Type == TT_ImplicitStringLiteral)
+  if (Left.is(TT_ImplicitStringLiteral))
     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
   if (Line.Type == LT_ObjCMethodDecl) {
-    if (Left.Type == TT_ObjCMethodSpecifier)
+    if (Left.is(TT_ObjCMethodSpecifier))
       return true;
     if (Left.is(tok::r_paren) && Right.is(tok::identifier))
       // Don't space between ')' and <id>
@@ -1723,31 +1796,30 @@
       (Right.is(tok::equal) || Left.is(tok::equal)))
     return false;
 
-  if (Right.Type == TT_TrailingReturnArrow ||
-      Left.Type == TT_TrailingReturnArrow)
+  if (Right.is(TT_TrailingReturnArrow) || Left.is(TT_TrailingReturnArrow))
     return true;
   if (Left.is(tok::comma))
     return true;
   if (Right.is(tok::comma))
     return false;
-  if (Right.Type == TT_CtorInitializerColon || Right.Type == TT_ObjCBlockLParen)
+  if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
     return true;
   if (Left.is(tok::kw_operator))
     return Right.is(tok::coloncolon);
-  if (Right.Type == TT_OverloadedOperatorLParen)
+  if (Right.is(TT_OverloadedOperatorLParen))
     return false;
   if (Right.is(tok::colon))
     return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
-           Right.getNextNonComment() && Right.Type != TT_ObjCMethodExpr &&
+           Right.getNextNonComment() && Right.isNot(TT_ObjCMethodExpr) &&
            !Left.is(tok::question) &&
-           !(Right.Type == TT_InlineASMColon && Left.is(tok::coloncolon)) &&
-           (Right.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
-  if (Left.Type == TT_UnaryOperator)
-    return Right.Type == TT_BinaryOperator;
-  if (Left.Type == TT_CastRParen)
-    return Style.SpaceAfterCStyleCast || Right.Type == TT_BinaryOperator;
+           !(Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) &&
+           (Right.isNot(TT_DictLiteral) || Style.SpacesInContainerLiterals);
+  if (Left.is(TT_UnaryOperator))
+    return Right.is(TT_BinaryOperator);
+  if (Left.is(TT_CastRParen))
+    return Style.SpaceAfterCStyleCast || Right.is(TT_BinaryOperator);
   if (Left.is(tok::greater) && Right.is(tok::greater)) {
-    return Right.Type == TT_TemplateCloser && Left.Type == TT_TemplateCloser &&
+    return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
   }
   if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
@@ -1757,27 +1829,27 @@
       Right.getPrecedence() == prec::Assignment)
     return false;
   if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
-    return (Left.Type == TT_TemplateOpener &&
+    return (Left.is(TT_TemplateOpener) &&
             Style.Standard == FormatStyle::LS_Cpp03) ||
            !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
-             Left.Type == TT_TemplateCloser || Left.Type == TT_TemplateOpener);
-  if ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser))
+             Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
+  if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
     return Style.SpacesInAngles;
-  if ((Right.Type == TT_BinaryOperator && !Left.is(tok::l_paren)) ||
-      Left.Type == TT_BinaryOperator || Left.Type == TT_ConditionalExpr)
+  if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
+      Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
     return true;
-  if (Left.Type == TT_TemplateCloser && Right.is(tok::l_paren))
+  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
+      Right.isNot(TT_FunctionTypeLParen))
     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
-  if (Right.Type == TT_TemplateOpener && Left.is(tok::r_paren) &&
-      Left.MatchingParen &&
-      Left.MatchingParen->Type == TT_OverloadedOperatorLParen)
+  if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
+      Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
     return false;
   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
       Line.First->is(tok::hash))
     return true;
-  if (Right.Type == TT_TrailingUnaryOperator)
+  if (Right.is(TT_TrailingUnaryOperator))
     return false;
-  if (Left.Type == TT_RegexLiteral)
+  if (Left.is(TT_RegexLiteral))
     return false;
   return spaceRequiredBetween(Line, Left, Right);
 }
@@ -1785,7 +1857,7 @@
 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
 static bool isAllmanBrace(const FormatToken &Tok) {
   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
-         Tok.Type != TT_ObjCBlockLBrace && Tok.Type != TT_DictLiteral;
+         !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
 }
 
 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
@@ -1806,66 +1878,68 @@
                              BeforeClosingBrace->isTrailingComment()))
     return true;
 
-  if (Right.is(tok::comment)) {
+  if (Right.is(tok::comment))
     return Left.BlockKind != BK_BracedInit &&
-           Left.Type != TT_CtorInitializerColon &&
+           Left.isNot(TT_CtorInitializerColon) &&
            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
-  } else if (Right.Previous->isTrailingComment() ||
-             (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
+  if (Right.Previous->isTrailingComment() ||
+      (Right.isStringLiteral() && Right.Previous->isStringLiteral()))
     return true;
-  } else if (Right.Previous->IsUnterminatedLiteral) {
+  if (Right.Previous->IsUnterminatedLiteral)
     return true;
-  } else if (Right.is(tok::lessless) && Right.Next &&
-             Right.Previous->is(tok::string_literal) &&
-             Right.Next->is(tok::string_literal)) {
+  if (Right.is(tok::lessless) && Right.Next &&
+      Right.Previous->is(tok::string_literal) &&
+      Right.Next->is(tok::string_literal))
     return true;
-  } else if (Right.Previous->ClosesTemplateDeclaration &&
-             Right.Previous->MatchingParen &&
-             Right.Previous->MatchingParen->NestingLevel == 0 &&
-             Style.AlwaysBreakTemplateDeclarations) {
+  if (Right.Previous->ClosesTemplateDeclaration &&
+      Right.Previous->MatchingParen &&
+      Right.Previous->MatchingParen->NestingLevel == 0 &&
+      Style.AlwaysBreakTemplateDeclarations)
     return true;
-  } else if ((Right.Type == TT_CtorInitializerComma ||
-              Right.Type == TT_CtorInitializerColon) &&
-             Style.BreakConstructorInitializersBeforeComma &&
-             !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
+  if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
+      Style.BreakConstructorInitializersBeforeComma &&
+      !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
     return true;
-  } else if (Right.is(tok::string_literal) &&
-             Right.TokenText.startswith("R\"")) {
+  if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
     // Raw string literals are special wrt. line breaks. The author has made a
     // deliberate choice and might have aligned the contents of the string
     // literal accordingly. Thus, we try keep existing line breaks.
     return Right.NewlinesBefore > 0;
-  } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
-             Style.Language == FormatStyle::LK_Proto) {
+  if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
+      Style.Language == FormatStyle::LK_Proto)
     // Don't put enums onto single lines in protocol buffers.
     return true;
-  } else if (Style.Language == FormatStyle::LK_JavaScript &&
-             Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
-             !Left.Children.empty()) {
+  if (Style.Language == FormatStyle::LK_JavaScript && Right.is(tok::r_brace) &&
+      Left.is(tok::l_brace) && !Left.Children.empty())
     // Support AllowShortFunctionsOnASingleLine for JavaScript.
     return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
            (Left.NestingLevel == 0 && Line.Level == 0 &&
             Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline);
-  } else if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
+  if (isAllmanBrace(Left) || isAllmanBrace(Right))
     return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
            Style.BreakBeforeBraces == FormatStyle::BS_GNU;
-  } else if (Style.Language == FormatStyle::LK_Proto &&
-             Left.isNot(tok::l_brace) && Right.Type == TT_SelectorName) {
+  if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
+      Right.is(TT_SelectorName))
     return true;
-  } else if (Left.Type == TT_ObjCBlockLBrace &&
-             !Style.AllowShortBlocksOnASingleLine) {
+  if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
     return true;
-  }
+
+  if ((Style.Language == FormatStyle::LK_Java ||
+       Style.Language == FormatStyle::LK_JavaScript) &&
+      Left.is(TT_LeadingJavaAnnotation) &&
+      Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
+      Line.Last->is(tok::l_brace))
+    return true;
 
   if (Style.Language == FormatStyle::LK_JavaScript) {
     // FIXME: This might apply to other languages and token kinds.
     if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
         Left.Previous->is(tok::char_constant))
       return true;
-  } else if (Style.Language == FormatStyle::LK_Java) {
-    if (Left.Type == TT_LeadingJavaAnnotation && Right.isNot(tok::l_paren) &&
-        Line.Last->is(tok::l_brace))
+    if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) &&
+        Left.NestingLevel == 0)
       return true;
+  } else if (Style.Language == FormatStyle::LK_Java) {
     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
         Right.Next->is(tok::string_literal))
       return true;
@@ -1891,10 +1965,10 @@
     return false;
   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
     return false;
-  if (Left.Type == TT_JavaAnnotation || Left.Type == TT_LeadingJavaAnnotation)
-    return true;
-  if (Right.Type == TT_StartOfName ||
-      Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator))
+  if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
+    return !Right.is(tok::l_paren);
+  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
+      Right.is(tok::kw_operator))
     return true;
   if (Right.isTrailingComment())
     // We rely on MustBreakBefore being set correctly here as we should not
@@ -1905,47 +1979,45 @@
     return Left.BlockKind == BK_BracedInit;
   if (Left.is(tok::question) && Right.is(tok::colon))
     return false;
-  if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
+  if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
     return Style.BreakBeforeTernaryOperators;
-  if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
+  if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
     return !Style.BreakBeforeTernaryOperators;
-  if (Right.Type == TT_InheritanceColon)
+  if (Right.is(TT_InheritanceColon))
     return true;
-  if (Right.is(tok::colon) && (Right.Type != TT_CtorInitializerColon &&
-                               Right.Type != TT_InlineASMColon))
+  if (Right.is(tok::colon) &&
+      !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
     return false;
-  if (Left.is(tok::colon) &&
-      (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
+  if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
     return true;
-  if (Right.Type == TT_SelectorName)
+  if (Right.is(TT_SelectorName))
     return true;
   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
     return true;
   if (Left.ClosesTemplateDeclaration)
     return true;
-  if (Right.Type == TT_RangeBasedForLoopColon ||
-      Right.Type == TT_OverloadedOperatorLParen ||
-      Right.Type == TT_OverloadedOperator)
+  if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
+                    TT_OverloadedOperator))
     return false;
-  if (Left.Type == TT_RangeBasedForLoopColon)
+  if (Left.is(TT_RangeBasedForLoopColon))
     return true;
-  if (Right.Type == TT_RangeBasedForLoopColon)
+  if (Right.is(TT_RangeBasedForLoopColon))
     return false;
-  if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
-      Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
+  if (Left.isOneOf(TT_PointerOrReference, TT_TemplateCloser,
+                   TT_UnaryOperator) ||
+      Left.is(tok::kw_operator))
     return false;
   if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
     return false;
-  if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
+  if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
     return false;
   if (Left.is(tok::l_paren) && Left.Previous &&
-      (Left.Previous->Type == TT_BinaryOperator ||
-       Left.Previous->Type == TT_CastRParen || Left.Previous->is(tok::kw_if)))
+      (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
     return false;
-  if (Right.Type == TT_ImplicitStringLiteral)
+  if (Right.is(TT_ImplicitStringLiteral))
     return false;
 
-  if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
+  if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
     return false;
 
   // We only break before r_brace if there was a corresponding break before
@@ -1955,7 +2027,7 @@
 
   // Allow breaking after a trailing annotation, e.g. after a method
   // declaration.
-  if (Left.Type == TT_TrailingAnnotation)
+  if (Left.is(TT_TrailingAnnotation))
     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
                           tok::less, tok::coloncolon);
 
@@ -1965,25 +2037,24 @@
   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
     return true;
 
-  if (Right.is(tok::identifier) && Right.Next &&
-      Right.Next->Type == TT_DictLiteral)
+  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
     return true;
 
-  if (Left.Type == TT_CtorInitializerComma &&
+  if (Left.is(TT_CtorInitializerComma) &&
       Style.BreakConstructorInitializersBeforeComma)
     return false;
-  if (Right.Type == TT_CtorInitializerComma &&
+  if (Right.is(TT_CtorInitializerComma) &&
       Style.BreakConstructorInitializersBeforeComma)
     return true;
-  if (Left.is(tok::greater) && Right.is(tok::greater) &&
-      Left.Type != TT_TemplateCloser)
+  if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
+      (Left.is(tok::less) && Right.is(tok::less)))
     return false;
-  if (Right.Type == TT_BinaryOperator &&
+  if (Right.is(TT_BinaryOperator) &&
       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
        Right.getPrecedence() != prec::Assignment))
     return true;
-  if (Left.Type == TT_ArrayInitializerLSquare)
+  if (Left.is(TT_ArrayInitializerLSquare))
     return true;
   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
     return true;
@@ -1994,7 +2065,7 @@
     return true;
   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
                       tok::kw_class, tok::kw_struct) ||
-         Right.isMemberAccess() || Right.Type == TT_TrailingReturnArrow ||
+         Right.isMemberAccess() || Right.is(TT_TrailingReturnArrow) ||
          Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at) ||
          (Left.is(tok::r_paren) &&
           Right.isOneOf(tok::identifier, tok::kw_const)) ||
diff --git a/lib/Format/TokenAnnotator.h b/lib/Format/TokenAnnotator.h
index fc4d1d6..94ed1d1 100644
--- a/lib/Format/TokenAnnotator.h
+++ b/lib/Format/TokenAnnotator.h
@@ -27,12 +27,13 @@
 
 enum LineType {
   LT_Invalid,
-  LT_Other,
-  LT_PreprocessorDirective,
-  LT_VirtualFunctionDecl,
+  LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
-  LT_ObjCProperty // An @property line.
+  LT_ObjCProperty, // An @property line.
+  LT_Other,
+  LT_PreprocessorDirective,
+  LT_VirtualFunctionDecl
 };
 
 class AnnotatedLine {
@@ -58,11 +59,8 @@
       I->Tok->Previous = Current;
       Current = Current->Next;
       Current->Children.clear();
-      for (SmallVectorImpl<UnwrappedLine>::const_iterator
-               I = Node.Children.begin(),
-               E = Node.Children.end();
-           I != E; ++I) {
-        Children.push_back(new AnnotatedLine(*I));
+      for (const auto& Child : Node.Children) {
+        Children.push_back(new AnnotatedLine(Child));
         Current->Children.push_back(Children.back());
       }
     }
@@ -74,6 +72,12 @@
     for (unsigned i = 0, e = Children.size(); i != e; ++i) {
       delete Children[i];
     }
+    FormatToken *Current = First;
+    while (Current) {
+      Current->Children.clear();
+      Current->Role.reset();
+      Current = Current->Next;
+    }
   }
 
   FormatToken *First;
@@ -100,8 +104,8 @@
 
 private:
   // Disallow copying.
-  AnnotatedLine(const AnnotatedLine &) LLVM_DELETED_FUNCTION;
-  void operator=(const AnnotatedLine &) LLVM_DELETED_FUNCTION;
+  AnnotatedLine(const AnnotatedLine &) = delete;
+  void operator=(const AnnotatedLine &) = delete;
 };
 
 /// \brief Determines extra information about the tokens comprising an
diff --git a/lib/Format/UnwrappedLineFormatter.cpp b/lib/Format/UnwrappedLineFormatter.cpp
new file mode 100644
index 0000000..8e6809f
--- /dev/null
+++ b/lib/Format/UnwrappedLineFormatter.cpp
@@ -0,0 +1,722 @@
+//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "UnwrappedLineFormatter.h"
+#include "WhitespaceManager.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "format-formatter"
+
+namespace clang {
+namespace format {
+
+namespace {
+
+bool startsExternCBlock(const AnnotatedLine &Line) {
+  const FormatToken *Next = Line.First->getNextNonComment();
+  const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
+  return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
+         NextNext && NextNext->is(tok::l_brace);
+}
+
+class LineJoiner {
+public:
+  LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords)
+      : Style(Style), Keywords(Keywords) {}
+
+  /// \brief Calculates how many lines can be merged into 1 starting at \p I.
+  unsigned
+  tryFitMultipleLinesInOne(unsigned Indent,
+                           SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+                           SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
+    // We can never merge stuff if there are trailing line comments.
+    const AnnotatedLine *TheLine = *I;
+    if (TheLine->Last->is(TT_LineComment))
+      return 0;
+
+    if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
+      return 0;
+
+    unsigned Limit =
+        Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
+    // If we already exceed the column limit, we set 'Limit' to 0. The different
+    // tryMerge..() functions can then decide whether to still do merging.
+    Limit = TheLine->Last->TotalLength > Limit
+                ? 0
+                : Limit - TheLine->Last->TotalLength;
+
+    if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
+      return 0;
+
+    // FIXME: TheLine->Level != 0 might or might not be the right check to do.
+    // If necessary, change to something smarter.
+    bool MergeShortFunctions =
+        Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
+        (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
+         I[1]->First->is(tok::r_brace)) ||
+        (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
+         TheLine->Level != 0);
+
+    if (TheLine->Last->is(TT_FunctionLBrace) &&
+        TheLine->First != TheLine->Last) {
+      return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
+    }
+    if (TheLine->Last->is(tok::l_brace)) {
+      return Style.BreakBeforeBraces == FormatStyle::BS_Attach
+                 ? tryMergeSimpleBlock(I, E, Limit)
+                 : 0;
+    }
+    if (I[1]->First->is(TT_FunctionLBrace) &&
+        Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
+      if (I[1]->Last->is(TT_LineComment))
+        return 0;
+
+      // Check for Limit <= 2 to account for the " {".
+      if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
+        return 0;
+      Limit -= 2;
+
+      unsigned MergedLines = 0;
+      if (MergeShortFunctions) {
+        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
+        // If we managed to merge the block, count the function header, which is
+        // on a separate line.
+        if (MergedLines > 0)
+          ++MergedLines;
+      }
+      return MergedLines;
+    }
+    if (TheLine->First->is(tok::kw_if)) {
+      return Style.AllowShortIfStatementsOnASingleLine
+                 ? tryMergeSimpleControlStatement(I, E, Limit)
+                 : 0;
+    }
+    if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
+      return Style.AllowShortLoopsOnASingleLine
+                 ? tryMergeSimpleControlStatement(I, E, Limit)
+                 : 0;
+    }
+    if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
+      return Style.AllowShortCaseLabelsOnASingleLine
+                 ? tryMergeShortCaseLabels(I, E, Limit)
+                 : 0;
+    }
+    if (TheLine->InPPDirective &&
+        (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
+      return tryMergeSimplePPDirective(I, E, Limit);
+    }
+    return 0;
+  }
+
+private:
+  unsigned
+  tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+                            SmallVectorImpl<AnnotatedLine *>::const_iterator E,
+                            unsigned Limit) {
+    if (Limit == 0)
+      return 0;
+    if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
+      return 0;
+    if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
+      return 0;
+    if (1 + I[1]->Last->TotalLength > Limit)
+      return 0;
+    return 1;
+  }
+
+  unsigned tryMergeSimpleControlStatement(
+      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
+    if (Limit == 0)
+      return 0;
+    if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
+         Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
+        (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
+      return 0;
+    if (I[1]->InPPDirective != (*I)->InPPDirective ||
+        (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
+      return 0;
+    Limit = limitConsideringMacros(I + 1, E, Limit);
+    AnnotatedLine &Line = **I;
+    if (Line.Last->isNot(tok::r_paren))
+      return 0;
+    if (1 + I[1]->Last->TotalLength > Limit)
+      return 0;
+    if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
+                             tok::kw_while, TT_LineComment))
+      return 0;
+    // Only inline simple if's (no nested if or else).
+    if (I + 2 != E && Line.First->is(tok::kw_if) &&
+        I[2]->First->is(tok::kw_else))
+      return 0;
+    return 1;
+  }
+
+  unsigned tryMergeShortCaseLabels(
+      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
+    if (Limit == 0 || I + 1 == E ||
+        I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
+      return 0;
+    unsigned NumStmts = 0;
+    unsigned Length = 0;
+    bool InPPDirective = I[0]->InPPDirective;
+    for (; NumStmts < 3; ++NumStmts) {
+      if (I + 1 + NumStmts == E)
+        break;
+      const AnnotatedLine *Line = I[1 + NumStmts];
+      if (Line->InPPDirective != InPPDirective)
+        break;
+      if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
+        break;
+      if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
+                               tok::kw_while, tok::comment))
+        return 0;
+      Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
+    }
+    if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
+      return 0;
+    return NumStmts;
+  }
+
+  unsigned
+  tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+                      SmallVectorImpl<AnnotatedLine *>::const_iterator E,
+                      unsigned Limit) {
+    AnnotatedLine &Line = **I;
+
+    // Don't merge ObjC @ keywords and methods.
+    // FIXME: If an option to allow short exception handling clauses on a single
+    // line is added, change this to not return for @try and friends.
+    if (Style.Language != FormatStyle::LK_Java &&
+        Line.First->isOneOf(tok::at, tok::minus, tok::plus))
+      return 0;
+
+    // Check that the current line allows merging. This depends on whether we
+    // are in a control flow statements as well as several style flags.
+    if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
+      return 0;
+    if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
+                            tok::kw___try, tok::kw_catch, tok::kw___finally,
+                            tok::kw_for, tok::r_brace) ||
+        Line.First->is(Keywords.kw___except)) {
+      if (!Style.AllowShortBlocksOnASingleLine)
+        return 0;
+      if (!Style.AllowShortIfStatementsOnASingleLine &&
+          Line.First->is(tok::kw_if))
+        return 0;
+      if (!Style.AllowShortLoopsOnASingleLine &&
+          Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
+        return 0;
+      // FIXME: Consider an option to allow short exception handling clauses on
+      // a single line.
+      // FIXME: This isn't covered by tests.
+      // FIXME: For catch, __except, __finally the first token on the line
+      // is '}', so this isn't correct here.
+      if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
+                              Keywords.kw___except, tok::kw___finally))
+        return 0;
+    }
+
+    FormatToken *Tok = I[1]->First;
+    if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
+        (Tok->getNextNonComment() == nullptr ||
+         Tok->getNextNonComment()->is(tok::semi))) {
+      // We merge empty blocks even if the line exceeds the column limit.
+      Tok->SpacesRequiredBefore = 0;
+      Tok->CanBreakBefore = true;
+      return 1;
+    } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
+               !startsExternCBlock(Line)) {
+      // We don't merge short records.
+      if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
+        return 0;
+
+      // Check that we still have three lines and they fit into the limit.
+      if (I + 2 == E || I[2]->Type == LT_Invalid)
+        return 0;
+      Limit = limitConsideringMacros(I + 2, E, Limit);
+
+      if (!nextTwoLinesFitInto(I, Limit))
+        return 0;
+
+      // Second, check that the next line does not contain any braces - if it
+      // does, readability declines when putting it into a single line.
+      if (I[1]->Last->is(TT_LineComment))
+        return 0;
+      do {
+        if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
+          return 0;
+        Tok = Tok->Next;
+      } while (Tok);
+
+      // Last, check that the third line starts with a closing brace.
+      Tok = I[2]->First;
+      if (Tok->isNot(tok::r_brace))
+        return 0;
+
+      return 2;
+    }
+    return 0;
+  }
+
+  /// Returns the modified column limit for \p I if it is inside a macro and
+  /// needs a trailing '\'.
+  unsigned
+  limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+                         SmallVectorImpl<AnnotatedLine *>::const_iterator E,
+                         unsigned Limit) {
+    if (I[0]->InPPDirective && I + 1 != E &&
+        !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
+      return Limit < 2 ? 0 : Limit - 2;
+    }
+    return Limit;
+  }
+
+  bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+                           unsigned Limit) {
+    if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
+      return false;
+    return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
+  }
+
+  bool containsMustBreak(const AnnotatedLine *Line) {
+    for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
+      if (Tok->MustBreakBefore)
+        return true;
+    }
+    return false;
+  }
+
+  const FormatStyle &Style;
+  const AdditionalKeywords &Keywords;
+};
+
+class NoColumnLimitFormatter {
+public:
+  NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
+
+  /// \brief Formats the line starting at \p State, simply keeping all of the
+  /// input's line breaking decisions.
+  void format(unsigned FirstIndent, const AnnotatedLine *Line) {
+    LineState State =
+        Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
+    while (State.NextToken) {
+      bool Newline =
+          Indenter->mustBreak(State) ||
+          (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
+      Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
+    }
+  }
+
+private:
+  ContinuationIndenter *Indenter;
+};
+
+
+static void markFinalized(FormatToken *Tok) {
+  for (; Tok; Tok = Tok->Next) {
+    Tok->Finalized = true;
+    for (AnnotatedLine *Child : Tok->Children)
+      markFinalized(Child->First);
+  }
+}
+
+} // namespace
+
+unsigned
+UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
+                               bool DryRun, int AdditionalIndent,
+                               bool FixBadIndentation) {
+  LineJoiner Joiner(Style, Keywords);
+
+  // Try to look up already computed penalty in DryRun-mode.
+  std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
+      &Lines, AdditionalIndent);
+  auto CacheIt = PenaltyCache.find(CacheKey);
+  if (DryRun && CacheIt != PenaltyCache.end())
+    return CacheIt->second;
+
+  assert(!Lines.empty());
+  unsigned Penalty = 0;
+  std::vector<int> IndentForLevel;
+  for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
+    IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
+  const AnnotatedLine *PreviousLine = nullptr;
+  for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
+                                                        E = Lines.end();
+       I != E; ++I) {
+    const AnnotatedLine &TheLine = **I;
+    const FormatToken *FirstTok = TheLine.First;
+    int Offset = getIndentOffset(*FirstTok);
+
+    // Determine indent and try to merge multiple unwrapped lines.
+    unsigned Indent;
+    if (TheLine.InPPDirective) {
+      Indent = TheLine.Level * Style.IndentWidth;
+    } else {
+      while (IndentForLevel.size() <= TheLine.Level)
+        IndentForLevel.push_back(-1);
+      IndentForLevel.resize(TheLine.Level + 1);
+      Indent = getIndent(IndentForLevel, TheLine.Level);
+    }
+    unsigned LevelIndent = Indent;
+    if (static_cast<int>(Indent) + Offset >= 0)
+      Indent += Offset;
+
+    // Merge multiple lines if possible.
+    unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
+    if (MergedLines > 0 && Style.ColumnLimit == 0) {
+      // Disallow line merging if there is a break at the start of one of the
+      // input lines.
+      for (unsigned i = 0; i < MergedLines; ++i) {
+        if (I[i + 1]->First->NewlinesBefore > 0)
+          MergedLines = 0;
+      }
+    }
+    if (!DryRun) {
+      for (unsigned i = 0; i < MergedLines; ++i) {
+        join(*I[i], *I[i + 1]);
+      }
+    }
+    I += MergedLines;
+
+    bool FixIndentation =
+        FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
+    if (TheLine.First->is(tok::eof)) {
+      if (PreviousLine && PreviousLine->Affected && !DryRun) {
+        // Remove the file's trailing whitespace.
+        unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
+        Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
+                                       /*IndentLevel=*/0, /*Spaces=*/0,
+                                       /*TargetColumn=*/0);
+      }
+    } else if (TheLine.Type != LT_Invalid &&
+               (TheLine.Affected || FixIndentation)) {
+      if (FirstTok->WhitespaceRange.isValid()) {
+        if (!DryRun)
+          formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
+                           TheLine.InPPDirective);
+      } else {
+        Indent = LevelIndent = FirstTok->OriginalColumn;
+      }
+
+      // If everything fits on a single line, just put it there.
+      unsigned ColumnLimit = Style.ColumnLimit;
+      if (I + 1 != E) {
+        AnnotatedLine *NextLine = I[1];
+        if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
+          ColumnLimit = getColumnLimit(TheLine.InPPDirective);
+      }
+
+      if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
+          TheLine.Type == LT_ImportStatement) {
+        LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
+        while (State.NextToken) {
+          formatChildren(State, /*Newline=*/false, DryRun, Penalty);
+          Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
+        }
+      } else if (Style.ColumnLimit == 0) {
+        // FIXME: Implement nested blocks for ColumnLimit = 0.
+        NoColumnLimitFormatter Formatter(Indenter);
+        if (!DryRun)
+          Formatter.format(Indent, &TheLine);
+      } else {
+        Penalty += format(TheLine, Indent, DryRun);
+      }
+
+      if (!TheLine.InPPDirective)
+        IndentForLevel[TheLine.Level] = LevelIndent;
+    } else if (TheLine.ChildrenAffected) {
+      format(TheLine.Children, DryRun);
+    } else {
+      // Format the first token if necessary, and notify the WhitespaceManager
+      // about the unchanged whitespace.
+      for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
+        if (Tok == TheLine.First && (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
+          unsigned LevelIndent = Tok->OriginalColumn;
+          if (!DryRun) {
+            // Remove trailing whitespace of the previous line.
+            if ((PreviousLine && PreviousLine->Affected) ||
+                TheLine.LeadingEmptyLinesAffected) {
+              formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
+                               TheLine.InPPDirective);
+            } else {
+              Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
+            }
+          }
+
+          if (static_cast<int>(LevelIndent) - Offset >= 0)
+            LevelIndent -= Offset;
+          if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
+            IndentForLevel[TheLine.Level] = LevelIndent;
+        } else if (!DryRun) {
+          Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
+        }
+      }
+    }
+    if (!DryRun)
+      markFinalized(TheLine.First);
+    PreviousLine = *I;
+  }
+  PenaltyCache[CacheKey] = Penalty;
+  return Penalty;
+}
+
+unsigned UnwrappedLineFormatter::format(const AnnotatedLine &Line,
+                                        unsigned FirstIndent, bool DryRun) {
+  LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
+
+  // If the ObjC method declaration does not fit on a line, we should format
+  // it with one arg per line.
+  if (State.Line->Type == LT_ObjCMethodDecl)
+    State.Stack.back().BreakBeforeParameter = true;
+
+  // Find best solution in solution space.
+  return analyzeSolutionSpace(State, DryRun);
+}
+
+void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
+                                              const AnnotatedLine *PreviousLine,
+                                              unsigned IndentLevel,
+                                              unsigned Indent,
+                                              bool InPPDirective) {
+  unsigned Newlines =
+      std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
+  // Remove empty lines before "}" where applicable.
+  if (RootToken.is(tok::r_brace) &&
+      (!RootToken.Next ||
+       (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
+    Newlines = std::min(Newlines, 1u);
+  if (Newlines == 0 && !RootToken.IsFirst)
+    Newlines = 1;
+  if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
+    Newlines = 0;
+
+  // Remove empty lines after "{".
+  if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
+      PreviousLine->Last->is(tok::l_brace) &&
+      PreviousLine->First->isNot(tok::kw_namespace) &&
+      !startsExternCBlock(*PreviousLine))
+    Newlines = 1;
+
+  // Insert extra new line before access specifiers.
+  if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
+      RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
+    ++Newlines;
+
+  // Remove empty lines after access specifiers.
+  if (PreviousLine && PreviousLine->First->isAccessSpecifier())
+    Newlines = std::min(1u, Newlines);
+
+  Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
+                                 Indent, InPPDirective &&
+                                             !RootToken.HasUnescapedNewline);
+}
+
+/// \brief Get the indent of \p Level from \p IndentForLevel.
+///
+/// \p IndentForLevel must contain the indent for the level \c l
+/// at \p IndentForLevel[l], or a value < 0 if the indent for
+/// that level is unknown.
+unsigned UnwrappedLineFormatter::getIndent(ArrayRef<int> IndentForLevel,
+                                           unsigned Level) {
+  if (IndentForLevel[Level] != -1)
+    return IndentForLevel[Level];
+  if (Level == 0)
+    return 0;
+  return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
+}
+
+void UnwrappedLineFormatter::join(AnnotatedLine &A, const AnnotatedLine &B) {
+  assert(!A.Last->Next);
+  assert(!B.First->Previous);
+  if (B.Affected)
+    A.Affected = true;
+  A.Last->Next = B.First;
+  B.First->Previous = A.Last;
+  B.First->CanBreakBefore = true;
+  unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
+  for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
+    Tok->TotalLength += LengthA;
+    A.Last = Tok;
+  }
+}
+
+unsigned UnwrappedLineFormatter::analyzeSolutionSpace(LineState &InitialState,
+                                                      bool DryRun) {
+  std::set<LineState *, CompareLineStatePointers> Seen;
+
+  // Increasing count of \c StateNode items we have created. This is used to
+  // create a deterministic order independent of the container.
+  unsigned Count = 0;
+  QueueType Queue;
+
+  // Insert start element into queue.
+  StateNode *Node =
+      new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
+  Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
+  ++Count;
+
+  unsigned Penalty = 0;
+
+  // While not empty, take first element and follow edges.
+  while (!Queue.empty()) {
+    Penalty = Queue.top().first.first;
+    StateNode *Node = Queue.top().second;
+    if (!Node->State.NextToken) {
+      DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
+      break;
+    }
+    Queue.pop();
+
+    // Cut off the analysis of certain solutions if the analysis gets too
+    // complex. See description of IgnoreStackForComparison.
+    if (Count > 10000)
+      Node->State.IgnoreStackForComparison = true;
+
+    if (!Seen.insert(&Node->State).second)
+      // State already examined with lower penalty.
+      continue;
+
+    FormatDecision LastFormat = Node->State.NextToken->Decision;
+    if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
+      addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
+    if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
+      addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
+  }
+
+  if (Queue.empty()) {
+    // We were unable to find a solution, do nothing.
+    // FIXME: Add diagnostic?
+    DEBUG(llvm::dbgs() << "Could not find a solution.\n");
+    return 0;
+  }
+
+  // Reconstruct the solution.
+  if (!DryRun)
+    reconstructPath(InitialState, Queue.top().second);
+
+  DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
+  DEBUG(llvm::dbgs() << "---\n");
+
+  return Penalty;
+}
+
+#ifndef NDEBUG
+static void printLineState(const LineState &State) {
+  llvm::dbgs() << "State: ";
+  for (const ParenState &P : State.Stack) {
+    llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
+                 << " ";
+  }
+  llvm::dbgs() << State.NextToken->TokenText << "\n";
+}
+#endif
+
+void UnwrappedLineFormatter::reconstructPath(LineState &State,
+                                             StateNode *Current) {
+  std::deque<StateNode *> Path;
+  // We do not need a break before the initial token.
+  while (Current->Previous) {
+    Path.push_front(Current);
+    Current = Current->Previous;
+  }
+  for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
+       I != E; ++I) {
+    unsigned Penalty = 0;
+    formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
+    Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
+
+    DEBUG({
+      printLineState((*I)->Previous->State);
+      if ((*I)->NewLine) {
+        llvm::dbgs() << "Penalty for placing "
+                     << (*I)->Previous->State.NextToken->Tok.getName() << ": "
+                     << Penalty << "\n";
+      }
+    });
+  }
+}
+
+void UnwrappedLineFormatter::addNextStateToQueue(unsigned Penalty,
+                                                 StateNode *PreviousNode,
+                                                 bool NewLine, unsigned *Count,
+                                                 QueueType *Queue) {
+  if (NewLine && !Indenter->canBreak(PreviousNode->State))
+    return;
+  if (!NewLine && Indenter->mustBreak(PreviousNode->State))
+    return;
+
+  StateNode *Node = new (Allocator.Allocate())
+      StateNode(PreviousNode->State, NewLine, PreviousNode);
+  if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
+    return;
+
+  Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
+
+  Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
+  ++(*Count);
+}
+
+bool UnwrappedLineFormatter::formatChildren(LineState &State, bool NewLine,
+                                            bool DryRun, unsigned &Penalty) {
+  const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
+  FormatToken &Previous = *State.NextToken->Previous;
+  if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->BlockKind != BK_Block ||
+      Previous.Children.size() == 0)
+    // The previous token does not open a block. Nothing to do. We don't
+    // assert so that we can simply call this function for all tokens.
+    return true;
+
+  if (NewLine) {
+    int AdditionalIndent = State.Stack.back().Indent -
+                           Previous.Children[0]->Level * Style.IndentWidth;
+
+    Penalty += format(Previous.Children, DryRun, AdditionalIndent,
+                      /*FixBadIndentation=*/true);
+    return true;
+  }
+
+  if (Previous.Children[0]->First->MustBreakBefore)
+    return false;
+
+  // Cannot merge multiple statements into a single line.
+  if (Previous.Children.size() > 1)
+    return false;
+
+  // Cannot merge into one line if this line ends on a comment.
+  if (Previous.is(tok::comment))
+    return false;
+
+  // We can't put the closing "}" on a line with a trailing comment.
+  if (Previous.Children[0]->Last->isTrailingComment())
+    return false;
+
+  // If the child line exceeds the column limit, we wouldn't want to merge it.
+  // We add +2 for the trailing " }".
+  if (Style.ColumnLimit > 0 &&
+      Previous.Children[0]->Last->TotalLength + State.Column + 2 >
+          Style.ColumnLimit)
+    return false;
+
+  if (!DryRun) {
+    Whitespaces->replaceWhitespace(
+        *Previous.Children[0]->First,
+        /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
+        /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
+  }
+  Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
+
+  State.Column += 1 + Previous.Children[0]->Last->TotalLength;
+  return true;
+}
+
+} // namespace format
+} // namespace clang
diff --git a/lib/Format/UnwrappedLineFormatter.h b/lib/Format/UnwrappedLineFormatter.h
new file mode 100644
index 0000000..9b83b27
--- /dev/null
+++ b/lib/Format/UnwrappedLineFormatter.h
@@ -0,0 +1,172 @@
+//===--- UnwrappedLineFormatter.h - Format C++ code -------------*- C++ -*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Implements a combinartorial exploration of all the different
+/// linebreaks unwrapped lines can be formatted in.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEFORMATTER_H
+#define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEFORMATTER_H
+
+#include "ContinuationIndenter.h"
+#include "clang/Format/Format.h"
+#include <map>
+#include <queue>
+#include <string>
+
+namespace clang {
+namespace format {
+
+class ContinuationIndenter;
+class WhitespaceManager;
+
+class UnwrappedLineFormatter {
+public:
+  UnwrappedLineFormatter(ContinuationIndenter *Indenter,
+                         WhitespaceManager *Whitespaces,
+                         const FormatStyle &Style,
+                         const AdditionalKeywords &Keywords)
+      : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
+        Keywords(Keywords) {}
+
+  unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
+                  int AdditionalIndent = 0, bool FixBadIndentation = false);
+
+private:
+  /// \brief Formats an \c AnnotatedLine and returns the penalty.
+  ///
+  /// If \p DryRun is \c false, directly applies the changes.
+  unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
+                  bool DryRun);
+
+  /// \brief An edge in the solution space from \c Previous->State to \c State,
+  /// inserting a newline dependent on the \c NewLine.
+  struct StateNode {
+    StateNode(const LineState &State, bool NewLine, StateNode *Previous)
+        : State(State), NewLine(NewLine), Previous(Previous) {}
+    LineState State;
+    bool NewLine;
+    StateNode *Previous;
+  };
+
+  /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
+  ///
+  /// In case of equal penalties, we want to prefer states that were inserted
+  /// first. During state generation we make sure that we insert states first
+  /// that break the line as late as possible.
+  typedef std::pair<unsigned, unsigned> OrderedPenalty;
+
+  /// \brief An item in the prioritized BFS search queue. The \c StateNode's
+  /// \c State has the given \c OrderedPenalty.
+  typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
+
+  /// \brief The BFS queue type.
+  typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
+                              std::greater<QueueItem> > QueueType;
+
+  /// \brief Get the offset of the line relatively to the level.
+  ///
+  /// For example, 'public:' labels in classes are offset by 1 or 2
+  /// characters to the left from their level.
+  int getIndentOffset(const FormatToken &RootToken) {
+    if (Style.Language == FormatStyle::LK_Java ||
+        Style.Language == FormatStyle::LK_JavaScript)
+      return 0;
+    if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
+      return Style.AccessModifierOffset;
+    return 0;
+  }
+
+  /// \brief Add a new line and the required indent before the first Token
+  /// of the \c UnwrappedLine if there was no structural parsing error.
+  void formatFirstToken(FormatToken &RootToken,
+                        const AnnotatedLine *PreviousLine, unsigned IndentLevel,
+                        unsigned Indent, bool InPPDirective);
+
+  /// \brief Get the indent of \p Level from \p IndentForLevel.
+  ///
+  /// \p IndentForLevel must contain the indent for the level \c l
+  /// at \p IndentForLevel[l], or a value < 0 if the indent for
+  /// that level is unknown.
+  unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level);
+
+  void join(AnnotatedLine &A, const AnnotatedLine &B);
+
+  unsigned getColumnLimit(bool InPPDirective) const {
+    // In preprocessor directives reserve two chars for trailing " \"
+    return Style.ColumnLimit - (InPPDirective ? 2 : 0);
+  }
+
+  struct CompareLineStatePointers {
+    bool operator()(LineState *obj1, LineState *obj2) const {
+      return *obj1 < *obj2;
+    }
+  };
+
+  /// \brief Analyze the entire solution space starting from \p InitialState.
+  ///
+  /// This implements a variant of Dijkstra's algorithm on the graph that spans
+  /// the solution space (\c LineStates are the nodes). The algorithm tries to
+  /// find the shortest path (the one with lowest penalty) from \p InitialState
+  /// to a state where all tokens are placed. Returns the penalty.
+  ///
+  /// If \p DryRun is \c false, directly applies the changes.
+  unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false);
+
+  void reconstructPath(LineState &State, StateNode *Current);
+
+  /// \brief Add the following state to the analysis queue \c Queue.
+  ///
+  /// Assume the current state is \p PreviousNode and has been reached with a
+  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
+  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
+                           bool NewLine, unsigned *Count, QueueType *Queue);
+
+  /// \brief If the \p State's next token is an r_brace closing a nested block,
+  /// format the nested block before it.
+  ///
+  /// Returns \c true if all children could be placed successfully and adapts
+  /// \p Penalty as well as \p State. If \p DryRun is false, also directly
+  /// creates changes using \c Whitespaces.
+  ///
+  /// The crucial idea here is that children always get formatted upon
+  /// encountering the closing brace right after the nested block. Now, if we
+  /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
+  /// \c false), the entire block has to be kept on the same line (which is only
+  /// possible if it fits on the line, only contains a single statement, etc.
+  ///
+  /// If \p NewLine is true, we format the nested block on separate lines, i.e.
+  /// break after the "{", format all lines with correct indentation and the put
+  /// the closing "}" on yet another new line.
+  ///
+  /// This enables us to keep the simple structure of the
+  /// \c UnwrappedLineFormatter, where we only have two options for each token:
+  /// break or don't break.
+  bool formatChildren(LineState &State, bool NewLine, bool DryRun,
+                      unsigned &Penalty);
+
+  ContinuationIndenter *Indenter;
+  WhitespaceManager *Whitespaces;
+  FormatStyle Style;
+  const AdditionalKeywords &Keywords;
+
+  llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
+
+  // Cache to store the penalty of formatting a vector of AnnotatedLines
+  // starting from a specific additional offset. Improves performance if there
+  // are many nested blocks.
+  std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
+           unsigned> PenaltyCache;
+};
+} // end namespace format
+} // end namespace clang
+
+#endif // LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEFORMATTER_H
diff --git a/lib/Format/UnwrappedLineParser.cpp b/lib/Format/UnwrappedLineParser.cpp
index af1e94c..7bab55c 100644
--- a/lib/Format/UnwrappedLineParser.cpp
+++ b/lib/Format/UnwrappedLineParser.cpp
@@ -262,7 +262,7 @@
 void UnwrappedLineParser::parseFile() {
   ScopedDeclarationState DeclarationState(
       *Line, DeclarationScopeStack,
-      /*MustBeDeclaration=*/ !Line->InPPDirective);
+      /*MustBeDeclaration=*/!Line->InPPDirective);
   parseLevel(/*HasOpeningBrace=*/false);
   // Make sure to format the remaining tokens.
   flushComments(true);
@@ -374,6 +374,7 @@
     case tok::kw_for:
     case tok::kw_switch:
     case tok::kw_try:
+    case tok::kw___try:
       if (!LBraceStack.empty())
         LBraceStack.back()->BlockKind = BK_Block;
       break;
@@ -418,6 +419,8 @@
 }
 
 static bool IsGoogScope(const UnwrappedLine &Line) {
+  // FIXME: Closure-library specific stuff should not be hard-coded but be
+  // configurable.
   if (Line.Tokens.size() < 4)
     return false;
   auto I = Line.Tokens.begin();
@@ -547,6 +550,7 @@
 void UnwrappedLineParser::parsePPIf(bool IfDef) {
   nextToken();
   bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
+                         FormatTok->Tok.getLiteralData() != nullptr &&
                          StringRef(FormatTok->Tok.getLiteralData(),
                                    FormatTok->Tok.getLength()) == "0") ||
                         FormatTok->Tok.is(tok::kw_false);
@@ -653,20 +657,25 @@
       nextToken();
       addUnwrappedLine();
       return;
+    case tok::objc_try:
+      // This branch isn't strictly necessary (the kw_try case below would
+      // do this too after the tok::at is parsed above).  But be explicit.
+      parseTryCatch();
+      return;
     default:
       break;
     }
     break;
   case tok::kw_asm:
-    FormatTok->Finalized = true;
     nextToken();
     if (FormatTok->is(tok::l_brace)) {
+      nextToken();
       while (FormatTok && FormatTok->isNot(tok::eof)) {
-        FormatTok->Finalized = true;
         if (FormatTok->is(tok::r_brace)) {
           nextToken();
           break;
         }
+        FormatTok->Finalized = true;
         nextToken();
       }
     }
@@ -684,7 +693,8 @@
   case tok::kw_public:
   case tok::kw_protected:
   case tok::kw_private:
-    if (Style.Language == FormatStyle::LK_Java)
+    if (Style.Language == FormatStyle::LK_Java ||
+        Style.Language == FormatStyle::LK_JavaScript)
       nextToken();
     else
       parseAccessSpecifier();
@@ -710,6 +720,7 @@
     parseCaseLabel();
     return;
   case tok::kw_try:
+  case tok::kw___try:
     parseTryCatch();
     return;
   case tok::kw_extern:
@@ -723,11 +734,22 @@
       }
     }
     break;
+  case tok::kw_export:
+    if (Style.Language == FormatStyle::LK_JavaScript) {
+      parseJavaScriptEs6ImportExport();
+      return;
+    }
+    break;
   case tok::identifier:
     if (FormatTok->IsForEachMacro) {
       parseForOrWhileLoop();
       return;
     }
+    if (Style.Language == FormatStyle::LK_JavaScript &&
+        FormatTok->is(Keywords.kw_import)) {
+      parseJavaScriptEs6ImportExport();
+      return;
+    }
     // In all other cases, parse the declaration.
     break;
   default:
@@ -745,7 +767,8 @@
       break;
     case tok::kw_typedef:
       nextToken();
-      if (FormatTok->is(Keywords.kw_NS_ENUM))
+      if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
+                             Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
         parseEnum();
       break;
     case tok::kw_struct:
@@ -755,6 +778,13 @@
       // A record declaration or definition is always the start of a structural
       // element.
       break;
+    case tok::period:
+      nextToken();
+      // In Java, classes have an implicit static member "class".
+      if (Style.Language == FormatStyle::LK_Java && FormatTok &&
+          FormatTok->is(tok::kw_class))
+        nextToken();
+      break;
     case tok::semi:
       nextToken();
       addUnwrappedLine();
@@ -805,13 +835,17 @@
         break;
       }
       nextToken();
-      if (Line->Tokens.size() == 1) {
+      if (Line->Tokens.size() == 1 &&
+          // JS doesn't have macros, and within classes colons indicate fields,
+          // not labels.
+          (Style.Language != FormatStyle::LK_JavaScript ||
+           !Line->MustBeDeclaration)) {
         if (FormatTok->Tok.is(tok::colon)) {
           parseLabel();
           return;
         }
         // Recognize function-like macro usages without trailing semicolon as
-        // well as free-standing macrose like Q_OBJECT.
+        // well as free-standing macros like Q_OBJECT.
         bool FunctionLike = FormatTok->is(tok::l_paren);
         if (FunctionLike)
           parseParens();
@@ -867,6 +901,10 @@
     case tok::l_paren:
       parseParens();
       break;
+    case tok::amp:
+    case tok::star:
+    case tok::kw_const:
+    case tok::comma:
     case tok::less:
     case tok::greater:
     case tok::identifier:
@@ -938,7 +976,7 @@
 
   // Consume function name.
   if (FormatTok->is(tok::identifier))
-      nextToken();
+    nextToken();
 
   if (FormatTok->isNot(tok::l_paren))
     return;
@@ -1019,6 +1057,8 @@
     switch (FormatTok->Tok.getKind()) {
     case tok::l_paren:
       parseParens();
+      if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
+        parseChildBlock();
       break;
     case tok::r_paren:
       nextToken();
@@ -1029,12 +1069,11 @@
     case tok::l_square:
       tryToParseLambda();
       break;
-    case tok::l_brace: {
+    case tok::l_brace:
       if (!tryToParseBracedList()) {
         parseChildBlock();
       }
       break;
-    }
     case tok::at:
       nextToken();
       if (FormatTok->Tok.is(tok::l_brace))
@@ -1133,7 +1172,7 @@
 }
 
 void UnwrappedLineParser::parseTryCatch() {
-  assert(FormatTok->is(tok::kw_try) && "'try' expected");
+  assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
   nextToken();
   bool NeedsUnwrappedLine = false;
   if (FormatTok->is(tok::colon)) {
@@ -1149,6 +1188,10 @@
         nextToken();
     }
   }
+  // Parse try with resource.
+  if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
+    parseParens();
+  }
   if (FormatTok->is(tok::l_brace)) {
     CompoundStatementIndenter Indenter(this, Style, Line->Level);
     parseBlock(/*MustBeDeclaration=*/false);
@@ -1169,17 +1212,24 @@
     parseStructuralElement();
     --Line->Level;
   }
-  while (FormatTok->is(tok::kw_catch) ||
-         ((Style.Language == FormatStyle::LK_Java ||
-           Style.Language == FormatStyle::LK_JavaScript) &&
-          FormatTok->is(Keywords.kw_finally))) {
+  while (1) {
+    if (FormatTok->is(tok::at))
+      nextToken();
+    if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
+                             tok::kw___finally) ||
+          ((Style.Language == FormatStyle::LK_Java ||
+            Style.Language == FormatStyle::LK_JavaScript) &&
+           FormatTok->is(Keywords.kw_finally)) ||
+          (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
+           FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
+      break;
     nextToken();
     while (FormatTok->isNot(tok::l_brace)) {
       if (FormatTok->is(tok::l_paren)) {
         parseParens();
         continue;
       }
-      if (FormatTok->isOneOf(tok::semi, tok::r_brace))
+      if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
         return;
       nextToken();
     }
@@ -1480,7 +1530,8 @@
   // class A {} n, m;
   // will end up in one unwrapped line.
   // This does not apply for Java.
-  if (Style.Language == FormatStyle::LK_Java)
+  if (Style.Language == FormatStyle::LK_Java ||
+      Style.Language == FormatStyle::LK_JavaScript)
     addUnwrappedLine();
 }
 
@@ -1559,6 +1610,30 @@
   parseObjCUntilAtEnd();
 }
 
+void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
+  assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export));
+  nextToken();
+
+  if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, Keywords.kw_function,
+                         Keywords.kw_var))
+    return; // Fall through to parsing the corresponding structure.
+
+  if (FormatTok->is(tok::kw_default)) {
+    nextToken(); // export default ..., fall through after eating 'default'.
+    return;
+  }
+
+  if (FormatTok->is(tok::l_brace)) {
+    FormatTok->BlockKind = BK_Block;
+    parseBracedList();
+  }
+
+  while (!eof() && FormatTok->isNot(tok::semi) &&
+         FormatTok->isNot(tok::l_brace)) {
+    nextToken();
+  }
+}
+
 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
                                                  StringRef Prefix = "") {
   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
@@ -1643,8 +1718,7 @@
            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
       // If there is an unfinished unwrapped line, we flush the preprocessor
       // directives only after that unwrapped line was finished later.
-      bool SwitchToPreprocessorLines =
-          !Line->Tokens.empty() && CurrentLines == &Lines;
+      bool SwitchToPreprocessorLines = !Line->Tokens.empty();
       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
       // Comments stored before the preprocessor directive need to be output
       // before the preprocessor directive, at the same level as the
diff --git a/lib/Format/UnwrappedLineParser.h b/lib/Format/UnwrappedLineParser.h
index 3218afe..4b953ea 100644
--- a/lib/Format/UnwrappedLineParser.h
+++ b/lib/Format/UnwrappedLineParser.h
@@ -103,6 +103,7 @@
   void parseObjCUntilAtEnd();
   void parseObjCInterfaceOrImplementation();
   void parseObjCProtocol();
+  void parseJavaScriptEs6ImportExport();
   bool tryToParseLambda();
   bool tryToParseLambdaIntroducer();
   void tryToParseJSFunction();
diff --git a/lib/Format/WhitespaceManager.cpp b/lib/Format/WhitespaceManager.cpp
index 47b94de..44e5f69 100644
--- a/lib/Format/WhitespaceManager.cpp
+++ b/lib/Format/WhitespaceManager.cpp
@@ -81,7 +81,7 @@
       // FIXME: We still need to take this change in account to properly
       // calculate the new length of the comment and to calculate the changes
       // for which to do the alignment when aligning comments.
-      Tok.Type == TT_LineComment && Newlines > 0 ? tok::comment : tok::unknown,
+      Tok.is(TT_LineComment) && Newlines > 0 ? tok::comment : tok::unknown,
       InPPDirective && !Tok.IsFirst));
 }
 
@@ -163,15 +163,17 @@
                                   Changes[i - 1].StartOfTokenColumn == 0;
     bool WasAlignedWithStartOfNextLine = false;
     if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
+      unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
+          Changes[i].OriginalWhitespaceRange.getEnd());
       for (unsigned j = i + 1; j != e; ++j) {
         if (Changes[j].Kind != tok::comment) { // Skip over comments.
+          unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
+              Changes[j].OriginalWhitespaceRange.getEnd());
           // The start of the next token was previously aligned with the
           // start of this comment.
           WasAlignedWithStartOfNextLine =
-              (SourceMgr.getSpellingColumnNumber(
-                   Changes[i].OriginalWhitespaceRange.getEnd()) ==
-               SourceMgr.getSpellingColumnNumber(
-                   Changes[j].OriginalWhitespaceRange.getEnd()));
+              CommentColumn == NextColumn ||
+              CommentColumn == NextColumn + Style.IndentWidth;
           break;
         }
       }
@@ -262,6 +264,11 @@
 void WhitespaceManager::generateChanges() {
   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
     const Change &C = Changes[i];
+    if (i > 0) {
+      assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
+                 C.OriginalWhitespaceRange.getBegin() &&
+             "Generating two replacements for the same location");
+    }
     if (C.CreateReplacement) {
       std::string ReplacementText = C.PreviousLinePostfix;
       if (C.ContinuesPPDirective)
diff --git a/lib/Frontend/ASTConsumers.cpp b/lib/Frontend/ASTConsumers.cpp
index f53c614..52776b6 100644
--- a/lib/Frontend/ASTConsumers.cpp
+++ b/lib/Frontend/ASTConsumers.cpp
@@ -21,7 +21,6 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
-#include "llvm/IR/Module.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/raw_ostream.h"
diff --git a/lib/Frontend/ASTUnit.cpp b/lib/Frontend/ASTUnit.cpp
index a3998fa..bfb1efe 100644
--- a/lib/Frontend/ASTUnit.cpp
+++ b/lib/Frontend/ASTUnit.cpp
@@ -120,11 +120,10 @@
 static void cleanupOnDiskMapAtExit() {
   // Use the mutex because there can be an alive thread destroying an ASTUnit.
   llvm::MutexGuard Guard(getOnDiskMutex());
-  OnDiskDataMap &M = getOnDiskDataMap();
-  for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
+  for (const auto &I : getOnDiskDataMap()) {
     // We don't worry about freeing the memory associated with OnDiskDataMap.
     // All we care about is erasing stale files.
-    I->second->Cleanup();
+    I.second->Cleanup();
   }
 }
 
@@ -151,7 +150,7 @@
   OnDiskDataMap::iterator I = M.find(AU);
   if (I != M.end()) {
     I->second->Cleanup();
-    M.erase(AU);
+    M.erase(I);
   }
 }
 
@@ -164,8 +163,8 @@
 }
 
 void OnDiskData::CleanTemporaryFiles() {
-  for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
-    llvm::sys::fs::remove(TemporaryFiles[I]);
+  for (StringRef File : TemporaryFiles)
+    llvm::sys::fs::remove(File);
   TemporaryFiles.clear();
 }
 
@@ -354,26 +353,24 @@
   
   // Translate global code completions into cached completions.
   llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
-  
-  for (unsigned I = 0, N = Results.size(); I != N; ++I) {
-    switch (Results[I].Kind) {
+
+  for (Result &R : Results) {
+    switch (R.Kind) {
     case Result::RK_Declaration: {
       bool IsNestedNameSpecifier = false;
       CachedCodeCompletionResult CachedResult;
-      CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
-                                                    *CachedCompletionAllocator,
-                                                    CCTUInfo,
-                                          IncludeBriefCommentsInCodeCompletion);
-      CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
-                                                        Ctx->getLangOpts(),
-                                                        IsNestedNameSpecifier);
-      CachedResult.Priority = Results[I].Priority;
-      CachedResult.Kind = Results[I].CursorKind;
-      CachedResult.Availability = Results[I].Availability;
+      CachedResult.Completion = R.CreateCodeCompletionString(
+          *TheSema, *CachedCompletionAllocator, CCTUInfo,
+          IncludeBriefCommentsInCodeCompletion);
+      CachedResult.ShowInContexts = getDeclShowContexts(
+          R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
+      CachedResult.Priority = R.Priority;
+      CachedResult.Kind = R.CursorKind;
+      CachedResult.Availability = R.Availability;
 
       // Keep track of the type of this completion in an ASTContext-agnostic 
       // way.
-      QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
+      QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
       if (UsageType.isNull()) {
         CachedResult.TypeClass = STC_Void;
         CachedResult.Type = 0;
@@ -398,8 +395,8 @@
       CachedCompletionResults.push_back(CachedResult);
       
       /// Handle nested-name-specifiers in C++.
-      if (TheSema->Context.getLangOpts().CPlusPlus && 
-          IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
+      if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
+          !R.StartsNestedNameSpecifier) {
         // The contexts in which a nested-name-specifier can appear in C++.
         uint64_t NNSContexts
           = (1LL << CodeCompletionContext::CCC_TopLevel)
@@ -415,8 +412,8 @@
           | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
           | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
 
-        if (isa<NamespaceDecl>(Results[I].Declaration) ||
-            isa<NamespaceAliasDecl>(Results[I].Declaration))
+        if (isa<NamespaceDecl>(R.Declaration) ||
+            isa<NamespaceAliasDecl>(R.Declaration))
           NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
 
         if (unsigned RemainingContexts 
@@ -424,12 +421,10 @@
           // If there any contexts where this completion can be a 
           // nested-name-specifier but isn't already an option, create a 
           // nested-name-specifier completion.
-          Results[I].StartsNestedNameSpecifier = true;
-          CachedResult.Completion 
-            = Results[I].CreateCodeCompletionString(*TheSema,
-                                                    *CachedCompletionAllocator,
-                                                    CCTUInfo,
-                                        IncludeBriefCommentsInCodeCompletion);
+          R.StartsNestedNameSpecifier = true;
+          CachedResult.Completion = R.CreateCodeCompletionString(
+              *TheSema, *CachedCompletionAllocator, CCTUInfo,
+              IncludeBriefCommentsInCodeCompletion);
           CachedResult.ShowInContexts = RemainingContexts;
           CachedResult.Priority = CCP_NestedNameSpecifier;
           CachedResult.TypeClass = STC_Void;
@@ -448,11 +443,9 @@
       
     case Result::RK_Macro: {
       CachedCodeCompletionResult CachedResult;
-      CachedResult.Completion 
-        = Results[I].CreateCodeCompletionString(*TheSema,
-                                                *CachedCompletionAllocator,
-                                                CCTUInfo,
-                                          IncludeBriefCommentsInCodeCompletion);
+      CachedResult.Completion = R.CreateCodeCompletionString(
+          *TheSema, *CachedCompletionAllocator, CCTUInfo,
+          IncludeBriefCommentsInCodeCompletion);
       CachedResult.ShowInContexts
         = (1LL << CodeCompletionContext::CCC_TopLevel)
         | (1LL << CodeCompletionContext::CCC_ObjCInterface)
@@ -466,10 +459,10 @@
         | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
         | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
         | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
-      
-      CachedResult.Priority = Results[I].Priority;
-      CachedResult.Kind = Results[I].CursorKind;
-      CachedResult.Availability = Results[I].Availability;
+
+      CachedResult.Priority = R.Priority;
+      CachedResult.Kind = R.CursorKind;
+      CachedResult.Availability = R.Availability;
       CachedResult.TypeClass = STC_Void;
       CachedResult.Type = 0;
       CachedCompletionResults.push_back(CachedResult);
@@ -689,8 +682,8 @@
 
   PreprocessorOptions *PPOpts = new PreprocessorOptions();
 
-  for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
-    PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
+  for (const auto &RemappedFile : RemappedFiles)
+    PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
 
   // Gather Info for preprocessor construction later on.
 
@@ -853,8 +846,8 @@
   }
 
   bool HandleTopLevelDecl(DeclGroupRef D) override {
-    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
-      handleTopLevelDecl(*it);
+    for (Decl *TopLevelDecl : D)
+      handleTopLevelDecl(TopLevelDecl);
     return true;
   }
 
@@ -862,8 +855,8 @@
   void HandleInterestingDecl(DeclGroupRef) override {}
 
   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
-    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
-      handleTopLevelDecl(*it);
+    for (Decl *TopLevelDecl : D)
+      handleTopLevelDecl(TopLevelDecl);
   }
 
   ASTMutationListener *GetASTMutationListener() override {
@@ -931,9 +924,8 @@
     Hash = 0;
   }
 
-  bool HandleTopLevelDecl(DeclGroupRef D) override {
-    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
-      Decl *D = *it;
+  bool HandleTopLevelDecl(DeclGroupRef DG) override {
+    for (Decl *D : DG) {
       // FIXME: Currently ObjC method declarations are incorrectly being
       // reported as top-level declarations, even though their DeclContext
       // is the containing ObjC @interface/@implementation.  This is a
@@ -953,8 +945,7 @@
       // parsing into declaration IDs in the precompiled
       // preamble. This will allow us to deserialize those top-level
       // declarations when requested.
-      for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
-        Decl *D = TopLevelDecls[I];
+      for (Decl *D : TopLevelDecls) {
         // Invalid top-level decls may not have been serialized.
         if (D->isInvalidDecl())
           continue;
@@ -1009,10 +1000,10 @@
   // been careful to make sure that the source manager's state
   // before and after are identical, so that we can reuse the source
   // location itself.
-  for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
-    if (StoredDiagnostics[I].getLocation().isValid()) {
-      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
-      StoredDiagnostics[I].setLocation(Loc);
+  for (StoredDiagnostic &SD : StoredDiagnostics) {
+    if (SD.getLocation().isValid()) {
+      FullSourceLoc Loc(SD.getLocation(), SM);
+      SD.setLocation(Loc);
     }
   }
 }
@@ -1300,14 +1291,10 @@
   if (OutDiag.Filename.empty())
     return OutDiag;
   OutDiag.LocOffset = SM.getFileOffset(FileLoc);
-  for (StoredDiagnostic::range_iterator
-         I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
-    OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
-  }
-  for (StoredDiagnostic::fixit_iterator I = InDiag.fixit_begin(),
-                                        E = InDiag.fixit_end();
-       I != E; ++I)
-    OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, *I));
+  for (const CharSourceRange &Range : InDiag.getRanges())
+    OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
+  for (const FixItHint &FixIt : InDiag.getFixIts())
+    OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
 
   return OutDiag;
 }
@@ -1634,11 +1621,10 @@
   std::vector<Decl *> Resolved;
   Resolved.reserve(TopLevelDeclsInPreamble.size());
   ExternalASTSource &Source = *getASTContext().getExternalSource();
-  for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
+  for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
     // Resolve the declaration ID to an actual declaration, possibly
     // deserializing the declaration in the process.
-    Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
-    if (D)
+    if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
       Resolved.push_back(D);
   }
   TopLevelDeclsInPreamble.clear();
@@ -1943,9 +1929,9 @@
   }
 
   // Override any files that need remapping
-  for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
-    CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
-                                              RemappedFiles[I].second);
+  for (const auto &RemappedFile : RemappedFiles) {
+    CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
+                                              RemappedFile.second);
   }
   PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
   PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
@@ -2015,9 +2001,9 @@
     delete RB.second;
 
   Invocation->getPreprocessorOpts().clearRemappedFiles();
-  for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
-    Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
-                                                      RemappedFiles[I].second);
+  for (const auto &RemappedFile : RemappedFiles) {
+    Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
+                                                      RemappedFile.second);
   }
 
   // If we have a preamble file lying around, or if we might try to
@@ -2375,10 +2361,9 @@
   // Remap files.
   PreprocessorOpts.clearRemappedFiles();
   PreprocessorOpts.RetainRemappedFileBuffers = true;
-  for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
-    PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
-                                     RemappedFiles[I].second);
-    OwnedBuffers.push_back(RemappedFiles[I].second);
+  for (const auto &RemappedFile : RemappedFiles) {
+    PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
+    OwnedBuffers.push_back(RemappedFile.second);
   }
 
   // Use the code completion consumer we were given, but adding any cached
@@ -2509,9 +2494,8 @@
 
   SmallVector<StoredDiagnostic, 4> Result;
   Result.reserve(Diags.size());
-  for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
+  for (const StandaloneDiagnostic &SD : Diags) {
     // Rebuild the StoredDiagnostic.
-    const StandaloneDiagnostic &SD = Diags[I];
     if (SD.Filename.empty())
       continue;
     const FileEntry *FE = FileMgr.getFile(SD.Filename);
@@ -2526,23 +2510,20 @@
 
     SmallVector<CharSourceRange, 4> Ranges;
     Ranges.reserve(SD.Ranges.size());
-    for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
-           I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
-      SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
-      SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
+    for (const auto &Range : SD.Ranges) {
+      SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
+      SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
       Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
     }
 
     SmallVector<FixItHint, 2> FixIts;
     FixIts.reserve(SD.FixIts.size());
-    for (std::vector<StandaloneFixIt>::const_iterator
-           I = SD.FixIts.begin(), E = SD.FixIts.end();
-         I != E; ++I) {
+    for (const StandaloneFixIt &FixIt : SD.FixIts) {
       FixIts.push_back(FixItHint());
       FixItHint &FH = FixIts.back();
-      FH.CodeToInsert = I->CodeToInsert;
-      SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
-      SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
+      FH.CodeToInsert = FixIt.CodeToInsert;
+      SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
+      SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
       FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
     }
 
@@ -2736,7 +2717,7 @@
   return SourceMgr->getLocForStartOfFile(FID);
 }
 
-std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
+llvm::iterator_range<PreprocessingRecord::iterator>
 ASTUnit::getLocalPreprocessingEntities() const {
   if (isMainFileAST()) {
     serialization::ModuleFile &
@@ -2745,20 +2726,18 @@
   }
 
   if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
-    return std::make_pair(PPRec->local_begin(), PPRec->local_end());
+    return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
 
-  return std::make_pair(PreprocessingRecord::iterator(),
-                        PreprocessingRecord::iterator());
+  return llvm::make_range(PreprocessingRecord::iterator(),
+                          PreprocessingRecord::iterator());
 }
 
 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
   if (isMainFileAST()) {
     serialization::ModuleFile &
       Mod = Reader->getModuleManager().getPrimaryModule();
-    ASTReader::ModuleDeclIterator MDI, MDE;
-    std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
-    for (; MDI != MDE; ++MDI) {
-      if (!Fn(context, *MDI))
+    for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
+      if (!Fn(context, D))
         return false;
     }
 
@@ -2821,11 +2800,8 @@
   if (empty())
     return;
 
-  for (std::vector<char>::const_iterator
-         I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
-    if (*I == '\n')
-      ++NumLines;
-  }
+  NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
+
   if (Buffer.back() != '\n')
     ++NumLines;
 }
diff --git a/lib/Frontend/CodeGenOptions.cpp b/lib/Frontend/CodeGenOptions.cpp
index 4fa28b4..75ee47f 100644
--- a/lib/Frontend/CodeGenOptions.cpp
+++ b/lib/Frontend/CodeGenOptions.cpp
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include <string.h>
 #include "clang/Frontend/CodeGenOptions.h"
+#include <string.h>
 
 namespace clang {
 
diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp
index b059965..07812bd 100644
--- a/lib/Frontend/CompilerInstance.cpp
+++ b/lib/Frontend/CompilerInstance.cpp
@@ -329,14 +329,7 @@
 
   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
 
-  // Set up the module path, including the hash for the
-  // module-creation options.
-  SmallString<256> SpecificModuleCache(
-                           getHeaderSearchOpts().ModuleCachePath);
-  if (!getHeaderSearchOpts().DisableModuleHash)
-    llvm::sys::path::append(SpecificModuleCache,
-                            getInvocation().getModuleHash());
-  PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
+  PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
 
   // Handle generating dependencies, if requested.
   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
@@ -373,6 +366,17 @@
   }
 }
 
+std::string CompilerInstance::getSpecificModuleCachePath() {
+  // Set up the module path, including the hash for the
+  // module-creation options.
+  SmallString<256> SpecificModuleCache(
+                           getHeaderSearchOpts().ModuleCachePath);
+  if (!getHeaderSearchOpts().DisableModuleHash)
+    llvm::sys::path::append(SpecificModuleCache,
+                            getInvocation().getModuleHash());
+  return SpecificModuleCache.str();
+}
+
 // ASTContext
 
 void CompilerInstance::createASTContext() {
@@ -388,32 +392,30 @@
 void CompilerInstance::createPCHExternalASTSource(
     StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
     void *DeserializationListener, bool OwnDeserializationListener) {
-  IntrusiveRefCntPtr<ExternalASTSource> Source;
   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
-  Source = createPCHExternalASTSource(
+  ModuleManager = createPCHExternalASTSource(
       Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
       AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
       DeserializationListener, OwnDeserializationListener, Preamble,
       getFrontendOpts().UseGlobalModuleIndex);
-  ModuleManager = static_cast<ASTReader*>(Source.get());
-  getASTContext().setExternalSource(Source);
 }
 
-ExternalASTSource *CompilerInstance::createPCHExternalASTSource(
+IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
     StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
     bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
     void *DeserializationListener, bool OwnDeserializationListener,
     bool Preamble, bool UseGlobalModuleIndex) {
   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
 
-  std::unique_ptr<ASTReader> Reader;
-  Reader.reset(new ASTReader(PP, Context,
-                             Sysroot.empty() ? "" : Sysroot.c_str(),
-                             DisablePCHValidation,
-                             AllowPCHWithCompilerErrors,
-                             /*AllowConfigurationMismatch*/false,
-                             HSOpts.ModulesValidateSystemHeaders,
-                             UseGlobalModuleIndex));
+  IntrusiveRefCntPtr<ASTReader> Reader(
+      new ASTReader(PP, Context, Sysroot.empty() ? "" : Sysroot.c_str(),
+                    DisablePCHValidation, AllowPCHWithCompilerErrors,
+                    /*AllowConfigurationMismatch*/ false,
+                    HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
+
+  // We need the external source to be set up before we read the AST, because
+  // eagerly-deserialized declarations may use it.
+  Context.setExternalSource(Reader.get());
 
   Reader->setDeserializationListener(
       static_cast<ASTDeserializationListener *>(DeserializationListener),
@@ -427,7 +429,7 @@
     // Set the predefines buffer as suggested by the PCH reader. Typically, the
     // predefines buffer will be empty.
     PP.setPredefines(Reader->getSuggestedPredefines());
-    return Reader.release();
+    return Reader;
 
   case ASTReader::Failure:
     // Unrecoverable failure: don't even try to process the input file.
@@ -442,6 +444,7 @@
     break;
   }
 
+  Context.setExternalSource(nullptr);
   return nullptr;
 }
 
@@ -1023,9 +1026,19 @@
     case llvm::LockFileManager::LFS_Shared:
       // Someone else is responsible for building the module. Wait for them to
       // finish.
-      if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
+      switch (Locked.waitForUnlock()) {
+      case llvm::LockFileManager::Res_Success:
+        ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
+        break;
+      case llvm::LockFileManager::Res_OwnerDied:
         continue; // try again to get the lock.
-      ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
+      case llvm::LockFileManager::Res_Timeout:
+        Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
+            << Module->Name;
+        // Clear the lock file so that future invokations can make progress.
+        Locked.unsafeRemoveLockFile();
+        return false;
+      }
       break;
     }
 
@@ -1275,6 +1288,12 @@
     bool needsImportVisitation() const override { return true; }
 
     void visitImport(StringRef FileName) override {
+      if (!CI.ExplicitlyLoadedModuleFiles.insert(FileName).second) {
+        if (ModuleFileStack.size() == 0)
+          TopFileIsModule = true;
+        return;
+      }
+
       ModuleFileStack.push_back(FileName);
       if (ASTReader::readASTFileControlBlock(FileName, CI.getFileManager(),
                                              *this)) {
@@ -1292,7 +1311,9 @@
         TopFileIsModule = true;
 
       auto &ModuleFile = CI.ModuleFileOverrides[ModuleName];
-      if (!ModuleFile.empty() && ModuleFile != ModuleFileStack.back())
+      if (!ModuleFile.empty() &&
+          CI.getFileManager().getFile(ModuleFile) !=
+              CI.getFileManager().getFile(ModuleFileStack.back()))
         CI.getDiagnostics().Report(SourceLocation(),
                                    diag::err_conflicting_module_files)
             << ModuleName << ModuleFile << ModuleFileStack.back();
@@ -1363,6 +1384,12 @@
 
     auto Override = ModuleFileOverrides.find(ModuleName);
     bool Explicit = Override != ModuleFileOverrides.end();
+    if (!Explicit && !getLangOpts().ImplicitModules) {
+      getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
+          << ModuleName;
+      ModuleBuildFailed = true;
+      return ModuleLoadResult();
+    }
 
     std::string ModuleFileName =
         Explicit ? Override->second
@@ -1552,7 +1579,7 @@
 
     // Check whether this module is available.
     clang::Module::Requirement Requirement;
-    clang::Module::HeaderDirective MissingHeader;
+    clang::Module::UnresolvedHeaderDirective MissingHeader;
     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
                              MissingHeader)) {
       if (MissingHeader.FileNameLoc.isValid()) {
@@ -1581,9 +1608,16 @@
                      Module, ImportLoc);
   }
 
+  // Determine whether we're in the #include buffer for a module. The #includes
+  // in that buffer do not qualify as module imports; they're just an
+  // implementation detail of us building the module.
+  bool IsInModuleIncludes = !getLangOpts().CurrentModule.empty() &&
+                            getSourceManager().getFileID(ImportLoc) ==
+                                getSourceManager().getMainFileID();
+
   // If this module import was due to an inclusion directive, create an 
   // implicit import declaration to capture it in the AST.
-  if (IsInclusionDirective && hasASTContext()) {
+  if (IsInclusionDirective && hasASTContext() && !IsInModuleIncludes) {
     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
                                                      ImportLoc, Module,
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index f261c6c..2098dec 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -10,6 +10,7 @@
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
 #include "clang/Driver/Util.h"
@@ -19,8 +20,8 @@
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Serialization/ASTReader.h"
 #include "llvm/ADT/Hashing.h"
-#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
@@ -252,7 +253,7 @@
     for (unsigned i = 0, e = checkers.size(); i != e; ++i)
       Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enable));
   }
-  
+
   // Go through the analyzer configuration options.
   for (arg_iterator it = Args.filtered_begin(OPT_analyzer_config),
        ie = Args.filtered_end(); it != ie; ++it) {
@@ -324,21 +325,38 @@
   return Pattern;
 }
 
+static void parseSanitizerKinds(StringRef FlagName,
+                                const std::vector<std::string> &Sanitizers,
+                                DiagnosticsEngine &Diags, SanitizerSet &S) {
+  for (const auto &Sanitizer : Sanitizers) {
+    SanitizerKind K = llvm::StringSwitch<SanitizerKind>(Sanitizer)
+#define SANITIZER(NAME, ID) .Case(NAME, SanitizerKind::ID)
+#include "clang/Basic/Sanitizers.def"
+                          .Default(SanitizerKind::Unknown);
+    if (K == SanitizerKind::Unknown)
+      Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
+    else
+      S.set(K, true);
+  }
+}
+
 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
                              DiagnosticsEngine &Diags,
                              const TargetOptions &TargetOpts) {
   using namespace options;
   bool Success = true;
 
-  Opts.OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
+  unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
   // TODO: This could be done in Driver
   unsigned MaxOptLevel = 3;
-  if (Opts.OptimizationLevel > MaxOptLevel) {
-    // If the optimization level is not supported, fall back on the default optimization
+  if (OptimizationLevel > MaxOptLevel) {
+    // If the optimization level is not supported, fall back on the default
+    // optimization
     Diags.Report(diag::warn_drv_optimization_value)
         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
-    Opts.OptimizationLevel = MaxOptLevel;
+    OptimizationLevel = MaxOptLevel;
   }
+  Opts.OptimizationLevel = OptimizationLevel;
 
   // We must always run at least the always inlining pass.
   Opts.setInlining(
@@ -417,11 +435,13 @@
   Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
   Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
   Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
-                       Args.hasArg(OPT_cl_finite_math_only)||
+                       Args.hasArg(OPT_cl_finite_math_only) ||
                        Args.hasArg(OPT_cl_fast_relaxed_math));
   Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
-                       Args.hasArg(OPT_cl_finite_math_only)||
+                       Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
+                       Args.hasArg(OPT_cl_finite_math_only) ||
                        Args.hasArg(OPT_cl_fast_relaxed_math));
+  Opts.NoSignedZeros = Args.hasArg(OPT_fno_signed_zeros);
   Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
   Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
   Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
@@ -452,15 +472,19 @@
                                        OPT_fno_function_sections, false);
   Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
                                    OPT_fno_data_sections, false);
+  Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
+                                         OPT_fno_unique_section_names, true);
+
   Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
 
+  Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
+
   Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive);
   Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
   Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
 
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
   Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
-  Opts.SanitizeRecover = !Args.hasArg(OPT_fno_sanitize_recover);
 
   Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
   Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
@@ -504,6 +528,13 @@
     Opts.StackAlignment = StackAlignment;
   }
 
+  if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
+    StringRef Val = A->getValue();
+    unsigned StackProbeSize = Opts.StackProbeSize;
+    Val.getAsInteger(0, StackProbeSize);
+    Opts.StackProbeSize = StackProbeSize;
+  }
+
   if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
     StringRef Name = A->getValue();
     unsigned Method = llvm::StringSwitch<unsigned>(Name)
@@ -589,6 +620,14 @@
   if (NeedLocTracking && Opts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
     Opts.setDebugInfo(CodeGenOptions::LocTrackingOnly);
 
+  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
+
+  // Parse -fsanitize-recover= arguments.
+  // FIXME: Report unrecoverable sanitizers incorrectly specified here.
+  parseSanitizerKinds("-fsanitize-recover=",
+                      Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
+                      Opts.SanitizeRecover);
+
   return Success;
 }
 
@@ -675,9 +714,9 @@
   if (Format == "clang")
     Opts.setFormat(DiagnosticOptions::Clang);
   else if (Format == "msvc")
-    Opts.setFormat(DiagnosticOptions::Msvc);
+    Opts.setFormat(DiagnosticOptions::MSVC);
   else if (Format == "msvc-fallback") {
-    Opts.setFormat(DiagnosticOptions::Msvc);
+    Opts.setFormat(DiagnosticOptions::MSVC);
     Opts.CLFallbackMode = true;
   } else if (Format == "vi")
     Opts.setFormat(DiagnosticOptions::Vi);
@@ -705,6 +744,9 @@
   Opts.ConstexprBacktraceLimit = getLastArgIntValue(
       Args, OPT_fconstexpr_backtrace_limit,
       DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
+  Opts.SpellCheckingLimit = getLastArgIntValue(
+      Args, OPT_fspell_checking_limit,
+      DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
   Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
                                     DiagnosticOptions::DefaultTabStop, Diags);
   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
@@ -848,6 +890,7 @@
   Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
   Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
   Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
+  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
   Opts.ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
 
   Opts.CodeCompleteOpts.IncludeMacros
@@ -974,14 +1017,19 @@
 
 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
                                                  void *MainAddr) {
-  SmallString<128> P(llvm::sys::fs::getMainExecutable(Argv0, MainAddr));
+  std::string ClangExecutable =
+      llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
+  StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
 
-  if (!P.empty()) {
-    llvm::sys::path::remove_filename(P); // Remove /clang from foo/bin/clang
-    llvm::sys::path::remove_filename(P); // Remove /bin   from foo/bin
-
-    // Get foo/lib/clang/<version>/include
-    llvm::sys::path::append(P, "lib", "clang", CLANG_VERSION_STRING);
+  // Compute the path to the resource directory.
+  StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
+  SmallString<128> P(Dir);
+  if (ClangResourceDir != "") {
+    llvm::sys::path::append(P, ClangResourceDir);
+  } else {
+    StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
+    llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
+                            CLANG_VERSION_STRING);
   }
 
   return P.str();
@@ -1002,6 +1050,7 @@
   Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
   // -fmodules implies -fmodule-maps
   Opts.ModuleMaps = Args.hasArg(OPT_fmodule_maps) || Args.hasArg(OPT_fmodules);
+  Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
   Opts.ModuleCachePruneInterval =
       getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
   Opts.ModuleCachePruneAfter =
@@ -1019,9 +1068,6 @@
     StringRef MacroDef = (*it)->getValue();
     Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first);
   }
-  std::vector<std::string> ModuleMapFiles =
-      Args.getAllArgValues(OPT_fmodule_map_file);
-  Opts.ModuleMapFiles.insert(ModuleMapFiles.begin(), ModuleMapFiles.end());
 
   // Add -I..., -F..., and -index-header-map options in order.
   bool IsIndexHeaderMap = false;
@@ -1201,11 +1247,6 @@
   Opts.GNUKeywords = Opts.GNUMode;
   Opts.CXXOperatorNames = Opts.CPlusPlus;
 
-  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
-  // is specified, or -std is set to a conforming mode.
-  // Trigraphs are disabled by default in c++1z onwards.
-  Opts.Trigraphs = !Opts.GNUMode && !Opts.CPlusPlus1z;
-
   Opts.DollarIdents = !Opts.AsmPreprocessor;
 
   // C++14 onwards has sized global deallocation functions.
@@ -1349,6 +1390,12 @@
   if (Args.hasArg(OPT_fno_operator_names))
     Opts.CXXOperatorNames = 0;
 
+  if (Args.hasArg(OPT_fcuda_is_device))
+    Opts.CUDAIsDevice = 1;
+
+  if (Args.hasArg(OPT_fcuda_allow_host_calls_from_host_device))
+    Opts.CUDAAllowHostCallsFromHostDevice = 1;
+
   if (Opts.ObjC1) {
     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
       StringRef value = arg->getValue();
@@ -1427,17 +1474,22 @@
   else if (Args.hasArg(OPT_fwrapv))
     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
 
-  if (Args.hasArg(OPT_trigraphs))
-    Opts.Trigraphs = 1;
+  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
+  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
+  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
+  Opts.MSCompatibilityVersion = parseMSCVersion(Args, Diags);
+
+  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
+  // is specified, or -std is set to a conforming mode.
+  // Trigraphs are disabled by default in c++1z onwards.
+  Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus1z;
+  Opts.Trigraphs =
+      Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
 
   Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
                                    OPT_fno_dollars_in_identifiers,
                                    Opts.DollarIdents);
   Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
-  Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
-  Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
-  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
-  Opts.MSCompatibilityVersion = parseMSCVersion(Args, Diags);
   Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
   Opts.Borland = Args.hasArg(OPT_fborland_extensions);
   Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
@@ -1465,6 +1517,9 @@
     !Args.hasArg(OPT_fno_modules_search_all) &&
     Args.hasArg(OPT_fmodules_search_all);
   Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
+  Opts.ModulesImplicitMaps = Args.hasFlag(OPT_fmodules_implicit_maps,
+                                          OPT_fno_modules_implicit_maps, true);
+  Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
   Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
   Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
   Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false);
@@ -1474,6 +1529,9 @@
   Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
   Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
   Opts.SizedDeallocation |= Args.hasArg(OPT_fsized_deallocation);
+  Opts.SizedDeallocation &= !Args.hasArg(OPT_fno_sized_deallocation);
+  Opts.DefineSizedDeallocation = Opts.SizedDeallocation &&
+      Args.hasArg(OPT_fdefine_sized_deallocation);
   Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
   Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
   Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
@@ -1522,8 +1580,10 @@
   Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name);
   Opts.ImplementationOfModule =
       Args.getLastArgValue(OPT_fmodule_implementation_of);
+  Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
   Opts.NativeHalfType = Opts.NativeHalfType;
   Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns);
+  Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
 
   if (!Opts.CurrentModule.empty() && !Opts.ImplementationOfModule.empty() &&
       Opts.CurrentModule != Opts.ImplementationOfModule) {
@@ -1594,8 +1654,11 @@
   // inlining enabled.
   Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
 
-  Opts.FastMath = Args.hasArg(OPT_ffast_math);
-  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only);
+  Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
+      Args.hasArg(OPT_cl_fast_relaxed_math);
+  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
+      Args.hasArg(OPT_cl_finite_math_only) ||
+      Args.hasArg(OPT_cl_fast_relaxed_math);
 
   Opts.RetainCommentsFromSystemHeaders =
       Args.hasArg(OPT_fretain_comments_from_system_headers);
@@ -1613,22 +1676,12 @@
   }
 
   // Parse -fsanitize= arguments.
-  std::vector<std::string> Sanitizers = Args.getAllArgValues(OPT_fsanitize_EQ);
-  for (const auto &Sanitizer : Sanitizers) {
-    SanitizerKind K = llvm::StringSwitch<SanitizerKind>(Sanitizer)
-#define SANITIZER(NAME, ID) .Case(NAME, SanitizerKind::ID)
-#include "clang/Basic/Sanitizers.def"
-        .Default(SanitizerKind::Unknown);
-    if (K == SanitizerKind::Unknown)
-      Diags.Report(diag::err_drv_invalid_value)
-        << "-fsanitize=" << Sanitizer;
-    else
-      Opts.Sanitize.set(K, true);
-  }
+  parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
+                      Diags, Opts.Sanitize);
   // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
   Opts.SanitizeAddressFieldPadding =
       getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
-  Opts.SanitizerBlacklistFile = Args.getLastArgValue(OPT_fsanitize_blacklist);
+  Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
 }
 
 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
@@ -1773,6 +1826,7 @@
   Opts.ShowMacroComments = Args.hasArg(OPT_CC);
   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
   Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
+  Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
 }
 
 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) {
diff --git a/lib/Frontend/FrontendAction.cpp b/lib/Frontend/FrontendAction.cpp
index c81c81a..75670d9 100644
--- a/lib/Frontend/FrontendAction.cpp
+++ b/lib/Frontend/FrontendAction.cpp
@@ -262,6 +262,7 @@
     FileManager &FileMgr = CI.getFileManager();
     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
+    std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
     if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
       std::error_code EC;
       SmallString<128> DirNative;
@@ -273,7 +274,8 @@
         if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr,
                                            CI.getLangOpts(),
                                            CI.getTargetOpts(),
-                                           CI.getPreprocessorOpts())) {
+                                           CI.getPreprocessorOpts(),
+                                           SpecificModuleCachePath)) {
           PPOpts.ImplicitPCHInclude = Dir->path();
           Found = true;
           break;
@@ -383,6 +385,15 @@
            "doesn't support modules");
   }
 
+  // If we were asked to load any module map files, do so now.
+  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
+    if (auto *File = CI.getFileManager().getFile(Filename))
+      CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
+          File, /*IsSystem*/false);
+    else
+      CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
+  }
+
   // If we were asked to load any module files, do so now.
   for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
     if (!CI.loadModuleFile(ModuleFile))
diff --git a/lib/Frontend/FrontendActions.cpp b/lib/Frontend/FrontendActions.cpp
index 6a2ac60..a55a325 100644
--- a/lib/Frontend/FrontendActions.cpp
+++ b/lib/Frontend/FrontendActions.cpp
@@ -142,17 +142,9 @@
     Includes += "#import \"";
   else
     Includes += "#include \"";
-  // Use an absolute path for the include; there's no reason to think that
-  // a relative path will work (. might not be on our include path) or that
-  // it will find the same file.
-  if (llvm::sys::path::is_absolute(HeaderName)) {
-    Includes += HeaderName;
-  } else {
-    SmallString<256> Header = HeaderName;
-    if (std::error_code Err = llvm::sys::fs::make_absolute(Header))
-      return Err;
-    Includes += Header;
-  }
+
+  Includes += HeaderName;
+
   Includes += "\"\n";
   if (IsExternC && LangOpts.CPlusPlus)
     Includes += "}\n";
@@ -163,7 +155,16 @@
                                         SmallVectorImpl<char> &Includes,
                                         const LangOptions &LangOpts,
                                         bool IsExternC) {
-  return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
+  // Use an absolute path if we don't have a filename as written in the module
+  // map file; this ensures that we will identify the right file independent of
+  // header search paths.
+  if (llvm::sys::path::is_absolute(Header->getName()))
+    return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
+
+  SmallString<256> AbsName(Header->getName());
+  if (std::error_code Err = llvm::sys::fs::make_absolute(AbsName))
+    return Err;
+  return addHeaderInclude(AbsName, Includes, LangOpts, IsExternC);
 }
 
 /// \brief Collect the set of header includes needed to construct the given 
@@ -182,16 +183,20 @@
     return std::error_code();
 
   // Add includes for each of these headers.
-  for (unsigned I = 0, N = Module->NormalHeaders.size(); I != N; ++I) {
-    const FileEntry *Header = Module->NormalHeaders[I];
-    Module->addTopHeader(Header);
-    if (std::error_code Err =
-            addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
+  for (Module::Header &H : Module->Headers[Module::HK_Normal]) {
+    Module->addTopHeader(H.Entry);
+    // Use the path as specified in the module map file. We'll look for this
+    // file relative to the module build directory (the directory containing
+    // the module map file) so this will find the same file that we found
+    // while parsing the module map.
+    if (std::error_code Err = addHeaderInclude(H.NameAsWritten, Includes,
+                                               LangOpts, Module->IsExternC))
       return Err;
   }
   // Note that Module->PrivateHeaders will not be a TopHeader.
 
   if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
+    // FIXME: Track the name as written here.
     Module->addTopHeader(UmbrellaHeader);
     if (Module->Parent) {
       // Include the umbrella header for submodules.
@@ -213,25 +218,30 @@
           .Cases(".h", ".H", ".hh", ".hpp", true)
           .Default(false))
         continue;
-      
+
+      const FileEntry *Header = FileMgr.getFile(Dir->path());
+      // FIXME: This shouldn't happen unless there is a file system race. Is
+      // that worth diagnosing?
+      if (!Header)
+        continue;
+
       // If this header is marked 'unavailable' in this module, don't include 
       // it.
-      if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
-        if (ModMap.isHeaderUnavailableInModule(Header, Module))
-          continue;
-        Module->addTopHeader(Header);
-      }
-      
+      if (ModMap.isHeaderUnavailableInModule(Header, Module))
+        continue;
+
       // Include this header as part of the umbrella directory.
-      if (std::error_code Err = addHeaderInclude(Dir->path(), Includes,
-                                                 LangOpts, Module->IsExternC))
+      // FIXME: Track the name as written through to here.
+      Module->addTopHeader(Header);
+      if (std::error_code Err =
+              addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
         return Err;
     }
 
     if (EC)
       return EC;
   }
-  
+
   // Recurse into submodules.
   for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
                                       SubEnd = Module->submodule_end();
@@ -288,7 +298,7 @@
 
   // Check whether we can build this module at all.
   clang::Module::Requirement Requirement;
-  clang::Module::HeaderDirective MissingHeader;
+  clang::Module::UnresolvedHeaderDirective MissingHeader;
   if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
                            MissingHeader)) {
     if (MissingHeader.FileNameLoc.isValid()) {
@@ -317,6 +327,7 @@
   SmallString<256> HeaderContents;
   std::error_code Err = std::error_code();
   if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
+    // FIXME: Track the file name as written.
     Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
                            Module->IsExternC);
   if (!Err)
@@ -331,6 +342,10 @@
     return false;
   }
 
+  // Inform the preprocessor that includes from within the input buffer should
+  // be resolved relative to the build directory of the module map file.
+  CI.getPreprocessor().setMainFileDir(Module->Directory);
+
   std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
       llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
                                            Module::getModuleInputBufferName());
@@ -486,9 +501,11 @@
     }
 
     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                 StringRef SpecificModuleCachePath,
                                  bool Complain) override {
       Out.indent(2) << "Header search options:\n";
       Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
+      Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
       DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
                    "Use builtin include directories [-nobuiltininc]");
       DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
diff --git a/lib/Frontend/InitHeaderSearch.cpp b/lib/Frontend/InitHeaderSearch.cpp
index 5e89c8c..a518a0a 100644
--- a/lib/Frontend/InitHeaderSearch.cpp
+++ b/lib/Frontend/InitHeaderSearch.cpp
@@ -467,7 +467,7 @@
   case llvm::Triple::Win32:
     if (triple.getEnvironment() == llvm::Triple::MSVC ||
         triple.getEnvironment() == llvm::Triple::Itanium ||
-        triple.getObjectFormat() == llvm::Triple::MachO)
+        triple.isOSBinFormatMachO())
       return;
     break;
   }
diff --git a/lib/Frontend/InitPreprocessor.cpp b/lib/Frontend/InitPreprocessor.cpp
index f671a2f..d9ae3ba 100644
--- a/lib/Frontend/InitPreprocessor.cpp
+++ b/lib/Frontend/InitPreprocessor.cpp
@@ -133,6 +133,7 @@
                      "4.94065645841246544176568792868221e-324",
                      "6.47517511943802511092443895822764655e-4966");
   int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
+  int DecimalDigits = PickFP(Sem, 9, 17, 21, 33, 36);
   Epsilon = PickFP(Sem, "1.19209290e-7", "2.2204460492503131e-16",
                    "1.08420217248550443401e-19",
                    "4.94065645841246544176568792868221e-324",
@@ -159,6 +160,7 @@
   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
+  Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
   Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
   Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
   Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
@@ -705,6 +707,10 @@
   Builder.defineMacro("__POINTER_WIDTH__",
                       Twine((int)TI.getPointerWidth(0)));
 
+  // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc.
+  Builder.defineMacro("__BIGGEST_ALIGNMENT__",
+                      Twine(TI.getSuitableAlign() / TI.getCharWidth()) );
+
   if (!LangOpts.CharIsSigned)
     Builder.defineMacro("__CHAR_UNSIGNED__");
 
@@ -831,8 +837,7 @@
   // Macros to control C99 numerics and <float.h>
   Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
   Builder.defineMacro("__FLT_RADIX__", "2");
-  int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
-  Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
+  Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__");
 
   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
     Builder.defineMacro("__SSP__");
@@ -870,6 +875,13 @@
     Builder.defineMacro("_OPENMP", "201307");
   }
 
+  // CUDA device path compilaton
+  if (LangOpts.CUDAIsDevice) {
+    // The CUDA_ARCH value is set for the GPU target specified in the NVPTX
+    // backend's target defines.
+    Builder.defineMacro("__CUDA_ARCH__");
+  }
+
   // Get other target #defines.
   TI.getTargetDefines(LangOpts, Builder);
 }
diff --git a/lib/Frontend/ModuleDependencyCollector.cpp b/lib/Frontend/ModuleDependencyCollector.cpp
index 882bf8e..62865e9 100644
--- a/lib/Frontend/ModuleDependencyCollector.cpp
+++ b/lib/Frontend/ModuleDependencyCollector.cpp
@@ -13,8 +13,8 @@
 
 #include "clang/Frontend/Utils.h"
 #include "clang/Serialization/ASTReader.h"
-#include "llvm/ADT/iterator_range.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
@@ -57,40 +57,17 @@
   VFSWriter.write(OS);
 }
 
-/// Remove traversal (ie, . or ..) from the given absolute path.
-static void removePathTraversal(SmallVectorImpl<char> &Path) {
-  using namespace llvm::sys;
-  SmallVector<StringRef, 16> ComponentStack;
-  StringRef P(Path.data(), Path.size());
-
-  // Skip the root path, then look for traversal in the components.
-  StringRef Rel = path::relative_path(P);
-  for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) {
-    if (C == ".")
-      continue;
-    if (C == "..") {
-      assert(ComponentStack.size() && "Path traverses out of parent");
-      ComponentStack.pop_back();
-    } else
-      ComponentStack.push_back(C);
-  }
-
-  // The stack is now the path without any directory traversal.
-  SmallString<256> Buffer = path::root_path(P);
-  for (StringRef C : ComponentStack)
-    path::append(Buffer, C);
-
-  // Put the result in Path.
-  Path.swap(Buffer);
-}
-
 std::error_code ModuleDependencyListener::copyToRoot(StringRef Src) {
   using namespace llvm::sys;
 
   // We need an absolute path to append to the root.
   SmallString<256> AbsoluteSrc = Src;
   fs::make_absolute(AbsoluteSrc);
-  removePathTraversal(AbsoluteSrc);
+  // Canonicalize to a native path to avoid mixed separator styles.
+  path::native(AbsoluteSrc);
+  // TODO: We probably need to handle .. as well as . in order to have valid
+  // input to the YAMLVFSWriter.
+  FileManager::removeDotPaths(AbsoluteSrc);
 
   // Build the destination path.
   SmallString<256> Dest = Collector.getDest();
diff --git a/lib/Frontend/MultiplexConsumer.cpp b/lib/Frontend/MultiplexConsumer.cpp
index 0198828..3c4fed1 100644
--- a/lib/Frontend/MultiplexConsumer.cpp
+++ b/lib/Frontend/MultiplexConsumer.cpp
@@ -292,10 +292,9 @@
     Consumer->CompleteTentativeDefinition(D);
 }
 
-void MultiplexConsumer::HandleVTable(
-    CXXRecordDecl *RD, bool DefinitionRequired) {
+void MultiplexConsumer::HandleVTable(CXXRecordDecl *RD) {
   for (auto &Consumer : Consumers)
-    Consumer->HandleVTable(RD, DefinitionRequired);
+    Consumer->HandleVTable(RD);
 }
 
 ASTMutationListener *MultiplexConsumer::GetASTMutationListener() {
diff --git a/lib/Frontend/PrintPreprocessedOutput.cpp b/lib/Frontend/PrintPreprocessedOutput.cpp
index 7c1d9a5..6507f8e 100644
--- a/lib/Frontend/PrintPreprocessedOutput.cpp
+++ b/lib/Frontend/PrintPreprocessedOutput.cpp
@@ -94,14 +94,14 @@
   bool Initialized;
   bool DisableLineMarkers;
   bool DumpDefines;
-  bool UseLineDirective;
+  bool UseLineDirectives;
   bool IsFirstFileEntered;
 public:
-  PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
-                           bool lineMarkers, bool defines)
-     : PP(pp), SM(PP.getSourceManager()),
-       ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
-       DumpDefines(defines) {
+  PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
+                           bool defines, bool UseLineDirectives)
+      : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
+        DisableLineMarkers(lineMarkers), DumpDefines(defines),
+        UseLineDirectives(UseLineDirectives) {
     CurLine = 0;
     CurFilename += "<uninit>";
     EmittedTokensOnThisLine = false;
@@ -109,9 +109,6 @@
     FileType = SrcMgr::C_User;
     Initialized = false;
     IsFirstFileEntered = false;
-
-    // If we're in microsoft mode, use normal #line instead of line markers.
-    UseLineDirective = PP.getLangOpts().MicrosoftExt;
   }
 
   void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
@@ -183,7 +180,7 @@
   startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
 
   // Emit #line directives or GNU line markers depending on what mode we're in.
-  if (UseLineDirective) {
+  if (UseLineDirectives) {
     OS << "#line" << ' ' << LineNo << ' ' << '"';
     OS.write_escaped(CurFilename);
     OS << '"';
@@ -719,9 +716,8 @@
   // to -C or -CC.
   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
 
-  PrintPPOutputPPCallbacks *Callbacks =
-      new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
-                                   Opts.ShowMacros);
+  PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
+      PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros, Opts.UseLineDirectives);
   PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
   PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
   PP.AddPragmaHandler("clang",
diff --git a/lib/Frontend/Rewrite/InclusionRewriter.cpp b/lib/Frontend/Rewrite/InclusionRewriter.cpp
index 1400557..865bb29 100644
--- a/lib/Frontend/Rewrite/InclusionRewriter.cpp
+++ b/lib/Frontend/Rewrite/InclusionRewriter.cpp
@@ -43,14 +43,15 @@
   StringRef MainEOL; ///< The line ending marker to use.
   const llvm::MemoryBuffer *PredefinesBuffer; ///< The preprocessor predefines.
   bool ShowLineMarkers; ///< Show #line markers.
-  bool UseLineDirective; ///< Use of line directives or line markers.
+  bool UseLineDirectives; ///< Use of line directives or line markers.
   typedef std::map<unsigned, FileChange> FileChangeMap;
   FileChangeMap FileChanges; ///< Tracks which files were included where.
   /// Used transitively for building up the FileChanges mapping over the
   /// various \c PPCallbacks callbacks.
   FileChangeMap::iterator LastInsertedFileChange;
 public:
-  InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers);
+  InclusionRewriter(Preprocessor &PP, raw_ostream &OS, bool ShowLineMarkers,
+                    bool UseLineDirectives);
   bool Process(FileID FileId, SrcMgr::CharacteristicKind FileType);
   void setPredefinesBuffer(const llvm::MemoryBuffer *Buf) {
     PredefinesBuffer = Buf;
@@ -89,13 +90,12 @@
 
 /// Initializes an InclusionRewriter with a \p PP source and \p OS destination.
 InclusionRewriter::InclusionRewriter(Preprocessor &PP, raw_ostream &OS,
-                                     bool ShowLineMarkers)
+                                     bool ShowLineMarkers,
+                                     bool UseLineDirectives)
     : PP(PP), SM(PP.getSourceManager()), OS(OS), MainEOL("\n"),
       PredefinesBuffer(nullptr), ShowLineMarkers(ShowLineMarkers),
-      LastInsertedFileChange(FileChanges.end()) {
-  // If we're in microsoft mode, use normal #line instead of line markers.
-  UseLineDirective = PP.getLangOpts().MicrosoftExt;
-}
+      UseLineDirectives(UseLineDirectives),
+      LastInsertedFileChange(FileChanges.end()) {}
 
 /// Write appropriate line information as either #line directives or GNU line
 /// markers depending on what mode we're in, including the \p Filename and
@@ -106,7 +106,7 @@
                                       StringRef Extra) {
   if (!ShowLineMarkers)
     return;
-  if (UseLineDirective) {
+  if (UseLineDirectives) {
     OS << "#line" << ' ' << Line << ' ' << '"';
     OS.write_escaped(Filename);
     OS << '"';
@@ -561,8 +561,8 @@
 void clang::RewriteIncludesInInput(Preprocessor &PP, raw_ostream *OS,
                                    const PreprocessorOutputOptions &Opts) {
   SourceManager &SM = PP.getSourceManager();
-  InclusionRewriter *Rewrite = new InclusionRewriter(PP, *OS,
-                                                     Opts.ShowLineMarkers);
+  InclusionRewriter *Rewrite = new InclusionRewriter(
+      PP, *OS, Opts.ShowLineMarkers, Opts.UseLineDirectives);
   Rewrite->detectMainFileEOL();
 
   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Rewrite));
diff --git a/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/lib/Frontend/Rewrite/RewriteModernObjC.cpp
index ffac51e..47f8189 100644
--- a/lib/Frontend/Rewrite/RewriteModernObjC.cpp
+++ b/lib/Frontend/Rewrite/RewriteModernObjC.cpp
@@ -4563,16 +4563,12 @@
         GetBlockDeclRefExprs(*CI);
     }
   // Handle specific things.
-  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
-    if (DRE->refersToEnclosingLocal()) {
+  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
+    if (DRE->refersToEnclosingVariableOrCapture() ||
+        HasLocalVariableExternalStorage(DRE->getDecl()))
       // FIXME: Handle enums.
-      if (!isa<FunctionDecl>(DRE->getDecl()))
-        BlockDeclRefs.push_back(DRE);
-      if (HasLocalVariableExternalStorage(DRE->getDecl()))
-        BlockDeclRefs.push_back(DRE);
-    }
-  }
-  
+      BlockDeclRefs.push_back(DRE);
+
   return;
 }
 
@@ -4595,11 +4591,11 @@
     }
   // Handle specific things.
   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
-    if (DRE->refersToEnclosingLocal()) {
-      if (!isa<FunctionDecl>(DRE->getDecl()) &&
-          !InnerContexts.count(DRE->getDecl()->getDeclContext()))
+    if (DRE->refersToEnclosingVariableOrCapture() ||
+        HasLocalVariableExternalStorage(DRE->getDecl())) {
+      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
         InnerBlockDeclRefs.push_back(DRE);
-      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
+      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
         if (Var->isFunctionOrMethodVarDecl())
           ImportedLocalExternalDecls.insert(Var);
     }
@@ -4776,7 +4772,8 @@
   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 
   // for each DeclRefExp where BYREFVAR is name of the variable.
   ValueDecl *VD = DeclRefExp->getDecl();
-  bool isArrow = DeclRefExp->refersToEnclosingLocal();
+  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
+                 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
 
   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
                                     SourceLocation(),
diff --git a/lib/Frontend/Rewrite/RewriteObjC.cpp b/lib/Frontend/Rewrite/RewriteObjC.cpp
index 5fb2374..5196810 100644
--- a/lib/Frontend/Rewrite/RewriteObjC.cpp
+++ b/lib/Frontend/Rewrite/RewriteObjC.cpp
@@ -3671,16 +3671,12 @@
         GetBlockDeclRefExprs(*CI);
     }
   // Handle specific things.
-  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
-    if (DRE->refersToEnclosingLocal()) {
+  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
+    if (DRE->refersToEnclosingVariableOrCapture() ||
+        HasLocalVariableExternalStorage(DRE->getDecl()))
       // FIXME: Handle enums.
-      if (!isa<FunctionDecl>(DRE->getDecl()))
-        BlockDeclRefs.push_back(DRE);
-      if (HasLocalVariableExternalStorage(DRE->getDecl()))
-        BlockDeclRefs.push_back(DRE);
-    }
-  }
-  
+      BlockDeclRefs.push_back(DRE);
+
   return;
 }
 
@@ -3703,11 +3699,11 @@
     }
   // Handle specific things.
   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
-    if (DRE->refersToEnclosingLocal()) {
-      if (!isa<FunctionDecl>(DRE->getDecl()) &&
-          !InnerContexts.count(DRE->getDecl()->getDeclContext()))
+    if (DRE->refersToEnclosingVariableOrCapture() ||
+        HasLocalVariableExternalStorage(DRE->getDecl())) {
+      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
         InnerBlockDeclRefs.push_back(DRE);
-      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
+      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
         if (Var->isFunctionOrMethodVarDecl())
           ImportedLocalExternalDecls.insert(Var);
     }
@@ -3865,7 +3861,8 @@
   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 
   // for each DeclRefExp where BYREFVAR is name of the variable.
   ValueDecl *VD = DeclRefExp->getDecl();
-  bool isArrow = DeclRefExp->refersToEnclosingLocal();
+  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
+                 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
 
   FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
                                     SourceLocation(),
diff --git a/lib/Frontend/SerializedDiagnosticPrinter.cpp b/lib/Frontend/SerializedDiagnosticPrinter.cpp
index 2ab8fbf..f701f72 100644
--- a/lib/Frontend/SerializedDiagnosticPrinter.cpp
+++ b/lib/Frontend/SerializedDiagnosticPrinter.cpp
@@ -8,8 +8,6 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
-#include "clang/Frontend/SerializedDiagnosticReader.h"
-#include "clang/Frontend/SerializedDiagnostics.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -17,6 +15,8 @@
 #include "clang/Basic/Version.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Frontend/SerializedDiagnosticReader.h"
+#include "clang/Frontend/SerializedDiagnostics.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseSet.h"
diff --git a/lib/Frontend/SerializedDiagnosticReader.cpp b/lib/Frontend/SerializedDiagnosticReader.cpp
index c8faef3..0ebbd22 100644
--- a/lib/Frontend/SerializedDiagnosticReader.cpp
+++ b/lib/Frontend/SerializedDiagnosticReader.cpp
@@ -8,8 +8,8 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Frontend/SerializedDiagnosticReader.h"
-#include "clang/Frontend/SerializedDiagnostics.h"
 #include "clang/Basic/FileManager.h"
+#include "clang/Frontend/SerializedDiagnostics.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/MemoryBuffer.h"
 
diff --git a/lib/Frontend/TextDiagnostic.cpp b/lib/Frontend/TextDiagnostic.cpp
index 6e6f3dd..17e41f6 100644
--- a/lib/Frontend/TextDiagnostic.cpp
+++ b/lib/Frontend/TextDiagnostic.cpp
@@ -176,7 +176,7 @@
 ///  of the printable representation of the line to the columns those printable
 ///  characters will appear at (numbering the first column as 0).
 ///
-/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
+/// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
 ///  character) then the array will map that byte to the first column the
 ///  tab appears at and the next value in the map will have been incremented
 ///  more than once.
@@ -293,14 +293,14 @@
 
   /// \brief Map from a byte index to the next byte which starts a column.
   int startOfNextColumn(int N) const {
-    assert(0 <= N && N < static_cast<int>(m_columnToByte.size() - 1));
+    assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
     while (byteToColumn(++N) == -1) {}
     return N;
   }
 
   /// \brief Map from a byte index to the previous byte which starts a column.
   int startOfPreviousColumn(int N) const {
-    assert(0 < N && N < static_cast<int>(m_columnToByte.size()));
+    assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
     while (byteToColumn(--N) == -1) {}
     return N;
   }
@@ -323,9 +323,10 @@
                                           std::string &FixItInsertionLine,
                                           unsigned Columns,
                                           const SourceColumnMap &map) {
-  unsigned MaxColumns = std::max<unsigned>(map.columns(),
-                                           std::max(CaretLine.size(),
-                                                    FixItInsertionLine.size()));
+  unsigned CaretColumns = CaretLine.size();
+  unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
+  unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
+                                 std::max(CaretColumns, FixItColumns));
   // if the number of columns is less than the desired number we're done
   if (MaxColumns <= Columns)
     return;
@@ -487,7 +488,7 @@
   // We checked up front that the line needed truncation
   assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
 
-  // The line needs some trunctiona, and we'd prefer to keep the front
+  // The line needs some truncation, and we'd prefer to keep the front
   //  if possible, so remove the back
   if (BackColumnsRemoved > strlen(back_ellipse))
     SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
@@ -798,14 +799,14 @@
   OS << PLoc.getFilename();
   switch (DiagOpts->getFormat()) {
   case DiagnosticOptions::Clang: OS << ':'  << LineNo; break;
-  case DiagnosticOptions::Msvc:  OS << '('  << LineNo; break;
+  case DiagnosticOptions::MSVC:  OS << '('  << LineNo; break;
   case DiagnosticOptions::Vi:    OS << " +" << LineNo; break;
   }
 
   if (DiagOpts->ShowColumn)
     // Compute the column number.
     if (unsigned ColNo = PLoc.getColumn()) {
-      if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) {
+      if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
         OS << ',';
         // Visual Studio 2010 or earlier expects column number to be off by one
         if (LangOpts.MSCompatibilityVersion &&
@@ -818,7 +819,7 @@
   switch (DiagOpts->getFormat()) {
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:    OS << ':';    break;
-  case DiagnosticOptions::Msvc:  OS << ") : "; break;
+  case DiagnosticOptions::MSVC:  OS << ") : "; break;
   }
 
   if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
@@ -1110,12 +1111,13 @@
   // Copy the line of code into an std::string for ease of manipulation.
   std::string SourceLine(LineStart, LineEnd);
 
-  // Create a line for the caret that is filled with spaces that is the same
-  // length as the line of source code.
-  std::string CaretLine(LineEnd-LineStart, ' ');
-
+  // Build the byte to column map.
   const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
 
+  // Create a line for the caret that is filled with spaces that is the same
+  // number of columns as the line of source code.
+  std::string CaretLine(sourceColMap.columns(), ' ');
+
   // Highlight all of the characters covered by Ranges with ~ characters.
   for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
                                                   E = Ranges.end();
diff --git a/lib/Headers/Intrin.h b/lib/Headers/Intrin.h
index 016c480..727a55e 100644
--- a/lib/Headers/Intrin.h
+++ b/lib/Headers/Intrin.h
@@ -289,6 +289,7 @@
 unsigned __int32 xbegin(void);
 void _xend(void);
 static __inline__
+#define _XCR_XFEATURE_ENABLED_MASK 0
 unsigned __int64 __cdecl _xgetbv(unsigned int);
 void __cdecl _xrstor(void const *, unsigned __int64);
 void __cdecl _xsave(void *, unsigned __int64);
@@ -330,7 +331,6 @@
                                  unsigned char _Shift);
 static __inline__
 void __stosq(unsigned __int64 *, unsigned __int64, size_t);
-unsigned __int64 __umulh(unsigned __int64, unsigned __int64);
 unsigned char __vmx_on(unsigned __int64 *);
 unsigned char __vmx_vmclear(unsigned __int64 *);
 unsigned char __vmx_vmlaunch(void);
@@ -416,10 +416,25 @@
 int __cdecl _setjmpex(jmp_buf);
 #endif
 unsigned __int64 _shlx_u64(unsigned __int64, unsigned int);
-unsigned __int64 shrx_u64(unsigned __int64, unsigned int);
-unsigned __int64 _umul128(unsigned __int64 _Multiplier,
-                          unsigned __int64 _Multiplicand,
-                          unsigned __int64 *_HighProduct);
+unsigned __int64 _shrx_u64(unsigned __int64, unsigned int);
+/*
+ * Multiply two 64-bit integers and obtain a 64-bit result.
+ * The low-half is returned directly and the high half is in an out parameter.
+ */
+static __inline__ unsigned __int64 __attribute__((__always_inline__, __nodebug__))
+_umul128(unsigned __int64 _Multiplier, unsigned __int64 _Multiplicand,
+         unsigned __int64 *_HighProduct) {
+  unsigned __int128 _FullProduct =
+      (unsigned __int128)_Multiplier * (unsigned __int128)_Multiplicand;
+  *_HighProduct = _FullProduct >> 64;
+  return _FullProduct;
+}
+static __inline__ unsigned __int64 __attribute__((__always_inline__, __nodebug__))
+__umulh(unsigned __int64 _Multiplier, unsigned __int64 _Multiplicand) {
+  unsigned __int128 _FullProduct =
+      (unsigned __int128)_Multiplier * (unsigned __int128)_Multiplicand;
+  return _FullProduct >> 64;
+}
 void __cdecl _xrstor64(void const *, unsigned __int64);
 void __cdecl _xsave64(void *, unsigned __int64);
 void __cdecl _xsaveopt64(void *, unsigned __int64);
@@ -766,17 +781,17 @@
 \*----------------------------------------------------------------------------*/
 #if defined(__i386__) || defined(__x86_64__)
 static __inline__ void __attribute__((__always_inline__, __nodebug__))
-__attribute__((deprecated("use other intrinsics or C++11 atomics instead")))
+__attribute__((__deprecated__("use other intrinsics or C++11 atomics instead")))
 _ReadWriteBarrier(void) {
   __asm__ volatile ("" : : : "memory");
 }
 static __inline__ void __attribute__((__always_inline__, __nodebug__))
-__attribute__((deprecated("use other intrinsics or C++11 atomics instead")))
+__attribute__((__deprecated__("use other intrinsics or C++11 atomics instead")))
 _ReadBarrier(void) {
   __asm__ volatile ("" : : : "memory");
 }
 static __inline__ void __attribute__((__always_inline__, __nodebug__))
-__attribute__((deprecated("use other intrinsics or C++11 atomics instead")))
+__attribute__((__deprecated__("use other intrinsics or C++11 atomics instead")))
 _WriteBarrier(void) {
   __asm__ volatile ("" : : : "memory");
 }
@@ -929,14 +944,14 @@
   return (((unsigned __int64)__edx) << 32) | (unsigned __int64)__eax;
 }
 
-static __inline__ unsigned long __attribute__((always_inline, __nodebug__))
+static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
 __readcr3(void) {
   unsigned long __cr3_val;
   __asm__ __volatile__ ("mov %%cr3, %0" : "=q"(__cr3_val) : : "memory");
   return __cr3_val;
 }
 
-static __inline__ void __attribute__((always_inline, __nodebug__))
+static __inline__ void __attribute__((__always_inline__, __nodebug__))
 __writecr3(unsigned int __cr3_val) {
   __asm__ ("mov %0, %%cr3" : : "q"(__cr3_val) : "memory");
 }
diff --git a/lib/Headers/__stddef_max_align_t.h b/lib/Headers/__stddef_max_align_t.h
index a06f412..1e10ca9 100644
--- a/lib/Headers/__stddef_max_align_t.h
+++ b/lib/Headers/__stddef_max_align_t.h
@@ -26,15 +26,18 @@
 #ifndef __CLANG_MAX_ALIGN_T_DEFINED
 #define __CLANG_MAX_ALIGN_T_DEFINED
 
-#ifndef _MSC_VER
+#if defined(_MSC_VER)
+typedef double max_align_t;
+#elif defined(__APPLE__)
+typedef long double max_align_t;
+#else
+// Define 'max_align_t' to match the GCC definition.
 typedef struct {
   long long __clang_max_align_nonce1
       __attribute__((__aligned__(__alignof__(long long))));
   long double __clang_max_align_nonce2
       __attribute__((__aligned__(__alignof__(long double))));
 } max_align_t;
-#else
-typedef double max_align_t;
 #endif
 
 #endif
diff --git a/lib/Headers/altivec.h b/lib/Headers/altivec.h
index eded7b2..b8a8869 100644
--- a/lib/Headers/altivec.h
+++ b/lib/Headers/altivec.h
@@ -2270,7 +2270,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const signed char *__b)
 {
@@ -2289,7 +2289,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const unsigned char *__b)
 {
@@ -2308,7 +2308,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const short *__b)
 {
@@ -2327,7 +2327,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const unsigned short *__b)
 {
@@ -2346,7 +2346,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const int *__b)
 {
@@ -2365,7 +2365,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const unsigned int *__b)
 {
@@ -2384,7 +2384,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsl(int __a, const float *__b)
 {
@@ -2405,7 +2405,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const signed char *__b)
 {
@@ -2424,7 +2424,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const unsigned char *__b)
 {
@@ -2443,7 +2443,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const short *__b)
 {
@@ -2462,7 +2462,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const unsigned short *__b)
 {
@@ -2481,7 +2481,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const int *__b)
 {
@@ -2500,7 +2500,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const unsigned int *__b)
 {
@@ -2519,7 +2519,7 @@
 
 #ifdef __LITTLE_ENDIAN__
 static vector unsigned char __ATTRS_o_ai
-__attribute__((deprecated("use assignment for unaligned little endian \
+__attribute__((__deprecated__("use assignment for unaligned little endian \
 loads/stores")))
 vec_lvsr(int __a, const float *__b)
 {
@@ -4735,7 +4735,7 @@
 // in that the vec_xor can be recognized as a vec_nor (and for P8 and
 // later, possibly a vec_nand).
 
-vector signed char __ATTRS_o_ai
+static vector signed char __ATTRS_o_ai
 vec_perm(vector signed char __a, vector signed char __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4750,7 +4750,7 @@
 #endif
 }
 
-vector unsigned char __ATTRS_o_ai
+static vector unsigned char __ATTRS_o_ai
 vec_perm(vector unsigned char __a,
          vector unsigned char __b,
          vector unsigned char __c)
@@ -4767,7 +4767,7 @@
 #endif
 }
 
-vector bool char __ATTRS_o_ai
+static vector bool char __ATTRS_o_ai
 vec_perm(vector bool char __a, vector bool char __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4782,7 +4782,7 @@
 #endif
 }
 
-vector short __ATTRS_o_ai
+static vector short __ATTRS_o_ai
 vec_perm(vector short __a, vector short __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4797,7 +4797,7 @@
 #endif
 }
 
-vector unsigned short __ATTRS_o_ai
+static vector unsigned short __ATTRS_o_ai
 vec_perm(vector unsigned short __a,
          vector unsigned short __b,
          vector unsigned char __c)
@@ -4814,7 +4814,7 @@
 #endif
 }
 
-vector bool short __ATTRS_o_ai
+static vector bool short __ATTRS_o_ai
 vec_perm(vector bool short __a, vector bool short __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4829,7 +4829,7 @@
 #endif
 }
 
-vector pixel __ATTRS_o_ai
+static vector pixel __ATTRS_o_ai
 vec_perm(vector pixel __a, vector pixel __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4844,7 +4844,7 @@
 #endif
 }
 
-vector int __ATTRS_o_ai
+static vector int __ATTRS_o_ai
 vec_perm(vector int __a, vector int __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4857,7 +4857,7 @@
 #endif
 }
 
-vector unsigned int __ATTRS_o_ai
+static vector unsigned int __ATTRS_o_ai
 vec_perm(vector unsigned int __a, vector unsigned int __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4872,7 +4872,7 @@
 #endif
 }
 
-vector bool int __ATTRS_o_ai
+static vector bool int __ATTRS_o_ai
 vec_perm(vector bool int __a, vector bool int __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4887,7 +4887,7 @@
 #endif
 }
 
-vector float __ATTRS_o_ai
+static vector float __ATTRS_o_ai
 vec_perm(vector float __a, vector float __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4903,7 +4903,7 @@
 }
 
 #ifdef __VSX__
-vector long long __ATTRS_o_ai
+static vector long long __ATTRS_o_ai
 vec_perm(vector long long __a, vector long long __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -4916,7 +4916,7 @@
 #endif
 }
 
-vector unsigned long long __ATTRS_o_ai
+static vector unsigned long long __ATTRS_o_ai
 vec_perm(vector unsigned long long __a, vector unsigned long long __b,
          vector unsigned char __c)
 {
@@ -4932,7 +4932,7 @@
 #endif
 }
 
-vector double __ATTRS_o_ai
+static vector double __ATTRS_o_ai
 vec_perm(vector double __a, vector double __b, vector unsigned char __c)
 {
 #ifdef __LITTLE_ENDIAN__
@@ -8664,11 +8664,11 @@
 #ifdef __LITTLE_ENDIAN__
   vector int __c = (vector signed int)
     vec_perm(__b, __b, (vector unsigned char)
-	     (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
+             (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
   __c = __builtin_altivec_vsum2sws(__a, __c);
   return (vector signed int)
     vec_perm(__c, __c, (vector unsigned char)
-	     (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
+             (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
 #else
   return __builtin_altivec_vsum2sws(__a, __b);
 #endif
@@ -8682,11 +8682,11 @@
 #ifdef __LITTLE_ENDIAN__
   vector int __c = (vector signed int)
     vec_perm(__b, __b, (vector unsigned char)
-	     (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
+             (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
   __c = __builtin_altivec_vsum2sws(__a, __c);
   return (vector signed int)
     vec_perm(__c, __c, (vector unsigned char)
-	     (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
+             (4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11));
 #else
   return __builtin_altivec_vsum2sws(__a, __b);
 #endif
diff --git a/lib/Headers/arm_acle.h b/lib/Headers/arm_acle.h
index 814df2c..6c56f3b 100644
--- a/lib/Headers/arm_acle.h
+++ b/lib/Headers/arm_acle.h
@@ -45,23 +45,23 @@
 /* 8.4 Hints */
 
 #if !defined(_MSC_VER)
-static __inline__ void __attribute__((always_inline, nodebug)) __wfi(void) {
+static __inline__ void __attribute__((__always_inline__, __nodebug__)) __wfi(void) {
   __builtin_arm_wfi();
 }
 
-static __inline__ void __attribute__((always_inline, nodebug)) __wfe(void) {
+static __inline__ void __attribute__((__always_inline__, __nodebug__)) __wfe(void) {
   __builtin_arm_wfe();
 }
 
-static __inline__ void __attribute__((always_inline, nodebug)) __sev(void) {
+static __inline__ void __attribute__((__always_inline__, __nodebug__)) __sev(void) {
   __builtin_arm_sev();
 }
 
-static __inline__ void __attribute__((always_inline, nodebug)) __sevl(void) {
+static __inline__ void __attribute__((__always_inline__, __nodebug__)) __sevl(void) {
   __builtin_arm_sevl();
 }
 
-static __inline__ void __attribute__((always_inline, nodebug)) __yield(void) {
+static __inline__ void __attribute__((__always_inline__, __nodebug__)) __yield(void) {
   __builtin_arm_yield();
 }
 #endif
@@ -71,7 +71,7 @@
 #endif
 
 /* 8.5 Swap */
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __swp(uint32_t x, volatile uint32_t *p) {
   uint32_t v;
   do v = __builtin_arm_ldrex(p); while (__builtin_arm_strex(x, p));
@@ -102,28 +102,28 @@
 #endif
 
 /* 8.7 NOP */
-static __inline__ void __attribute__((always_inline, nodebug)) __nop(void) {
+static __inline__ void __attribute__((__always_inline__, __nodebug__)) __nop(void) {
   __builtin_arm_nop();
 }
 
 /* 9 DATA-PROCESSING INTRINSICS */
 /* 9.2 Miscellaneous data-processing intrinsics */
 /* ROR */
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __ror(uint32_t x, uint32_t y) {
   y %= 32;
   if (y == 0)  return x;
   return (x >> y) | (x << (32 - y));
 }
 
-static __inline__ uint64_t __attribute__((always_inline, nodebug))
+static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
   __rorll(uint64_t x, uint32_t y) {
   y %= 64;
   if (y == 0)  return x;
   return (x >> y) | (x << (64 - y));
 }
 
-static __inline__ unsigned long __attribute__((always_inline, nodebug))
+static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
   __rorl(unsigned long x, uint32_t y) {
 #if __SIZEOF_LONG__ == 4
   return __ror(x, y);
@@ -134,28 +134,28 @@
 
 
 /* CLZ */
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __clz(uint32_t t) {
   return __builtin_clz(t);
 }
 
-static __inline__ unsigned long __attribute__((always_inline, nodebug))
+static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
   __clzl(unsigned long t) {
   return __builtin_clzl(t);
 }
 
-static __inline__ uint64_t __attribute__((always_inline, nodebug))
+static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
   __clzll(uint64_t t) {
   return __builtin_clzll(t);
 }
 
 /* REV */
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __rev(uint32_t t) {
   return __builtin_bswap32(t);
 }
 
-static __inline__ unsigned long __attribute__((always_inline, nodebug))
+static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
   __revl(unsigned long t) {
 #if __SIZEOF_LONG__ == 4
   return __builtin_bswap32(t);
@@ -164,40 +164,40 @@
 #endif
 }
 
-static __inline__ uint64_t __attribute__((always_inline, nodebug))
+static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
   __revll(uint64_t t) {
   return __builtin_bswap64(t);
 }
 
 /* REV16 */
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __rev16(uint32_t t) {
   return __ror(__rev(t), 16);
 }
 
-static __inline__ unsigned long __attribute__((always_inline, nodebug))
+static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
   __rev16l(unsigned long t) {
     return __rorl(__revl(t), sizeof(long) / 2);
 }
 
-static __inline__ uint64_t __attribute__((always_inline, nodebug))
+static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
   __rev16ll(uint64_t t) {
   return __rorll(__revll(t), 32);
 }
 
 /* REVSH */
-static __inline__ int16_t __attribute__((always_inline, nodebug))
+static __inline__ int16_t __attribute__((__always_inline__, __nodebug__))
   __revsh(int16_t t) {
   return __builtin_bswap16(t);
 }
 
 /* RBIT */
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __rbit(uint32_t t) {
   return __builtin_arm_rbit(t);
 }
 
-static __inline__ uint64_t __attribute__((always_inline, nodebug))
+static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
   __rbitll(uint64_t t) {
 #if __ARM_32BIT_STATE
   return (((uint64_t) __builtin_arm_rbit(t)) << 32) |
@@ -207,7 +207,7 @@
 #endif
 }
 
-static __inline__ unsigned long __attribute__((always_inline, nodebug))
+static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
   __rbitl(unsigned long t) {
 #if __SIZEOF_LONG__ == 4
   return __rbit(t);
@@ -230,17 +230,17 @@
 
 /* 9.4.2 Saturating addition and subtraction intrinsics */
 #if __ARM_32BIT_STATE
-static __inline__ int32_t __attribute__((always_inline, nodebug))
+static __inline__ int32_t __attribute__((__always_inline__, __nodebug__))
   __qadd(int32_t t, int32_t v) {
   return __builtin_arm_qadd(t, v);
 }
 
-static __inline__ int32_t __attribute__((always_inline, nodebug))
+static __inline__ int32_t __attribute__((__always_inline__, __nodebug__))
   __qsub(int32_t t, int32_t v) {
   return __builtin_arm_qsub(t, v);
 }
 
-static __inline__ int32_t __attribute__((always_inline, nodebug))
+static __inline__ int32_t __attribute__((__always_inline__, __nodebug__))
 __qdbl(int32_t t) {
   return __builtin_arm_qadd(t, t);
 }
@@ -248,42 +248,42 @@
 
 /* 9.7 CRC32 intrinsics */
 #if __ARM_FEATURE_CRC32
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32b(uint32_t a, uint8_t b) {
   return __builtin_arm_crc32b(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32h(uint32_t a, uint16_t b) {
   return __builtin_arm_crc32h(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32w(uint32_t a, uint32_t b) {
   return __builtin_arm_crc32w(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32d(uint32_t a, uint64_t b) {
   return __builtin_arm_crc32d(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32cb(uint32_t a, uint8_t b) {
   return __builtin_arm_crc32cb(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32ch(uint32_t a, uint16_t b) {
   return __builtin_arm_crc32ch(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32cw(uint32_t a, uint32_t b) {
   return __builtin_arm_crc32cw(a, b);
 }
 
-static __inline__ uint32_t __attribute__((always_inline, nodebug))
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
   __crc32cd(uint32_t a, uint64_t b) {
   return __builtin_arm_crc32cd(a, b);
 }
diff --git a/lib/Headers/avx512bwintrin.h b/lib/Headers/avx512bwintrin.h
index bc4d4ac..acc3da2 100644
--- a/lib/Headers/avx512bwintrin.h
+++ b/lib/Headers/avx512bwintrin.h
@@ -21,13 +21,16 @@
  *
  *===-----------------------------------------------------------------------===
  */
+#ifndef __IMMINTRIN_H
+#error "Never use <avx512bwintrin.h> directly; include <immintrin.h> instead."
+#endif
 
 #ifndef __AVX512BWINTRIN_H
 #define __AVX512BWINTRIN_H
 
 typedef unsigned int __mmask32;
 typedef unsigned long long __mmask64;
-typedef char __v64qi __attribute__ ((vector_size (64)));
+typedef char __v64qi __attribute__ ((__vector_size__ (64)));
 typedef short __v32hi __attribute__ ((__vector_size__ (64)));
 
 
@@ -45,6 +48,18 @@
                                                    __u);
 }
 
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpeq_epu8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 0,
+                                                 (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpeq_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 0,
+                                                 __u);
+}
+
 static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
 _mm512_cmpeq_epi16_mask(__m512i __a, __m512i __b) {
   return (__mmask32)__builtin_ia32_pcmpeqw512_mask((__v32hi)__a, (__v32hi)__b,
@@ -57,4 +72,296 @@
                                                    __u);
 }
 
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpeq_epu16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 0,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpeq_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 0,
+                                                 __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epi8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 5,
+                                                (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epu8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 5,
+                                                 (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 5,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epi16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 5,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epu16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 5,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 5,
+                                                 __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epi8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_pcmpgtb512_mask((__v64qi)__a, (__v64qi)__b,
+                                                   (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_pcmpgtb512_mask((__v64qi)__a, (__v64qi)__b,
+                                                   __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epu8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 6,
+                                                 (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 6,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epi16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_pcmpgtw512_mask((__v32hi)__a, (__v32hi)__b,
+                                                   (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_pcmpgtw512_mask((__v32hi)__a, (__v32hi)__b,
+                                                   __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epu16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 6,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 6,
+                                                 __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epi8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 2,
+                                                (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epu8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 2,
+                                                 (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 2,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epi16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 2,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epu16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 2,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 2,
+                                                 __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epi8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 1,
+                                                (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epu8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 1,
+                                                 (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 1,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epi16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 1,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epu16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 1,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 1,
+                                                 __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epi8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 4,
+                                                (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_cmpb512_mask((__v64qi)__a, (__v64qi)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epu8_mask(__m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 4,
+                                                 (__mmask64)-1);
+}
+
+static __inline__ __mmask64 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  return (__mmask64)__builtin_ia32_ucmpb512_mask((__v64qi)__a, (__v64qi)__b, 4,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epi16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 4,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_cmpw512_mask((__v32hi)__a, (__v32hi)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epu16_mask(__m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 4,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  return (__mmask32)__builtin_ia32_ucmpw512_mask((__v32hi)__a, (__v32hi)__b, 4,
+                                                 __u);
+}
+
+#define _mm512_cmp_epi8_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpb512_mask((__v64qi)(__m512i)(a), \
+                                         (__v64qi)(__m512i)(b), \
+                                         (p), (__mmask64)-1); })
+
+#define _mm512_mask_cmp_epi8_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpb512_mask((__v64qi)(__m512i)(a), \
+                                         (__v64qi)(__m512i)(b), \
+                                         (p), (__mmask64)(m)); })
+
+#define _mm512_cmp_epu8_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpb512_mask((__v64qi)(__m512i)(a), \
+                                          (__v64qi)(__m512i)(b), \
+                                          (p), (__mmask64)-1); })
+
+#define _mm512_mask_cmp_epu8_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpb512_mask((__v64qi)(__m512i)(a), \
+                                          (__v64qi)(__m512i)(b), \
+                                          (p), (__mmask64)(m)); })
+
+#define _mm512_cmp_epi16_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpw512_mask((__v32hi)(__m512i)(a), \
+                                         (__v32hi)(__m512i)(b), \
+                                         (p), (__mmask32)-1); })
+
+#define _mm512_mask_cmp_epi16_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpw512_mask((__v32hi)(__m512i)(a), \
+                                         (__v32hi)(__m512i)(b), \
+                                         (p), (__mmask32)(m)); })
+
+#define _mm512_cmp_epu16_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpw512_mask((__v32hi)(__m512i)(a), \
+                                          (__v32hi)(__m512i)(b), \
+                                          (p), (__mmask32)-1); })
+
+#define _mm512_mask_cmp_epu16_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpw512_mask((__v32hi)(__m512i)(a), \
+                                          (__v32hi)(__m512i)(b), \
+                                          (p), (__mmask32)(m)); })
+
 #endif
diff --git a/lib/Headers/avx512erintrin.h b/lib/Headers/avx512erintrin.h
index 1a5ea15..57c61aa 100644
--- a/lib/Headers/avx512erintrin.h
+++ b/lib/Headers/avx512erintrin.h
@@ -28,85 +28,259 @@
 #define __AVX512ERINTRIN_H
 
 
+// exp2a23
+#define _mm512_exp2a23_round_pd(A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_exp2pd_mask((__v8df)(__m512d)(A), \
+                                      (__v8df)_mm512_setzero_pd(), \
+                                      (__mmask8)-1, (R)); })
+
+#define _mm512_mask_exp2a23_round_pd(S, M, A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_exp2pd_mask((__v8df)(__m512d)(A), \
+                                      (__v8df)(__m512d)(S), \
+                                      (__mmask8)(M), (R)); })
+
+#define _mm512_maskz_exp2a23_round_pd(M, A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_exp2pd_mask((__v8df)(__m512d)(A), \
+                                      (__v8df)_mm512_setzero_pd(), \
+                                      (__mmask8)(M), (R)); })
+
+#define _mm512_exp2a23_pd(A) \
+   _mm512_exp2a23_round_pd((A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_exp2a23_pd(S, M, A) \
+   _mm512_mask_exp2a23_round_pd((S), (M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_maskz_exp2a23_pd(M, A) \
+   _mm512_maskz_exp2a23_round_pd((M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_exp2a23_round_ps(A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_exp2ps_mask((__v16sf)(__m512)(A), \
+                                     (__v16sf)_mm512_setzero_ps(), \
+                                     (__mmask8)-1, (R)); })
+
+#define _mm512_mask_exp2a23_round_ps(S, M, A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_exp2ps_mask((__v16sf)(__m512)(A), \
+                                     (__v16sf)(__m512)(S), \
+                                     (__mmask8)(M), (R)); })
+
+#define _mm512_maskz_exp2a23_round_ps(M, A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_exp2ps_mask((__v16sf)(__m512)(A), \
+                                     (__v16sf)_mm512_setzero_ps(), \
+                                     (__mmask8)(M), (R)); })
+
+#define _mm512_exp2a23_ps(A) \
+   _mm512_exp2a23_round_ps((A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_exp2a23_ps(S, M, A) \
+   _mm512_mask_exp2a23_round_ps((S), (M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_maskz_exp2a23_ps(M, A) \
+   _mm512_maskz_exp2a23_round_ps((M), (A), _MM_FROUND_CUR_DIRECTION)
+
 // rsqrt28
-static  __inline__ __m512d __attribute__((__always_inline__, __nodebug__))
-_mm512_rsqrt28_round_pd (__m512d __A, int __R)
-{
-  return (__m512d)__builtin_ia32_rsqrt28pd_mask ((__v8df)__A,
-                                                 (__v8df)_mm512_setzero_pd(),
-                                                 (__mmask8)-1,
-                                                 __R);
-}
-static  __inline__ __m512 __attribute__((__always_inline__, __nodebug__))
-_mm512_rsqrt28_round_ps(__m512 __A, int __R)
-{
-  return (__m512)__builtin_ia32_rsqrt28ps_mask ((__v16sf)__A,
-                                                (__v16sf)_mm512_setzero_ps(),
-                                                (__mmask16)-1,
-                                                __R);
-}
+#define _mm512_rsqrt28_round_pd(A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_rsqrt28pd_mask((__v8df)(__m512d)(A), \
+                                         (__v8df)_mm512_setzero_pd(), \
+                                         (__mmask8)-1, (R)); })
 
-static  __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
-_mm_rsqrt28_round_ss(__m128 __A, __m128 __B, int __R)
-{
-  return (__m128) __builtin_ia32_rsqrt28ss_mask ((__v4sf) __A,
-             (__v4sf) __B,
-             (__v4sf)
-             _mm_setzero_ps (),
-             (__mmask8) -1,
-             __R);
-}
+#define _mm512_mask_rsqrt28_round_pd(S, M, A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_rsqrt28pd_mask((__v8df)(__m512d)(A), \
+                                         (__v8df)(__m512d)(S), \
+                                         (__mmask8)(M), (R)); })
 
-static  __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
-_mm_rsqrt28_round_sd (__m128d __A, __m128d __B, int __R)
-{
-  return (__m128d) __builtin_ia32_rsqrt28sd_mask ((__v2df) __A,
-              (__v2df) __B,
-              (__v2df)
-              _mm_setzero_pd (),
-              (__mmask8) -1,
-             __R);
-}
+#define _mm512_maskz_rsqrt28_round_pd(M, A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_rsqrt28pd_mask((__v8df)(__m512d)(A), \
+                                         (__v8df)_mm512_setzero_pd(), \
+                                         (__mmask8)(M), (R)); })
 
+#define _mm512_rsqrt28_pd(A) \
+  _mm512_rsqrt28_round_pd((A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_rsqrt28_pd(S, M, A) \
+  _mm512_mask_rsqrt28_round_pd((S), (M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_maskz_rsqrt28_pd(M, A) \
+  _mm512_maskz_rsqrt28_round_pd((M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_rsqrt28_round_ps(A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_rsqrt28ps_mask((__v16sf)(__m512)(A), \
+                                        (__v16sf)_mm512_setzero_ps(), \
+                                        (__mmask16)-1, (R)); })
+
+#define _mm512_mask_rsqrt28_round_ps(S, M, A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_rsqrt28ps_mask((__v16sf)(__m512)(A), \
+                                        (__v16sf)(__m512)(S), \
+                                        (__mmask16)(M), (R)); })
+
+#define _mm512_maskz_rsqrt28_round_ps(M, A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_rsqrt28ps_mask((__v16sf)(__m512)(A), \
+                                        (__v16sf)_mm512_setzero_ps(), \
+                                        (__mmask16)(M), (R)); })
+
+#define _mm512_rsqrt28_ps(A) \
+  _mm512_rsqrt28_round_ps((A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_rsqrt28_ps(S, M, A) \
+  _mm512_mask_rsqrt28_round_ps((S), (M), A, _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_maskz_rsqrt28_ps(M, A) \
+  _mm512_maskz_rsqrt28_round_ps((M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_rsqrt28_round_ss(A, B, R) __extension__ ({ \
+  (__m128)__builtin_ia32_rsqrt28ss_mask((__v4sf)(__m128)(A), \
+                                        (__v4sf)(__m128)(B), \
+                                        (__v4sf)_mm_setzero_ps(), \
+                                        (__mmask8)-1, (R)); })
+
+#define _mm_mask_rsqrt28_round_ss(S, M, A, B, R) __extension__ ({ \
+  (__m128)__builtin_ia32_rsqrt28ss_mask((__v4sf)(__m128)(A), \
+                                        (__v4sf)(__m128)(B), \
+                                        (__v4sf)(__m128)(S), \
+                                        (__mmask8)(M), (R)); })
+
+#define _mm_maskz_rsqrt28_round_ss(M, A, B, R) __extension__ ({ \
+  (__m128)__builtin_ia32_rsqrt28ss_mask((__v4sf)(__m128)(A), \
+                                        (__v4sf)(__m128)(B), \
+                                        (__v4sf)_mm_setzero_ps(), \
+                                        (__mmask8)(M), (R)); })
+
+#define _mm_rsqrt28_ss(A, B) \
+  _mm_rsqrt28_round_ss((A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_mask_rsqrt28_ss(S, M, A, B) \
+  _mm_mask_rsqrt28_round_ss((S), (M), (A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_maskz_rsqrt28_ss(M, A, B) \
+  _mm_maskz_rsqrt28_round_ss((M), (A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_rsqrt28_round_sd(A, B, R) __extension__ ({ \
+  (__m128d)__builtin_ia32_rsqrt28sd_mask((__v2df)(__m128d)(A), \
+                                         (__v2df)(__m128d)(B), \
+                                         (__v2df)_mm_setzero_pd(), \
+                                         (__mmask8)-1, (R)); })
+
+#define _mm_mask_rsqrt28_round_sd(S, M, A, B, R) __extension__ ({ \
+  (__m128d)__builtin_ia32_rsqrt28sd_mask((__v2df)(__m128d)(A), \
+                                         (__v2df)(__m128d)(B), \
+                                         (__v2df)(__m128d)(S), \
+                                         (__mmask8)(M), (R)); })
+
+#define _mm_maskz_rsqrt28_round_sd(M, A, B, R) __extension__ ({ \
+  (__m128d)__builtin_ia32_rsqrt28sd_mask((__v2df)(__m128d)(A), \
+                                         (__v2df)(__m128d)(B), \
+                                         (__v2df)_mm_setzero_pd(), \
+                                         (__mmask8)(M), (R)); })
+
+#define _mm_rsqrt28_sd(A, B) \
+  _mm_rsqrt28_round_sd((A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_mask_rsqrt28_sd(S, M, A, B) \
+  _mm_mask_rsqrt28_round_sd((S), (M), (A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_maskz_rsqrt28_sd(M, A, B) \
+  _mm_mask_rsqrt28_round_sd((M), (A), (B), _MM_FROUND_CUR_DIRECTION)
 
 // rcp28
-static  __inline__ __m512d __attribute__((__always_inline__, __nodebug__))
-_mm512_rcp28_round_pd (__m512d __A, int __R)
-{
-  return (__m512d)__builtin_ia32_rcp28pd_mask ((__v8df)__A,
-                                               (__v8df)_mm512_setzero_pd(),
-                                               (__mmask8)-1,
-                                               __R);
-}
+#define _mm512_rcp28_round_pd(A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_rcp28pd_mask((__v8df)(__m512d)(A), \
+                                       (__v8df)_mm512_setzero_pd(), \
+                                       (__mmask8)-1, (R)); })
 
-static  __inline__ __m512 __attribute__((__always_inline__, __nodebug__))
-_mm512_rcp28_round_ps (__m512 __A, int __R)
-{
-  return (__m512)__builtin_ia32_rcp28ps_mask ((__v16sf)__A,
-                                              (__v16sf)_mm512_setzero_ps (),
-                                              (__mmask16)-1,
-                                              __R);
-}
+#define _mm512_mask_rcp28_round_pd(S, M, A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_rcp28pd_mask((__v8df)(__m512d)(A), \
+                                       (__v8df)(__m512d)(S), \
+                                       (__mmask8)(M), (R)); })
 
-static  __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
-_mm_rcp28_round_ss (__m128 __A, __m128 __B, int __R)
-{
-  return (__m128) __builtin_ia32_rcp28ss_mask ((__v4sf) __A,
-             (__v4sf) __B,
-             (__v4sf)
-             _mm_setzero_ps (),
-             (__mmask8) -1,
-             __R);
-}
-static  __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
-_mm_rcp28_round_sd (__m128d __A, __m128d __B, int __R)
-{
-  return (__m128d) __builtin_ia32_rcp28sd_mask ((__v2df) __A,
-              (__v2df) __B,
-              (__v2df)
-              _mm_setzero_pd (),
-              (__mmask8) -1,
-             __R);
-}
+#define _mm512_maskz_rcp28_round_pd(M, A, R) __extension__ ({ \
+  (__m512d)__builtin_ia32_rcp28pd_mask((__v8df)(__m512d)(A), \
+                                       (__v8df)_mm512_setzero_pd(), \
+                                       (__mmask8)(M), (R)); })
+
+#define _mm512_rcp28_pd(A) \
+  _mm512_rcp28_round_pd((A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_rcp28_pd(S, M, A) \
+  _mm512_mask_rcp28_round_pd((S), (M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_maskz_rcp28_pd(M, A) \
+  _mm512_maskz_rcp28_round_pd((M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_rcp28_round_ps(A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_rcp28ps_mask((__v16sf)(__m512)(A), \
+                                      (__v16sf)_mm512_setzero_ps(), \
+                                      (__mmask16)-1, (R)); })
+
+#define _mm512_mask_rcp28_round_ps(S, M, A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_rcp28ps_mask((__v16sf)(__m512)(A), \
+                                      (__v16sf)(__m512)(S), \
+                                      (__mmask16)(M), (R)); })
+
+#define _mm512_maskz_rcp28_round_ps(M, A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_rcp28ps_mask((__v16sf)(__m512)(A), \
+                                      (__v16sf)_mm512_setzero_ps(), \
+                                      (__mmask16)(M), (R)); })
+
+#define _mm512_rcp28_ps(A) \
+  _mm512_rcp28_round_ps((A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_rcp28_ps(S, M, A) \
+  _mm512_mask_rcp28_round_ps((S), (M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_maskz_rcp28_ps(M, A) \
+  _mm512_maskz_rcp28_round_ps((M), (A), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_rcp28_round_ss(A, B, R) __extension__ ({ \
+  (__m128)__builtin_ia32_rcp28ss_mask((__v4sf)(__m128)(A), \
+                                      (__v4sf)(__m128)(B), \
+                                      (__v4sf)_mm_setzero_ps(), \
+                                      (__mmask8)-1, (R)); })
+
+#define _mm_mask_rcp28_round_ss(S, M, A, B, R) __extension__ ({ \
+  (__m128)__builtin_ia32_rcp28ss_mask((__v4sf)(__m128)(A), \
+                                      (__v4sf)(__m128)(B), \
+                                      (__v4sf)(__m128)(S), \
+                                      (__mmask8)(M), (R)); })
+
+#define _mm_maskz_rcp28_round_ss(M, A, B, R) __extension__ ({ \
+  (__m128)__builtin_ia32_rcp28ss_mask((__v4sf)(__m128)(A), \
+                                      (__v4sf)(__m128)(B), \
+                                      (__v4sf)_mm_setzero_ps(), \
+                                      (__mmask8)(M), (R)); })
+
+#define _mm_rcp28_ss(A, B) \
+  _mm_rcp28_round_ss((A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_mask_rcp28_ss(S, M, A, B) \
+  _mm_mask_rcp28_round_ss((S), (M), (A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_maskz_rcp28_ss(M, A, B) \
+  _mm_maskz_rcp28_round_ss((M), (A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_rcp28_round_sd(A, B, R) __extension__ ({ \
+  (__m128d)__builtin_ia32_rcp28sd_mask((__v2df)(__m128d)(A), \
+                                       (__v2df)(__m128d)(B), \
+                                       (__v2df)_mm_setzero_pd(), \
+                                       (__mmask8)-1, (R)); })
+
+#define _mm_mask_rcp28_round_sd(S, M, A, B, R) __extension__ ({ \
+  (__m128d)__builtin_ia32_rcp28sd_mask((__v2df)(__m128d)(A), \
+                                       (__v2df)(__m128d)(B), \
+                                       (__v2df)(__m128d)(S), \
+                                       (__mmask8)(M), (R)); })
+
+#define _mm_maskz_rcp28_round_sd(M, A, B, R) __extension__ ({ \
+  (__m128d)__builtin_ia32_rcp28sd_mask((__v2df)(__m128d)(A), \
+                                       (__v2df)(__m128d)(B), \
+                                       (__v2df)_mm_setzero_pd(), \
+                                       (__mmask8)(M), (R)); })
+
+#define _mm_rcp28_sd(A, B) \
+  _mm_rcp28_round_sd((A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_mask_rcp28_sd(S, M, A, B) \
+  _mm_mask_rcp28_round_sd((S), (M), (A), (B), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm_maskz_rcp28_sd(M, A, B) \
+  _mm_maskz_rcp28_round_sd((M), (A), (B), _MM_FROUND_CUR_DIRECTION)
 
 #endif // __AVX512ERINTRIN_H
diff --git a/lib/Headers/avx512fintrin.h b/lib/Headers/avx512fintrin.h
index 9591dcf..c6d46cb 100644
--- a/lib/Headers/avx512fintrin.h
+++ b/lib/Headers/avx512fintrin.h
@@ -492,20 +492,13 @@
              (__mmask16) -1);
 }
 
-static __inline __m512 __attribute__ ((__always_inline__, __nodebug__))
-_mm512_roundscale_ps(__m512 __A, const int __imm)
-{
-  return (__m512) __builtin_ia32_rndscaleps_mask ((__v16sf) __A, __imm,
-              (__v16sf) __A, -1,
-              _MM_FROUND_CUR_DIRECTION);
-}
-static __inline __m512d __attribute__ ((__always_inline__, __nodebug__))
-_mm512_roundscale_pd(__m512d __A, const int __imm)
-{
-  return (__m512d) __builtin_ia32_rndscalepd_mask ((__v8df) __A, __imm,
-               (__v8df) __A, -1,
-               _MM_FROUND_CUR_DIRECTION);
-}
+#define _mm512_roundscale_ps(A, B) __extension__ ({ \
+  (__m512)__builtin_ia32_rndscaleps_mask((__v16sf)(A), (B), (__v16sf)(A), \
+                                         -1, _MM_FROUND_CUR_DIRECTION); })
+
+#define _mm512_roundscale_pd(A, B) __extension__ ({ \
+  (__m512d)__builtin_ia32_rndscalepd_mask((__v8df)(A), (B), (__v8df)(A), \
+                                          -1, _MM_FROUND_CUR_DIRECTION); })
 
 static __inline__ __m512d __attribute__((__always_inline__, __nodebug__))
 _mm512_fmadd_pd(__m512d __A, __m512d __B, __m512d __C)
@@ -613,25 +606,35 @@
                                                        (__mmask16) -1);
 }
 
-static __inline __m512i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_valign_epi64(__m512i __A, __m512i __B, const int __I)
-{
-  return (__m512i) __builtin_ia32_alignq512_mask((__v8di)__A,
-                                                 (__v8di)__B,
-                                                 __I,
-                                                 (__v8di)_mm512_setzero_si512(),
-                                                 (__mmask8) -1);
-}
+#define _mm512_alignr_epi64(A, B, I) __extension__ ({ \
+  (__m512i)__builtin_ia32_alignq512_mask((__v8di)(__m512i)(A), \
+                                         (__v8di)(__m512i)(B), \
+                                         (I), (__v8di)_mm512_setzero_si512(), \
+                                         (__mmask8)-1); })
 
-static __inline __m512i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_valign_epi32(__m512i __A, __m512i __B, const int __I)
-{
-  return (__m512i)__builtin_ia32_alignd512_mask((__v16si)__A,
-                                                (__v16si)__B,
-                                                __I,
-                                                (__v16si)_mm512_setzero_si512(),
-                                                (__mmask16) -1);
-}
+#define _mm512_alignr_epi32(A, B, I) __extension__ ({ \
+  (__m512i)__builtin_ia32_alignd512_mask((__v16si)(__m512i)(A), \
+                                         (__v16si)(__m512i)(B), \
+                                         (I), (__v16si)_mm512_setzero_si512(), \
+                                         (__mmask16)-1); })
+
+/* Vector Extract */
+
+#define _mm512_extractf64x4_pd(A, I) __extension__ ({                    \
+      __m512d __A = (A);                                                 \
+      (__m256d)                                                          \
+        __builtin_ia32_extractf64x4_mask((__v8df)__A,                    \
+                                         (I),                            \
+                                         (__v4df)_mm256_setzero_si256(), \
+                                         (__mmask8) -1); })
+
+#define _mm512_extractf32x4_ps(A, I) __extension__ ({                    \
+      __m512 __A = (A);                                                  \
+      (__m128)                                                           \
+        __builtin_ia32_extractf32x4_mask((__v16sf)__A,                   \
+                                         (I),                            \
+                                         (__v4sf)_mm_setzero_ps(),       \
+                                         (__mmask8) -1); })
 
 /* Vector Blend */
 
@@ -669,22 +672,37 @@
 
 /* Compare */
 
-static __inline __mmask16 __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cmp_ps_mask(__m512 a, __m512 b, const int p)
-{
-  return (__mmask16) __builtin_ia32_cmpps512_mask ((__v16sf) a,
-               (__v16sf) b, p, (__mmask16) -1,
-               _MM_FROUND_CUR_DIRECTION);
-}
+#define _mm512_cmp_round_ps_mask(A, B, P, R) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpps512_mask((__v16sf)(__m512)(A), \
+                                          (__v16sf)(__m512)(B), \
+                                          (P), (__mmask16)-1, (R)); })
 
-static __inline __mmask8 __attribute__ ((__always_inline__, __nodebug__)) 
-_mm512_cmp_pd_mask(__m512d __X, __m512d __Y, const int __P)
-{
-  return (__mmask8) __builtin_ia32_cmppd512_mask ((__v8df) __X,
-              (__v8df) __Y, __P,
-              (__mmask8) -1,
-              _MM_FROUND_CUR_DIRECTION);
-}
+#define _mm512_mask_cmp_round_ps_mask(U, A, B, P, R) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpps512_mask((__v16sf)(__m512)(A), \
+                                          (__v16sf)(__m512)(B), \
+                                          (P), (__mmask16)(U), (R)); })
+
+#define _mm512_cmp_ps_mask(A, B, P) \
+  _mm512_cmp_round_ps_mask((A), (B), (P), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_cmp_ps_mask(U, A, B, P) \
+  _mm512_mask_cmp_round_ps_mask((U), (A), (B), (P), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_cmp_round_pd_mask(A, B, P, R) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmppd512_mask((__v8df)(__m512d)(A), \
+                                         (__v8df)(__m512d)(B), \
+                                         (P), (__mmask8)-1, (R)); })
+
+#define _mm512_mask_cmp_round_pd_mask(U, A, B, P, R) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmppd512_mask((__v8df)(__m512d)(A), \
+                                         (__v8df)(__m512d)(B), \
+                                         (P), (__mmask8)(U), (R)); })
+
+#define _mm512_cmp_pd_mask(A, B, P) \
+  _mm512_cmp_round_pd_mask((A), (B), (P), _MM_FROUND_CUR_DIRECTION)
+
+#define _mm512_mask_cmp_pd_mask(U, A, B, P) \
+  _mm512_mask_cmp_round_pd_mask((U), (A), (B), (P), _MM_FROUND_CUR_DIRECTION)
 
 /* Conversion */
 
@@ -698,25 +716,15 @@
                   _MM_FROUND_CUR_DIRECTION);
 }
 
-static __inline __m512 __attribute__ (( __always_inline__, __nodebug__))
-_mm512_cvt_roundepi32_ps(__m512i __A, const int __R)
-{
-  return (__m512) __builtin_ia32_cvtdq2ps512_mask ((__v16si) __A,
-               (__v16sf)
-               _mm512_setzero_ps (),
-               (__mmask16) -1,
-               __R);
-}
+#define _mm512_cvt_roundepi32_ps(A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_cvtdq2ps512_mask((__v16si)(A), \
+                                          (__v16sf)_mm512_setzero_ps(), \
+                                          (__mmask16)-1, (R)); })
 
-static __inline __m512 __attribute__ (( __always_inline__, __nodebug__))
-_mm512_cvt_roundepu32_ps(__m512i __A, const int __R)
-{
-  return (__m512) __builtin_ia32_cvtudq2ps512_mask ((__v16si) __A,
-               (__v16sf)
-               _mm512_setzero_ps (),
-               (__mmask16) -1,
-               __R);
-}
+#define _mm512_cvt_roundepu32_ps(A, R) __extension__ ({ \
+  (__m512)__builtin_ia32_cvtudq2ps512_mask((__v16si)(A), \
+                                           (__v16sf)_mm512_setzero_ps(), \
+                                           (__mmask16)-1, (R)); })
 
 static __inline __m512d __attribute__ (( __always_inline__, __nodebug__))
 _mm512_cvtepi32_pd(__m256i __A)
@@ -735,25 +743,16 @@
                 _mm512_setzero_pd (),
                 (__mmask8) -1);
 }
-static __inline __m256 __attribute__ (( __always_inline__, __nodebug__))
-_mm512_cvt_roundpd_ps(__m512d __A, const int __R)
-{
-  return (__m256) __builtin_ia32_cvtpd2ps512_mask ((__v8df) __A,
-               (__v8sf)
-               _mm256_setzero_ps (),
-               (__mmask8) -1,
-               __R);
-}
 
-static  __inline __m256i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvtps_ph(__m512 __A, const int __I)
-{
-  return (__m256i) __builtin_ia32_vcvtps2ph512_mask ((__v16sf) __A,
-                 __I,
-                 (__v16hi)
-                 _mm256_setzero_si256 (),
-                 -1);
-}
+#define _mm512_cvt_roundpd_ps(A, R) __extension__ ({ \
+  (__m256)__builtin_ia32_cvtpd2ps512_mask((__v8df)(A), \
+                                          (__v8sf)_mm256_setzero_ps(), \
+                                          (__mmask8)-1, (R)); })
+
+#define _mm512_cvtps_ph(A, I) __extension__ ({ \
+  (__m256i)__builtin_ia32_vcvtps2ph512_mask((__v16sf)(A), (I), \
+                                            (__v16hi)_mm256_setzero_si256(), \
+                                            -1); })
 
 static  __inline __m512 __attribute__ ((__always_inline__, __nodebug__))
 _mm512_cvtph_ps(__m256i __A)
@@ -783,60 +782,67 @@
                                                     _MM_FROUND_CUR_DIRECTION);
 }
 
-static __inline __m256i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvtt_roundpd_epi32(__m512d __A, const int __R)
+#define _mm512_cvtt_roundpd_epi32(A, R) __extension__ ({ \
+  (__m256i)__builtin_ia32_cvttpd2dq512_mask((__v8df)(A), \
+                                            (__v8si)_mm256_setzero_si256(), \
+                                            (__mmask8)-1, (R)); })
+
+#define _mm512_cvtt_roundps_epi32(A, R) __extension__ ({ \
+  (__m512i)__builtin_ia32_cvttps2dq512_mask((__v16sf)(A), \
+                                            (__v16si)_mm512_setzero_si512(), \
+                                            (__mmask16)-1, (R)); })
+
+#define _mm512_cvt_roundps_epi32(A, R) __extension__ ({ \
+  (__m512i)__builtin_ia32_cvtps2dq512_mask((__v16sf)(A), \
+                                           (__v16si)_mm512_setzero_si512(), \
+                                           (__mmask16)-1, (R)); })
+
+#define _mm512_cvt_roundpd_epi32(A, R) __extension__ ({ \
+  (__m256i)__builtin_ia32_cvtpd2dq512_mask((__v8df)(A), \
+                                           (__v8si)_mm256_setzero_si256(), \
+                                           (__mmask8)-1, (R)); })
+
+#define _mm512_cvt_roundps_epu32(A, R) __extension__ ({ \
+  (__m512i)__builtin_ia32_cvtps2udq512_mask((__v16sf)(A), \
+                                            (__v16si)_mm512_setzero_si512(), \
+                                            (__mmask16)-1, (R)); })
+
+#define _mm512_cvt_roundpd_epu32(A, R) __extension__ ({ \
+  (__m256i)__builtin_ia32_cvtpd2udq512_mask((__v8df)(A), \
+                                            (__v8si)_mm256_setzero_si256(), \
+                                            (__mmask8) -1, (R)); })
+
+/* Unpack and Interleave */
+static __inline __m512d __attribute__((__always_inline__, __nodebug__))
+_mm512_unpackhi_pd(__m512d __a, __m512d __b)
 {
-  return (__m256i) __builtin_ia32_cvttpd2dq512_mask ((__v8df) __A,
-                 (__v8si)
-                 _mm256_setzero_si256 (),
-                 (__mmask8) -1,
-                 __R);
-}
-static __inline __m512i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvtt_roundps_epi32(__m512 __A, const int __R)
-{
-  return (__m512i) __builtin_ia32_cvttps2dq512_mask ((__v16sf) __A,
-                 (__v16si)
-                 _mm512_setzero_si512 (),
-                 (__mmask16) -1,
-                 __R);
+  return __builtin_shufflevector(__a, __b, 1, 9, 1+2, 9+2, 1+4, 9+4, 1+6, 9+6);
 }
 
-static __inline __m512i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvt_roundps_epi32(__m512 __A, const int __R)
+static __inline __m512d __attribute__((__always_inline__, __nodebug__))
+_mm512_unpacklo_pd(__m512d __a, __m512d __b)
 {
-  return (__m512i) __builtin_ia32_cvtps2dq512_mask ((__v16sf) __A,
-                (__v16si)
-                _mm512_setzero_si512 (),
-                (__mmask16) -1,
-                __R);
+  return __builtin_shufflevector(__a, __b, 0, 8, 0+2, 8+2, 0+4, 8+4, 0+6, 8+6);
 }
-static __inline __m256i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvt_roundpd_epi32(__m512d __A, const int __R)
+
+static __inline __m512 __attribute__((__always_inline__, __nodebug__))
+_mm512_unpackhi_ps(__m512 __a, __m512 __b)
 {
-  return (__m256i) __builtin_ia32_cvtpd2dq512_mask ((__v8df) __A,
-                (__v8si)
-                _mm256_setzero_si256 (),
-                (__mmask8) -1,
-                __R);
+  return __builtin_shufflevector(__a, __b,
+                                 2,    18,    3,    19,
+                                 2+4,  18+4,  3+4,  19+4,
+                                 2+8,  18+8,  3+8,  19+8,
+                                 2+12, 18+12, 3+12, 19+12);
 }
-static __inline __m512i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvt_roundps_epu32(__m512 __A, const int __R)
+
+static __inline __m512 __attribute__((__always_inline__, __nodebug__))
+_mm512_unpacklo_ps(__m512 __a, __m512 __b)
 {
-  return (__m512i) __builtin_ia32_cvtps2udq512_mask ((__v16sf) __A,
-                (__v16si)
-                _mm512_setzero_si512 (),
-                (__mmask16) -1,
-                __R);
-}
-static __inline __m256i __attribute__ ((__always_inline__, __nodebug__))
-_mm512_cvt_roundpd_epu32(__m512d __A, const int __R)
-{
-  return (__m256i) __builtin_ia32_cvtpd2udq512_mask ((__v8df) __A,
-                (__v8si)
-                _mm256_setzero_si256 (),
-                (__mmask8) -1,
-                __R);
+  return __builtin_shufflevector(__a, __b,
+                                 0,    16,    1,    17,
+                                 0+4,  16+4,  1+4,  17+4,
+                                 0+8,  16+8,  1+8,  17+8,
+                                 0+12, 16+12, 1+12, 17+12);
 }
 
 /* Bit Test */
@@ -895,12 +901,30 @@
                                                    (__mmask8) __U);
 }
 
+static __inline __m512 __attribute__ ((__always_inline__, __nodebug__))
+_mm512_maskz_load_ps(__mmask16 __U, void const *__P)
+{
+  return (__m512) __builtin_ia32_loadaps512_mask ((const __v16sf *)__P,
+                                                  (__v16sf)
+                                                  _mm512_setzero_ps (),
+                                                  (__mmask16) __U);
+}
+
+static __inline __m512d __attribute__ ((__always_inline__, __nodebug__))
+_mm512_maskz_load_pd(__mmask8 __U, void const *__P)
+{
+  return (__m512d) __builtin_ia32_loadapd512_mask ((const __v8df *)__P,
+                                                   (__v8df)
+                                                   _mm512_setzero_pd (),
+                                                   (__mmask8) __U);
+}
+
 static __inline __m512d __attribute__((__always_inline__, __nodebug__))
 _mm512_loadu_pd(double const *__p)
 {
   struct __loadu_pd {
     __m512d __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_pd*)__p)->__v;
 }
 
@@ -909,10 +933,28 @@
 {
   struct __loadu_ps {
     __m512 __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_ps*)__p)->__v;
 }
 
+static __inline __m512 __attribute__((__always_inline__, __nodebug__))
+_mm512_load_ps(double const *__p)
+{
+  return (__m512) __builtin_ia32_loadaps512_mask ((const __v16sf *)__p,
+                                                  (__v16sf)
+                                                  _mm512_setzero_ps (),
+                                                  (__mmask16) -1);
+}
+
+static __inline __m512d __attribute__((__always_inline__, __nodebug__))
+_mm512_load_pd(float const *__p)
+{
+  return (__m512d) __builtin_ia32_loadapd512_mask ((const __v8df *)__p,
+                                                   (__v8df)
+                                                   _mm512_setzero_pd (),
+                                                   (__mmask8) -1);
+}
+
 /* SIMD store ops */
 
 static __inline void __attribute__ ((__always_inline__, __nodebug__))
@@ -955,9 +997,9 @@
 }
 
 static __inline void __attribute__ ((__always_inline__, __nodebug__))
-_mm512_store_ps(void *__P, __m512 __A)
+_mm512_mask_store_pd(void *__P, __mmask8 __U, __m512d __A)
 {
-  *(__m512*)__P = __A;
+  __builtin_ia32_storeapd512_mask ((__v8df *)__P, (__v8df) __A, (__mmask8) __U);
 }
 
 static __inline void __attribute__ ((__always_inline__, __nodebug__))
@@ -966,6 +1008,19 @@
   *(__m512d*)__P = __A;
 }
 
+static __inline void __attribute__ ((__always_inline__, __nodebug__))
+_mm512_mask_store_ps(void *__P, __mmask16 __U, __m512 __A)
+{
+  __builtin_ia32_storeaps512_mask ((__v16sf *)__P, (__v16sf) __A,
+                                   (__mmask16) __U);
+}
+
+static __inline void __attribute__ ((__always_inline__, __nodebug__))
+_mm512_store_ps(void *__P, __m512 __A)
+{
+  *(__m512*)__P = __A;
+}
+
 /* Mask ops */
 
 static __inline __mmask16 __attribute__ ((__always_inline__, __nodebug__))
@@ -988,6 +1043,18 @@
                                                    __u);
 }
 
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpeq_epu32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 0,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpeq_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 0,
+                                                 __u);
+}
+
 static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
 _mm512_mask_cmpeq_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
   return (__mmask8)__builtin_ia32_pcmpeqq512_mask((__v8di)__a, (__v8di)__b,
@@ -1000,4 +1067,303 @@
                                                   (__mmask8)-1);
 }
 
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpeq_epu64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 0,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpeq_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 0,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epi32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 5,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epu32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 5,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 5,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epi64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 5,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 5,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpge_epu64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 5,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpge_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epi32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_pcmpgtd512_mask((__v16si)__a, (__v16si)__b,
+                                                   (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_pcmpgtd512_mask((__v16si)__a, (__v16si)__b,
+                                                   __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epu32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 6,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 6,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtq512_mask((__v8di)__a, (__v8di)__b,
+                                                  __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epi64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtq512_mask((__v8di)__a, (__v8di)__b,
+                                                  (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpgt_epu64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 6,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpgt_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 6,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epi32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 2,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epu32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 2,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 2,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epi64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 2,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 2,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmple_epu64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 2,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmple_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epi32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 1,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epu32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 1,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 1,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epi64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 1,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 1,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmplt_epu64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 1,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmplt_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epi32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 4,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epu32_mask(__m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 4,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  return (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, 4,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epi64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 4,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, 4,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_cmpneq_epu64_mask(__m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 4,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm512_mask_cmpneq_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, 4,
+                                                __u);
+}
+
+#define _mm512_cmp_epi32_mask(a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, (p), \
+                                         (__mmask16)-1); })
+
+#define _mm512_cmp_epu32_mask(a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, (p), \
+                                          (__mmask16)-1); })
+
+#define _mm512_cmp_epi64_mask(a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, (p), \
+                                        (__mmask8)-1); })
+
+#define _mm512_cmp_epu64_mask(a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, (p), \
+                                         (__mmask8)-1); })
+
+#define _mm512_mask_cmp_epi32_mask(m, a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask16)__builtin_ia32_cmpd512_mask((__v16si)__a, (__v16si)__b, (p), \
+                                         (__mmask16)(m)); })
+
+#define _mm512_mask_cmp_epu32_mask(m, a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask16)__builtin_ia32_ucmpd512_mask((__v16si)__a, (__v16si)__b, (p), \
+                                          (__mmask16)(m)); })
+
+#define _mm512_mask_cmp_epi64_mask(m, a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask8)__builtin_ia32_cmpq512_mask((__v8di)__a, (__v8di)__b, (p), \
+                                        (__mmask8)(m)); })
+
+#define _mm512_mask_cmp_epu64_mask(m, a, b, p) __extension__ ({ \
+  __m512i __a = (a); \
+  __m512i __b = (b); \
+  (__mmask8)__builtin_ia32_ucmpq512_mask((__v8di)__a, (__v8di)__b, (p), \
+                                         (__mmask8)(m)); })
 #endif // __AVX512FINTRIN_H
diff --git a/lib/Headers/avx512vlbwintrin.h b/lib/Headers/avx512vlbwintrin.h
index 11333f8..0746f43 100644
--- a/lib/Headers/avx512vlbwintrin.h
+++ b/lib/Headers/avx512vlbwintrin.h
@@ -42,6 +42,17 @@
                                                    __u);
 }
 
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpeq_epu8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 0,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpeq_epu8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 0,
+                                                 __u);
+}
 
 static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
 _mm256_cmpeq_epi8_mask(__m256i __a, __m256i __b) {
@@ -55,6 +66,18 @@
                                                    __u);
 }
 
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpeq_epu8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 0,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpeq_epu8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 0,
+                                                 __u);
+}
+
 static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_epi16_mask(__m128i __a, __m128i __b) {
   return (__mmask8)__builtin_ia32_pcmpeqw128_mask((__v8hi)__a, (__v8hi)__b,
@@ -67,6 +90,17 @@
                                                   __u);
 }
 
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpeq_epu16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 0,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpeq_epu16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 0,
+                                                __u);
+}
 
 static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
 _mm256_cmpeq_epi16_mask(__m256i __a, __m256i __b) {
@@ -80,4 +114,576 @@
                                                    __u);
 }
 
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpeq_epu16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 0,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpeq_epu16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 0,
+                                                 __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epi8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 5,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epi8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epu8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 5,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epu8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 5,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epi8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 5,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epi8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epu8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 5,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epu8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 5,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epi16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 5,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epi16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 5,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epu16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 5,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epu16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epi16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 5,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epi16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epu16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 5,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epu16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 5,
+                                                 __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epi8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_pcmpgtb128_mask((__v16qi)__a, (__v16qi)__b,
+                                                   (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epi8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_pcmpgtb128_mask((__v16qi)__a, (__v16qi)__b,
+                                                   __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epu8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 6,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epu8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 6,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epi8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_pcmpgtb256_mask((__v32qi)__a, (__v32qi)__b,
+                                                   (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epi8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_pcmpgtb256_mask((__v32qi)__a, (__v32qi)__b,
+                                                   __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epu8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 6,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epu8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 6,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epi16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtw128_mask((__v8hi)__a, (__v8hi)__b,
+                                                  (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epi16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtw128_mask((__v8hi)__a, (__v8hi)__b,
+                                                  __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epu16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 6,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epu16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 6,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epi16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_pcmpgtw256_mask((__v16hi)__a, (__v16hi)__b,
+                                                   (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epi16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_pcmpgtw256_mask((__v16hi)__a, (__v16hi)__b,
+                                                   __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epu16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 6,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epu16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 6,
+                                                 __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epi8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 2,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epi8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epu8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 2,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epu8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 2,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epi8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 2,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epi8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epu8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 2,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epu8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 2,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epi16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 2,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epi16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 2,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epu16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 2,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epu16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epi16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 2,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epi16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epu16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 2,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epu16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 2,
+                                                 __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epi8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 1,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epi8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epu8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 1,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epu8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 1,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epi8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 1,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epi8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epu8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 1,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epu8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 1,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epi16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 1,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epi16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 1,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epu16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 1,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epu16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epi16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 1,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epi16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epu16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 1,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epu16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 1,
+                                                 __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epi8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 4,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epi8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)__a, (__v16qi)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epu8_mask(__m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 4,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epu8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  return (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)__a, (__v16qi)__b, 4,
+                                                 __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epi8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 4,
+                                                (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epi8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)__a, (__v32qi)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epu8_mask(__m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 4,
+                                                 (__mmask32)-1);
+}
+
+static __inline__ __mmask32 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epu8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  return (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)__a, (__v32qi)__b, 4,
+                                                 __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epi16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 4,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epi16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)__a, (__v8hi)__b, 4,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epu16_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 4,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epu16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)__a, (__v8hi)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epi16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 4,
+                                                (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epi16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)__a, (__v16hi)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epu16_mask(__m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 4,
+                                                 (__mmask16)-1);
+}
+
+static __inline__ __mmask16 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epu16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  return (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)__a, (__v16hi)__b, 4,
+                                                 __u);
+}
+
+#define _mm_cmp_epi8_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)(__m128i)(a), \
+                                         (__v16qi)(__m128i)(b), \
+                                         (p), (__mmask16)-1); })
+
+#define _mm_mask_cmp_epi8_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpb128_mask((__v16qi)(__m128i)(a), \
+                                         (__v16qi)(__m128i)(b), \
+                                         (p), (__mmask16)(m)); })
+
+#define _mm_cmp_epu8_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)(__m128i)(a), \
+                                          (__v16qi)(__m128i)(b), \
+                                          (p), (__mmask16)-1); })
+
+#define _mm_mask_cmp_epu8_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpb128_mask((__v16qi)(__m128i)(a), \
+                                          (__v16qi)(__m128i)(b), \
+                                          (p), (__mmask16)(m)); })
+
+#define _mm256_cmp_epi8_mask(a, b, p) __extension__ ({ \
+  (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)(__m256i)(a), \
+                                         (__v32qi)(__m256i)(b), \
+                                         (p), (__mmask32)-1); })
+
+#define _mm256_mask_cmp_epi8_mask(m, a, b, p) __extension__ ({ \
+  (__mmask32)__builtin_ia32_cmpb256_mask((__v32qi)(__m256i)(a), \
+                                         (__v32qi)(__m256i)(b), \
+                                         (p), (__mmask32)(m)); })
+
+#define _mm256_cmp_epu8_mask(a, b, p) __extension__ ({ \
+  (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)(__m256i)(a), \
+                                          (__v32qi)(__m256i)(b), \
+                                          (p), (__mmask32)-1); })
+
+#define _mm256_mask_cmp_epu8_mask(m, a, b, p) __extension__ ({ \
+  (__mmask32)__builtin_ia32_ucmpb256_mask((__v32qi)(__m256i)(a), \
+                                          (__v32qi)(__m256i)(b), \
+                                          (p), (__mmask32)(m)); })
+
+#define _mm_cmp_epi16_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)(__m128i)(a), \
+                                        (__v8hi)(__m128i)(b), \
+                                        (p), (__mmask8)-1); })
+
+#define _mm_mask_cmp_epi16_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpw128_mask((__v8hi)(__m128i)(a), \
+                                        (__v8hi)(__m128i)(b), \
+                                        (p), (__mmask8)(m)); })
+
+#define _mm_cmp_epu16_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)(__m128i)(a), \
+                                         (__v8hi)(__m128i)(b), \
+                                         (p), (__mmask8)-1); })
+
+#define _mm_mask_cmp_epu16_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpw128_mask((__v8hi)(__m128i)(a), \
+                                         (__v8hi)(__m128i)(b), \
+                                         (p), (__mmask8)(m)); })
+
+#define _mm256_cmp_epi16_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)(__m256i)(a), \
+                                         (__v16hi)(__m256i)(b), \
+                                         (p), (__mmask16)-1); })
+
+#define _mm256_mask_cmp_epi16_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_cmpw256_mask((__v16hi)(__m256i)(a), \
+                                         (__v16hi)(__m256i)(b), \
+                                         (p), (__mmask16)(m)); })
+
+#define _mm256_cmp_epu16_mask(a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)(__m256i)(a), \
+                                          (__v16hi)(__m256i)(b), \
+                                          (p), (__mmask16)-1); })
+
+#define _mm256_mask_cmp_epu16_mask(m, a, b, p) __extension__ ({ \
+  (__mmask16)__builtin_ia32_ucmpw256_mask((__v16hi)(__m256i)(a), \
+                                          (__v16hi)(__m256i)(b), \
+                                          (p), (__mmask16)(m)); })
+
 #endif /* __AVX512VLBWINTRIN_H */
diff --git a/lib/Headers/avx512vlintrin.h b/lib/Headers/avx512vlintrin.h
index 8a374b1..b460992 100644
--- a/lib/Headers/avx512vlintrin.h
+++ b/lib/Headers/avx512vlintrin.h
@@ -42,6 +42,17 @@
                                                   __u);
 }
 
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpeq_epu32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 0,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpeq_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 0,
+                                                __u);
+}
 
 static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
 _mm256_cmpeq_epi32_mask(__m256i __a, __m256i __b) {
@@ -56,6 +67,18 @@
 }
 
 static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpeq_epu32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 0,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpeq_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 0,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_epi64_mask(__m128i __a, __m128i __b) {
   return (__mmask8)__builtin_ia32_pcmpeqq128_mask((__v2di)__a, (__v2di)__b,
                                                   (__mmask8)-1);
@@ -67,6 +90,17 @@
                                                   __u);
 }
 
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpeq_epu64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 0,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpeq_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 0,
+                                                __u);
+}
 
 static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
 _mm256_cmpeq_epi64_mask(__m256i __a, __m256i __b) {
@@ -80,4 +114,580 @@
                                                   __u);
 }
 
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpeq_epu64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 0,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpeq_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 0,
+                                                __u);
+}
+
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epi32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 5,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 5,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epu32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 5,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epi32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 5,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 5,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epu32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 5,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epi64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 5,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 5,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpge_epu64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 5,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpge_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 5,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epi64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 5,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 5,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpge_epu64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 5,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpge_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 5,
+                                                __u);
+}
+
+
+
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epi32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtd128_mask((__v4si)__a, (__v4si)__b,
+                                                  (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtd128_mask((__v4si)__a, (__v4si)__b,
+                                                  __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epu32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 6,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 6,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epi32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtd256_mask((__v8si)__a, (__v8si)__b,
+                                                  (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtd256_mask((__v8si)__a, (__v8si)__b,
+                                                  __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epu32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 6,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 6,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epi64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtq128_mask((__v2di)__a, (__v2di)__b,
+                                                  (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtq128_mask((__v2di)__a, (__v2di)__b,
+                                                  __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpgt_epu64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 6,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpgt_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 6,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epi64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtq256_mask((__v4di)__a, (__v4di)__b,
+                                                  (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_pcmpgtq256_mask((__v4di)__a, (__v4di)__b,
+                                                  __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpgt_epu64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 6,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpgt_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 6,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epi32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 2,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 2,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epu32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 2,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epi32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 2,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 2,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epu32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 2,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epi64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 2,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 2,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmple_epu64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 2,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmple_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epi64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 2,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 2,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmple_epu64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 2,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmple_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 2,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epi32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 1,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 1,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epu32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 1,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epi32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 1,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 1,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epu32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 1,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epi64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 1,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 1,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmplt_epu64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 1,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmplt_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epi64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 1,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 1,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmplt_epu64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 1,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmplt_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 1,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epi32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 4,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)__a, (__v4si)__b, 4,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epu32_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 4,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)__a, (__v4si)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epi32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 4,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)__a, (__v8si)__b, 4,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epu32_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 4,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)__a, (__v8si)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epi64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 4,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)__a, (__v2di)__b, 4,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_cmpneq_epu64_mask(__m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 4,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm_mask_cmpneq_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)__a, (__v2di)__b, 4,
+                                                __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epi64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 4,
+                                               (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)__a, (__v4di)__b, 4,
+                                               __u);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_cmpneq_epu64_mask(__m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 4,
+                                                (__mmask8)-1);
+}
+
+static __inline__ __mmask8 __attribute__((__always_inline__, __nodebug__))
+_mm256_mask_cmpneq_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  return (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)__a, (__v4di)__b, 4,
+                                                __u);
+}
+
+#define _mm_cmp_epi32_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)(__m128i)(a), \
+                                        (__v4si)(__m128i)(b), \
+                                        (p), (__mmask8)-1); })
+
+#define _mm_mask_cmp_epi32_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpd128_mask((__v4si)(__m128i)(a), \
+                                        (__v4si)(__m128i)(b), \
+                                        (p), (__mmask8)(m)); })
+
+#define _mm_cmp_epu32_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)(__m128i)(a), \
+                                         (__v4si)(__m128i)(b), \
+                                         (p), (__mmask8)-1); })
+
+#define _mm_mask_cmp_epu32_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpd128_mask((__v4si)(__m128i)(a), \
+                                         (__v4si)(__m128i)(b), \
+                                         (p), (__mmask8)(m)); })
+
+#define _mm256_cmp_epi32_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)(__m256i)(a), \
+                                        (__v8si)(__m256i)(b), \
+                                        (p), (__mmask8)-1); })
+
+#define _mm256_mask_cmp_epi32_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpd256_mask((__v8si)(__m256i)(a), \
+                                        (__v8si)(__m256i)(b), \
+                                        (p), (__mmask8)(m)); })
+
+#define _mm256_cmp_epu32_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)(__m256i)(a), \
+                                         (__v8si)(__m256i)(b), \
+                                         (p), (__mmask8)-1); })
+
+#define _mm256_mask_cmp_epu32_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpd256_mask((__v8si)(__m256i)(a), \
+                                         (__v8si)(__m256i)(b), \
+                                         (p), (__mmask8)(m)); })
+
+#define _mm_cmp_epi64_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)(__m128i)(a), \
+                                        (__v2di)(__m128i)(b), \
+                                        (p), (__mmask8)-1); })
+
+#define _mm_mask_cmp_epi64_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpq128_mask((__v2di)(__m128i)(a), \
+                                        (__v2di)(__m128i)(b), \
+                                        (p), (__mmask8)(m)); })
+
+#define _mm_cmp_epu64_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)(__m128i)(a), \
+                                         (__v2di)(__m128i)(b), \
+                                         (p), (__mmask8)-1); })
+
+#define _mm_mask_cmp_epu64_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpq128_mask((__v2di)(__m128i)(a), \
+                                         (__v2di)(__m128i)(b), \
+                                         (p), (__mmask8)(m)); })
+
+#define _mm256_cmp_epi64_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)(__m256i)(a), \
+                                        (__v4di)(__m256i)(b), \
+                                        (p), (__mmask8)-1); })
+
+#define _mm256_mask_cmp_epi64_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_cmpq256_mask((__v4di)(__m256i)(a), \
+                                        (__v4di)(__m256i)(b), \
+                                        (p), (__mmask8)(m)); })
+
+#define _mm256_cmp_epu64_mask(a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)(__m256i)(a), \
+                                         (__v4di)(__m256i)(b), \
+                                         (p), (__mmask8)-1); })
+
+#define _mm256_mask_cmp_epu64_mask(m, a, b, p) __extension__ ({ \
+  (__mmask8)__builtin_ia32_ucmpq256_mask((__v4di)(__m256i)(a), \
+                                         (__v4di)(__m256i)(b), \
+                                         (p), (__mmask8)(m)); })
+
 #endif /* __AVX512VLINTRIN_H */
diff --git a/lib/Headers/avxintrin.h b/lib/Headers/avxintrin.h
index 4e1044a..d7c7f46 100644
--- a/lib/Headers/avxintrin.h
+++ b/lib/Headers/avxintrin.h
@@ -257,8 +257,7 @@
 static __inline __m256 __attribute__((__always_inline__, __nodebug__))
 _mm256_permutevar_ps(__m256 __a, __m256i __c)
 {
-  return (__m256)__builtin_ia32_vpermilvarps256((__v8sf)__a,
-						  (__v8si)__c);
+  return (__m256)__builtin_ia32_vpermilvarps256((__v8sf)__a, (__v8si)__c);
 }
 
 #define _mm_permute_pd(A, C) __extension__ ({ \
@@ -444,21 +443,21 @@
   (__m128i)__builtin_ia32_vextractf128_si256((__v8si)__A, (O)); })
 
 static __inline int __attribute__((__always_inline__, __nodebug__))
-_mm256_extract_epi32(__m256i __a, int const __imm)
+_mm256_extract_epi32(__m256i __a, const int __imm)
 {
   __v8si __b = (__v8si)__a;
   return __b[__imm & 7];
 }
 
 static __inline int __attribute__((__always_inline__, __nodebug__))
-_mm256_extract_epi16(__m256i __a, int const __imm)
+_mm256_extract_epi16(__m256i __a, const int __imm)
 {
   __v16hi __b = (__v16hi)__a;
   return __b[__imm & 15];
 }
 
 static __inline int __attribute__((__always_inline__, __nodebug__))
-_mm256_extract_epi8(__m256i __a, int const __imm)
+_mm256_extract_epi8(__m256i __a, const int __imm)
 {
   __v32qi __b = (__v32qi)__a;
   return __b[__imm & 31];
@@ -515,7 +514,7 @@
 
 #ifdef __x86_64__
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
-_mm256_insert_epi64(__m256i __a, int __b, int const __imm)
+_mm256_insert_epi64(__m256i __a, long long __b, int const __imm)
 {
   __v4di __c = (__v4di)__a;
   __c[__imm & 3] = __b;
@@ -785,7 +784,7 @@
 {
   struct __loadu_pd {
     __m256d __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_pd*)__p)->__v;
 }
 
@@ -794,7 +793,7 @@
 {
   struct __loadu_ps {
     __m256 __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_ps*)__p)->__v;
 }
 
@@ -809,7 +808,7 @@
 {
   struct __loadu_si256 {
     __m256i __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_si256*)__p)->__v;
 }
 
@@ -935,23 +934,23 @@
 
 static __inline __m256 __attribute__((__always_inline__, __nodebug__))
 _mm256_set_ps(float __a, float __b, float __c, float __d,
-	            float __e, float __f, float __g, float __h)
+              float __e, float __f, float __g, float __h)
 {
   return (__m256){ __h, __g, __f, __e, __d, __c, __b, __a };
 }
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_set_epi32(int __i0, int __i1, int __i2, int __i3,
-		             int __i4, int __i5, int __i6, int __i7)
+                 int __i4, int __i5, int __i6, int __i7)
 {
   return (__m256i)(__v8si){ __i7, __i6, __i5, __i4, __i3, __i2, __i1, __i0 };
 }
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_set_epi16(short __w15, short __w14, short __w13, short __w12,
-		             short __w11, short __w10, short __w09, short __w08,
-		             short __w07, short __w06, short __w05, short __w04,
-		             short __w03, short __w02, short __w01, short __w00)
+                 short __w11, short __w10, short __w09, short __w08,
+                 short __w07, short __w06, short __w05, short __w04,
+                 short __w03, short __w02, short __w01, short __w00)
 {
   return (__m256i)(__v16hi){ __w00, __w01, __w02, __w03, __w04, __w05, __w06,
     __w07, __w08, __w09, __w10, __w11, __w12, __w13, __w14, __w15 };
@@ -959,13 +958,13 @@
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_set_epi8(char __b31, char __b30, char __b29, char __b28,
-		            char __b27, char __b26, char __b25, char __b24,
-		            char __b23, char __b22, char __b21, char __b20,
-		            char __b19, char __b18, char __b17, char __b16,
-		            char __b15, char __b14, char __b13, char __b12,
-		            char __b11, char __b10, char __b09, char __b08,
-		            char __b07, char __b06, char __b05, char __b04,
-		            char __b03, char __b02, char __b01, char __b00)
+                char __b27, char __b26, char __b25, char __b24,
+                char __b23, char __b22, char __b21, char __b20,
+                char __b19, char __b18, char __b17, char __b16,
+                char __b15, char __b14, char __b13, char __b12,
+                char __b11, char __b10, char __b09, char __b08,
+                char __b07, char __b06, char __b05, char __b04,
+                char __b03, char __b02, char __b01, char __b00)
 {
   return (__m256i)(__v32qi){
     __b00, __b01, __b02, __b03, __b04, __b05, __b06, __b07,
@@ -990,23 +989,23 @@
 
 static __inline __m256 __attribute__((__always_inline__, __nodebug__))
 _mm256_setr_ps(float __a, float __b, float __c, float __d,
-		           float __e, float __f, float __g, float __h)
+               float __e, float __f, float __g, float __h)
 {
   return (__m256){ __a, __b, __c, __d, __e, __f, __g, __h };
 }
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_setr_epi32(int __i0, int __i1, int __i2, int __i3,
-		              int __i4, int __i5, int __i6, int __i7)
+                  int __i4, int __i5, int __i6, int __i7)
 {
   return (__m256i)(__v8si){ __i0, __i1, __i2, __i3, __i4, __i5, __i6, __i7 };
 }
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_setr_epi16(short __w15, short __w14, short __w13, short __w12,
-		   short __w11, short __w10, short __w09, short __w08,
-		   short __w07, short __w06, short __w05, short __w04,
-		   short __w03, short __w02, short __w01, short __w00)
+       short __w11, short __w10, short __w09, short __w08,
+       short __w07, short __w06, short __w05, short __w04,
+       short __w03, short __w02, short __w01, short __w00)
 {
   return (__m256i)(__v16hi){ __w15, __w14, __w13, __w12, __w11, __w10, __w09,
     __w08, __w07, __w06, __w05, __w04, __w03, __w02, __w01, __w00 };
@@ -1014,19 +1013,19 @@
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_setr_epi8(char __b31, char __b30, char __b29, char __b28,
-		             char __b27, char __b26, char __b25, char __b24,
-		             char __b23, char __b22, char __b21, char __b20,
-		             char __b19, char __b18, char __b17, char __b16,
-		             char __b15, char __b14, char __b13, char __b12,
-		             char __b11, char __b10, char __b09, char __b08,
-		             char __b07, char __b06, char __b05, char __b04,
-		             char __b03, char __b02, char __b01, char __b00)
+                 char __b27, char __b26, char __b25, char __b24,
+                 char __b23, char __b22, char __b21, char __b20,
+                 char __b19, char __b18, char __b17, char __b16,
+                 char __b15, char __b14, char __b13, char __b12,
+                 char __b11, char __b10, char __b09, char __b08,
+                 char __b07, char __b06, char __b05, char __b04,
+                 char __b03, char __b02, char __b01, char __b00)
 {
   return (__m256i)(__v32qi){
     __b31, __b30, __b29, __b28, __b27, __b26, __b25, __b24,
-		__b23, __b22, __b21, __b20, __b19, __b18, __b17, __b16,
-		__b15, __b14, __b13, __b12, __b11, __b10, __b09, __b08,
-		__b07, __b06, __b05, __b04, __b03, __b02, __b01, __b00 };
+    __b23, __b22, __b21, __b20, __b19, __b18, __b17, __b16,
+    __b15, __b14, __b13, __b12, __b11, __b10, __b09, __b08,
+    __b07, __b06, __b05, __b04, __b03, __b02, __b01, __b00 };
 }
 
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
@@ -1195,7 +1194,7 @@
 {
   struct __loadu_si128 {
     __m128i __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   __m256i __v256 = _mm256_castsi128_si256(
     ((struct __loadu_si128*)__addr_lo)->__v);
   return _mm256_insertf128_si256(__v256,
diff --git a/lib/Headers/emmintrin.h b/lib/Headers/emmintrin.h
index b3f8569..c764d68 100644
--- a/lib/Headers/emmintrin.h
+++ b/lib/Headers/emmintrin.h
@@ -155,148 +155,148 @@
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 0);
+  return (__m128d)__builtin_ia32_cmpeqpd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmplt_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 1);
+  return (__m128d)__builtin_ia32_cmpltpd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmple_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 2);
+  return (__m128d)__builtin_ia32_cmplepd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpgt_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__b, __a, 1);
+  return (__m128d)__builtin_ia32_cmpltpd(__b, __a);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpge_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__b, __a, 2);
+  return (__m128d)__builtin_ia32_cmplepd(__b, __a);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpord_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 7);
+  return (__m128d)__builtin_ia32_cmpordpd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpunord_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 3);
+  return (__m128d)__builtin_ia32_cmpunordpd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpneq_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 4);
+  return (__m128d)__builtin_ia32_cmpneqpd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnlt_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 5);
+  return (__m128d)__builtin_ia32_cmpnltpd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnle_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__a, __b, 6);
+  return (__m128d)__builtin_ia32_cmpnlepd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpngt_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__b, __a, 5);
+  return (__m128d)__builtin_ia32_cmpnltpd(__b, __a);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnge_pd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmppd(__b, __a, 6);
+  return (__m128d)__builtin_ia32_cmpnlepd(__b, __a);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 0);
+  return (__m128d)__builtin_ia32_cmpeqsd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmplt_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 1);
+  return (__m128d)__builtin_ia32_cmpltsd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmple_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 2);
+  return (__m128d)__builtin_ia32_cmplesd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpgt_sd(__m128d __a, __m128d __b)
 {
-  __m128d __c = __builtin_ia32_cmpsd(__b, __a, 1);
+  __m128d __c = __builtin_ia32_cmpltsd(__b, __a);
   return (__m128d) { __c[0], __a[1] };
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpge_sd(__m128d __a, __m128d __b)
 {
-  __m128d __c = __builtin_ia32_cmpsd(__b, __a, 2);
+  __m128d __c = __builtin_ia32_cmplesd(__b, __a);
   return (__m128d) { __c[0], __a[1] };
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpord_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 7);
+  return (__m128d)__builtin_ia32_cmpordsd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpunord_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 3);
+  return (__m128d)__builtin_ia32_cmpunordsd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpneq_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 4);
+  return (__m128d)__builtin_ia32_cmpneqsd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnlt_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 5);
+  return (__m128d)__builtin_ia32_cmpnltsd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnle_sd(__m128d __a, __m128d __b)
 {
-  return (__m128d)__builtin_ia32_cmpsd(__a, __b, 6);
+  return (__m128d)__builtin_ia32_cmpnlesd(__a, __b);
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpngt_sd(__m128d __a, __m128d __b)
 {
-  __m128d __c = __builtin_ia32_cmpsd(__b, __a, 5);
+  __m128d __c = __builtin_ia32_cmpnltsd(__b, __a);
   return (__m128d) { __c[0], __a[1] };
 }
 
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnge_sd(__m128d __a, __m128d __b)
 {
-  __m128d __c = __builtin_ia32_cmpsd(__b, __a, 6);
+  __m128d __c = __builtin_ia32_cmpnlesd(__b, __a);
   return (__m128d) { __c[0], __a[1] };
 }
 
@@ -489,7 +489,7 @@
 {
   struct __loadu_pd {
     __m128d __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_pd*)__dp)->__v;
 }
 
@@ -825,11 +825,28 @@
   return __a ^ __b;
 }
 
-#define _mm_slli_si128(a, count) __extension__ ({ \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\""); \
-  __m128i __a = (a); \
-   _Pragma("clang diagnostic pop"); \
-  (__m128i)__builtin_ia32_pslldqi128(__a, (count)*8); })
+#define _mm_slli_si128(a, imm) __extension__ ({                         \
+  (__m128i)__builtin_shufflevector((__v16qi)_mm_setzero_si128(),        \
+                                   (__v16qi)(__m128i)(a),               \
+                                   ((imm)&0xF0) ? 0 : 16 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 17 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 18 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 19 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 20 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 21 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 22 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 23 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 24 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 25 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 26 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 27 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 28 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 29 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 30 - ((imm)&0xF), \
+                                   ((imm)&0xF0) ? 0 : 31 - ((imm)&0xF)); })
+
+#define _mm_bslli_si128(a, imm) \
+  _mm_slli_si128((a), (imm))
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_slli_epi16(__m128i __a, int __count)
@@ -891,12 +908,28 @@
   return (__m128i)__builtin_ia32_psrad128((__v4si)__a, (__v4si)__count);
 }
 
+#define _mm_srli_si128(a, imm) __extension__ ({                          \
+  (__m128i)__builtin_shufflevector((__v16qi)(__m128i)(a),                \
+                                   (__v16qi)_mm_setzero_si128(),         \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 0,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 1,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 2,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 3,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 4,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 5,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 6,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 7,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 8,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 9,  \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 10, \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 11, \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 12, \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 13, \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 14, \
+                                   ((imm)&0xF0) ? 16 : ((imm)&0xF) + 15); })
 
-#define _mm_srli_si128(a, count) __extension__ ({ \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\""); \
-  __m128i __a = (a); \
-  _Pragma("clang diagnostic pop"); \
-  (__m128i)__builtin_ia32_psrldqi128(__a, (count)*8); })
+#define _mm_bsrli_si128(a, imm) \
+  _mm_srli_si128((a), (imm))
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_srli_epi16(__m128i __a, int __count)
@@ -1070,7 +1103,7 @@
 {
   struct __loadu_si128 {
     __m128i __v;
-  } __attribute__((packed, may_alias));
+  } __attribute__((__packed__, __may_alias__));
   return ((struct __loadu_si128*)__p)->__v;
 }
 
@@ -1284,27 +1317,21 @@
 }
 
 #define _mm_shuffle_epi32(a, imm) __extension__ ({ \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\""); \
-  __m128i __a = (a); \
-  _Pragma("clang diagnostic pop"); \
-  (__m128i)__builtin_shufflevector((__v4si)__a, (__v4si) _mm_set1_epi32(0), \
+  (__m128i)__builtin_shufflevector((__v4si)(__m128i)(a), \
+                                   (__v4si)_mm_set1_epi32(0), \
                                    (imm) & 0x3, ((imm) & 0xc) >> 2, \
                                    ((imm) & 0x30) >> 4, ((imm) & 0xc0) >> 6); })
 
 #define _mm_shufflelo_epi16(a, imm) __extension__ ({ \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\""); \
-  __m128i __a = (a); \
-  _Pragma("clang diagnostic pop"); \
-  (__m128i)__builtin_shufflevector((__v8hi)__a, (__v8hi) _mm_set1_epi16(0), \
+  (__m128i)__builtin_shufflevector((__v8hi)(__m128i)(a), \
+                                   (__v8hi)_mm_set1_epi16(0), \
                                    (imm) & 0x3, ((imm) & 0xc) >> 2, \
                                    ((imm) & 0x30) >> 4, ((imm) & 0xc0) >> 6, \
                                    4, 5, 6, 7); })
 
 #define _mm_shufflehi_epi16(a, imm) __extension__ ({ \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\""); \
-  __m128i __a = (a); \
-  _Pragma("clang diagnostic pop"); \
-  (__m128i)__builtin_shufflevector((__v8hi)__a, (__v8hi) _mm_set1_epi16(0), \
+  (__m128i)__builtin_shufflevector((__v8hi)(__m128i)(a), \
+                                   (__v8hi)_mm_set1_epi16(0), \
                                    0, 1, 2, 3, \
                                    4 + (((imm) & 0x03) >> 0), \
                                    4 + (((imm) & 0x0c) >> 2), \
@@ -1396,11 +1423,8 @@
 }
 
 #define _mm_shuffle_pd(a, b, i) __extension__ ({ \
-  _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wshadow\""); \
-  __m128d __a = (a); \
-  __m128d __b = (b); \
-  _Pragma("clang diagnostic pop"); \
-  __builtin_shufflevector(__a, __b, (i) & 1, (((i) & 2) >> 1) + 2); })
+  __builtin_shufflevector((__m128d)(a), (__m128d)(b), \
+                          (i) & 1, (((i) & 2) >> 1) + 2); })
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_castpd_ps(__m128d __a)
diff --git a/lib/Headers/module.modulemap b/lib/Headers/module.modulemap
index 3c42477..062464e 100644
--- a/lib/Headers/module.modulemap
+++ b/lib/Headers/module.modulemap
@@ -1,4 +1,4 @@
-module _Builtin_intrinsics [system] {
+module _Builtin_intrinsics [system] [extern_c] {
   explicit module altivec {
     requires altivec
     header "altivec.h"
diff --git a/lib/Headers/shaintrin.h b/lib/Headers/shaintrin.h
index 66ed055..391a4bb 100644
--- a/lib/Headers/shaintrin.h
+++ b/lib/Headers/shaintrin.h
@@ -38,37 +38,37 @@
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_sha1nexte_epu32(__m128i __X, __m128i __Y)
 {
-  return __builtin_ia32_sha1nexte(__X, __Y);
+  return (__m128i)__builtin_ia32_sha1nexte((__v4si)__X, (__v4si)__Y);
 }
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_sha1msg1_epu32(__m128i __X, __m128i __Y)
 {
-  return __builtin_ia32_sha1msg1(__X, __Y);
+  return (__m128i)__builtin_ia32_sha1msg1((__v4si)__X, (__v4si)__Y);
 }
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_sha1msg2_epu32(__m128i __X, __m128i __Y)
 {
-  return __builtin_ia32_sha1msg2(__X, __Y);
+  return (__m128i)__builtin_ia32_sha1msg2((__v4si)__X, (__v4si)__Y);
 }
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_sha256rnds2_epu32(__m128i __X, __m128i __Y, __m128i __Z)
 {
-  return __builtin_ia32_sha256rnds2(__X, __Y, __Z);
+  return (__m128i)__builtin_ia32_sha256rnds2((__v4si)__X, (__v4si)__Y, (__v4si)__Z);
 }
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_sha256msg1_epu32(__m128i __X, __m128i __Y)
 {
-  return __builtin_ia32_sha256msg1(__X, __Y);
+  return (__m128i)__builtin_ia32_sha256msg1((__v4si)__X, (__v4si)__Y);
 }
 
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_sha256msg2_epu32(__m128i __X, __m128i __Y)
 {
-  return __builtin_ia32_sha256msg2(__X, __Y);
+  return (__m128i)__builtin_ia32_sha256msg2((__v4si)__X, (__v4si)__Y);
 }
 
 #endif /* __SHAINTRIN_H */
diff --git a/lib/Headers/stdatomic.h b/lib/Headers/stdatomic.h
index e3c3476..e037987 100644
--- a/lib/Headers/stdatomic.h
+++ b/lib/Headers/stdatomic.h
@@ -71,7 +71,7 @@
 
 /* 7.17.4 Fences */
 
-// These should be provided by the libc implementation.
+/* These should be provided by the libc implementation. */
 void atomic_thread_fence(memory_order);
 void atomic_signal_fence(memory_order);
 
@@ -164,7 +164,7 @@
 
 #define ATOMIC_FLAG_INIT { 0 }
 
-// These should be provided by the libc implementation.
+/* These should be provided by the libc implementation. */
 #ifdef __cplusplus
 bool atomic_flag_test_and_set(volatile atomic_flag *);
 bool atomic_flag_test_and_set_explicit(volatile atomic_flag *, memory_order);
diff --git a/lib/Headers/unwind.h b/lib/Headers/unwind.h
index 685c1df..303d792 100644
--- a/lib/Headers/unwind.h
+++ b/lib/Headers/unwind.h
@@ -26,8 +26,8 @@
 #ifndef __CLANG_UNWIND_H
 #define __CLANG_UNWIND_H
 
-#if __has_include_next(<unwind.h>)
-/* Darwin (from 11.x on) and libunwind provide an unwind.h. If that's available,
+#if defined(__APPLE__) && __has_include_next(<unwind.h>)
+/* Darwin (from 11.x on) provide an unwind.h. If that's available,
  * use it. libunwind wraps some of its definitions in #ifdef _GNU_SOURCE,
  * so define that around the include.*/
 # ifndef _GNU_SOURCE
@@ -199,6 +199,8 @@
 
 _Unwind_Word _Unwind_GetCFA(struct _Unwind_Context *);
 
+_Unwind_Word _Unwind_GetBSP(struct _Unwind_Context *);
+
 void *_Unwind_GetLanguageSpecificData(struct _Unwind_Context *);
 
 _Unwind_Ptr _Unwind_GetRegionStart(struct _Unwind_Context *);
@@ -233,9 +235,9 @@
 #ifdef __APPLE__
 
 _Unwind_Ptr _Unwind_GetDataRelBase(struct _Unwind_Context *)
-    __attribute__((unavailable));
+    __attribute__((__unavailable__));
 _Unwind_Ptr _Unwind_GetTextRelBase(struct _Unwind_Context *)
-    __attribute__((unavailable));
+    __attribute__((__unavailable__));
 
 /* Darwin-specific functions */
 void __register_frame(const void *);
@@ -249,15 +251,15 @@
 void *_Unwind_Find_FDE(const void *, struct dwarf_eh_bases *);
 
 void __register_frame_info_bases(const void *, void *, void *, void *)
-  __attribute__((unavailable));
-void __register_frame_info(const void *, void *) __attribute__((unavailable));
+  __attribute__((__unavailable__));
+void __register_frame_info(const void *, void *) __attribute__((__unavailable__));
 void __register_frame_info_table_bases(const void *, void*, void *, void *)
-  __attribute__((unavailable));
+  __attribute__((__unavailable__));
 void __register_frame_info_table(const void *, void *)
-  __attribute__((unavailable));
-void __register_frame_table(const void *) __attribute__((unavailable));
-void __deregister_frame_info(const void *) __attribute__((unavailable));
-void __deregister_frame_info_bases(const void *)__attribute__((unavailable));
+  __attribute__((__unavailable__));
+void __register_frame_table(const void *) __attribute__((__unavailable__));
+void __deregister_frame_info(const void *) __attribute__((__unavailable__));
+void __deregister_frame_info_bases(const void *)__attribute__((__unavailable__));
 
 #else
 
diff --git a/lib/Headers/xmmintrin.h b/lib/Headers/xmmintrin.h
index c9befcb..d1afe81 100644
--- a/lib/Headers/xmmintrin.h
+++ b/lib/Headers/xmmintrin.h
@@ -182,153 +182,153 @@
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 0);
+  return (__m128)__builtin_ia32_cmpeqss(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 0);
+  return (__m128)__builtin_ia32_cmpeqps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmplt_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 1);
+  return (__m128)__builtin_ia32_cmpltss(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmplt_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 1);
+  return (__m128)__builtin_ia32_cmpltps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmple_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 2);
+  return (__m128)__builtin_ia32_cmpless(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmple_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 2);
+  return (__m128)__builtin_ia32_cmpleps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpgt_ss(__m128 __a, __m128 __b)
 {
   return (__m128)__builtin_shufflevector(__a,
-                                         __builtin_ia32_cmpss(__b, __a, 1),
+                                         __builtin_ia32_cmpltss(__b, __a),
                                          4, 1, 2, 3);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpgt_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__b, __a, 1);
+  return (__m128)__builtin_ia32_cmpltps(__b, __a);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpge_ss(__m128 __a, __m128 __b)
 {
   return (__m128)__builtin_shufflevector(__a,
-                                         __builtin_ia32_cmpss(__b, __a, 2),
+                                         __builtin_ia32_cmpless(__b, __a),
                                          4, 1, 2, 3);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpge_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__b, __a, 2);
+  return (__m128)__builtin_ia32_cmpleps(__b, __a);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpneq_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 4);
+  return (__m128)__builtin_ia32_cmpneqss(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpneq_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 4);
+  return (__m128)__builtin_ia32_cmpneqps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnlt_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 5);
+  return (__m128)__builtin_ia32_cmpnltss(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnlt_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 5);
+  return (__m128)__builtin_ia32_cmpnltps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnle_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 6);
+  return (__m128)__builtin_ia32_cmpnless(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnle_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 6);
+  return (__m128)__builtin_ia32_cmpnleps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpngt_ss(__m128 __a, __m128 __b)
 {
   return (__m128)__builtin_shufflevector(__a,
-                                         __builtin_ia32_cmpss(__b, __a, 5),
+                                         __builtin_ia32_cmpnltss(__b, __a),
                                          4, 1, 2, 3);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpngt_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__b, __a, 5);
+  return (__m128)__builtin_ia32_cmpnltps(__b, __a);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnge_ss(__m128 __a, __m128 __b)
 {
   return (__m128)__builtin_shufflevector(__a,
-                                         __builtin_ia32_cmpss(__b, __a, 6),
+                                         __builtin_ia32_cmpnless(__b, __a),
                                          4, 1, 2, 3);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpnge_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__b, __a, 6);
+  return (__m128)__builtin_ia32_cmpnleps(__b, __a);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpord_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 7);
+  return (__m128)__builtin_ia32_cmpordss(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpord_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 7);
+  return (__m128)__builtin_ia32_cmpordps(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpunord_ss(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpss(__a, __b, 3);
+  return (__m128)__builtin_ia32_cmpunordss(__a, __b);
 }
 
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_cmpunord_ps(__m128 __a, __m128 __b)
 {
-  return (__m128)__builtin_ia32_cmpps(__a, __b, 3);
+  return (__m128)__builtin_ia32_cmpunordps(__a, __b);
 }
 
 static __inline__ int __attribute__((__always_inline__, __nodebug__))
diff --git a/lib/Index/USRGeneration.cpp b/lib/Index/USRGeneration.cpp
index e08b85e..baa166e 100644
--- a/lib/Index/USRGeneration.cpp
+++ b/lib/Index/USRGeneration.cpp
@@ -198,7 +198,9 @@
     return;
 
   VisitDeclContext(D->getDeclContext());
+  bool IsTemplate = false;
   if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
+    IsTemplate = true;
     Out << "@FT@";
     VisitTemplateParameterList(FunTmpl->getTemplateParameters());
   } else
@@ -226,12 +228,26 @@
   }
   if (D->isVariadic())
     Out << '.';
+  if (IsTemplate) {
+    // Function templates can be overloaded by return type, for example:
+    // \code
+    //   template <class T> typename T::A foo() {}
+    //   template <class T> typename T::B foo() {}
+    // \endcode
+    Out << '#';
+    VisitType(D->getReturnType());
+  }
   Out << '#';
   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
     if (MD->isStatic())
       Out << 'S';
     if (unsigned quals = MD->getTypeQualifiers())
       Out << (char)('0' + quals);
+    switch (MD->getRefQualifier()) {
+    case RQ_None: break;
+    case RQ_LValue: Out << '&'; break;
+    case RQ_RValue: Out << "&&"; break;
+    }
   }
 }
 
@@ -414,8 +430,8 @@
       
       switch (D->getTagKind()) {
       case TTK_Interface:
+      case TTK_Class:
       case TTK_Struct: Out << "@ST"; break;
-      case TTK_Class:  Out << "@CT"; break;
       case TTK_Union:  Out << "@UT"; break;
       case TTK_Enum: llvm_unreachable("enum template");
       }
@@ -426,8 +442,8 @@
       
       switch (D->getTagKind()) {
       case TTK_Interface:
+      case TTK_Class:
       case TTK_Struct: Out << "@SP"; break;
-      case TTK_Class:  Out << "@CP"; break;
       case TTK_Union:  Out << "@UP"; break;
       case TTK_Enum: llvm_unreachable("enum partial specialization");
       }      
@@ -438,8 +454,8 @@
   if (!AlreadyStarted) {
     switch (D->getTagKind()) {
       case TTK_Interface:
+      case TTK_Class:
       case TTK_Struct: Out << "@S"; break;
-      case TTK_Class:  Out << "@C"; break;
       case TTK_Union:  Out << "@U"; break;
       case TTK_Enum:   Out << "@E"; break;
     }
@@ -455,9 +471,13 @@
       Buf[off] = 'A';
       Out << '@' << *TD;
     }
-    else
+  else {
+    if (D->isEmbeddedInDeclarator() && !D->isFreeStanding()) {
+      printLoc(Out, D->getLocation(), Context->getSourceManager(), true);
+    } else
       Buf[off] = 'a';
   }
+  }
   
   // For a class template specialization, mangle the template arguments.
   if (const ClassTemplateSpecializationDecl *Spec
@@ -540,7 +560,6 @@
           c = 'v'; break;
         case BuiltinType::Bool:
           c = 'b'; break;
-        case BuiltinType::Char_U:
         case BuiltinType::UChar:
           c = 'c'; break;
         case BuiltinType::Char16:
@@ -557,9 +576,11 @@
           c = 'k'; break;
         case BuiltinType::UInt128:
           c = 'j'; break;
+        case BuiltinType::Char_U:
         case BuiltinType::Char_S:
-        case BuiltinType::SChar:
           c = 'C'; break;
+        case BuiltinType::SChar:
+          c = 'r'; break;
         case BuiltinType::WChar_S:
         case BuiltinType::WChar_U:
           c = 'W'; break;
@@ -626,6 +647,11 @@
       T = PT->getPointeeType();
       continue;
     }
+    if (const RValueReferenceType *RT = T->getAs<RValueReferenceType>()) {
+      Out << "&&";
+      T = RT->getPointeeType();
+      continue;
+    }
     if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
       Out << '&';
       T = RT->getPointeeType();
@@ -668,6 +694,22 @@
         VisitTemplateArgument(Spec->getArg(I));
       return;
     }
+    if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
+      Out << '^';
+      // FIXME: Encode the qualifier, don't just print it.
+      PrintingPolicy PO(Ctx.getLangOpts());
+      PO.SuppressTagKeyword = true;
+      PO.SuppressUnwrittenScope = true;
+      PO.ConstantArraySizeAsWritten = false;
+      PO.AnonymousTagLocations = false;
+      DNT->getQualifier()->print(Out, PO);
+      Out << ':' << DNT->getIdentifier()->getName();
+      return;
+    }
+    if (const InjectedClassNameType *InjT = T->getAs<InjectedClassNameType>()) {
+      T = InjT->getInjectedSpecializationType();
+      continue;
+    }
     
     // Unhandled type.
     Out << ' ';
diff --git a/lib/Lex/HeaderSearch.cpp b/lib/Lex/HeaderSearch.cpp
index 6345e75..b94cdbd 100644
--- a/lib/Lex/HeaderSearch.cpp
+++ b/lib/Lex/HeaderSearch.cpp
@@ -50,7 +50,8 @@
                            const LangOptions &LangOpts,
                            const TargetInfo *Target)
     : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
-      FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this) {
+      FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
+      LangOpts(LangOpts) {
   AngledDirIdx = 0;
   SystemDirIdx = 0;
   NoCurDirSearch = false;
@@ -60,8 +61,6 @@
   NumIncluded = 0;
   NumMultiIncludeFileOptzn = 0;
   NumFrameworkLookups = NumSubFrameworkLookups = 0;
-
-  EnabledModules = LangOpts.Modules;
 }
 
 HeaderSearch::~HeaderSearch() {
@@ -132,15 +131,24 @@
     llvm::sys::path::append(Result, ModuleName + ".pcm");
   } else {
     // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
-    // be globally unique to this particular module. To avoid false-negatives
-    // on case-insensitive filesystems, we use lower-case, which is safe because
-    // to cause a collision the modules must have the same name, which is an
-    // error if they are imported in the same translation.
-    SmallString<256> AbsModuleMapPath(ModuleMapPath);
-    llvm::sys::fs::make_absolute(AbsModuleMapPath);
-    llvm::APInt Code(64, llvm::hash_value(AbsModuleMapPath.str().lower()));
+    // ideally be globally unique to this particular module. Name collisions
+    // in the hash are safe (because any translation unit can only import one
+    // module with each name), but result in a loss of caching.
+    //
+    // To avoid false-negatives, we form as canonical a path as we can, and map
+    // to lower-case in case we're on a case-insensitive file system.
+   auto *Dir =
+        FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
+    if (!Dir)
+      return std::string();
+    auto DirName = FileMgr.getCanonicalName(Dir);
+    auto FileName = llvm::sys::path::filename(ModuleMapPath);
+
+    llvm::hash_code Hash =
+        llvm::hash_combine(DirName.lower(), FileName.lower());
+
     SmallString<128> HashStr;
-    Code.toStringUnsigned(HashStr, /*Radix*/36);
+    llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
     llvm::sys::path::append(Result, ModuleName + "-" + HashStr.str() + ".pcm");
   }
   return Result.str().str();
@@ -149,7 +157,7 @@
 Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
   // Look in the module map to determine if there is a module by this name.
   Module *Module = ModMap.findModule(ModuleName);
-  if (Module || !AllowSearch)
+  if (Module || !AllowSearch || !LangOpts.ModulesImplicitMaps)
     return Module;
   
   // Look through the various header search paths to load any available module
@@ -569,18 +577,6 @@
     ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
     SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
     ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
-  if (!HSOpts->ModuleMapFiles.empty()) {
-    // Preload all explicitly specified module map files. This enables modules
-    // map files lying in a directory structure separate from the header files
-    // that they describe. These cannot be loaded lazily upon encountering a
-    // header file, as there is no other known mapping from a header file to its
-    // module map file.
-    for (const auto &Filename : HSOpts->ModuleMapFiles)
-      if (const FileEntry *File = FileMgr.getFile(Filename))
-        loadModuleMapFile(File, /*IsSystem=*/false);
-    HSOpts->ModuleMapFiles.clear();
-  }
-
   if (SuggestedModule)
     *SuggestedModule = ModuleMap::KnownHeader();
     
@@ -625,11 +621,20 @@
       // FIXME: We don't cache the result of getFileInfo across the call to
       // getFileAndSuggestModule, because it's a reference to an element of
       // a container that could be reallocated across this call.
+      //
+      // FIXME: If we have no includer, that means we're processing a #include
+      // from a module build. We should treat this as a system header if we're
+      // building a [system] module.
       bool IncluderIsSystemHeader =
-          getFileInfo(Includer).DirInfo != SrcMgr::C_User;
+          Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
       if (const FileEntry *FE = getFileAndSuggestModule(
               *this, TmpDir.str(), IncluderAndDir.second,
               IncluderIsSystemHeader, SuggestedModule)) {
+        if (!Includer) {
+          assert(First && "only first includer can have no file");
+          return FE;
+        }
+
         // Leave CurDir unset.
         // This file is a system header or C++ unfriendly if the old file is.
         //
@@ -771,7 +776,7 @@
   // a header in a framework that is currently being built, and we couldn't
   // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
   // "Foo" is the name of the framework in which the including header was found.
-  if (!Includers.empty() && !isAngled &&
+  if (!Includers.empty() && Includers.front().first && !isAngled &&
       Filename.find('/') == StringRef::npos) {
     HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
     if (IncludingHFI.IndexHeaderMapHeader) {
@@ -1062,7 +1067,7 @@
 bool HeaderSearch::hasModuleMap(StringRef FileName, 
                                 const DirectoryEntry *Root,
                                 bool IsSystem) {
-  if (!enabledModules())
+  if (!enabledModules() || !LangOpts.ModulesImplicitMaps)
     return false;
 
   SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
@@ -1080,7 +1085,9 @@
       return false;
 
     // Try to load the module map file in this directory.
-    switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/false)) {
+    switch (loadModuleMapFile(Dir, IsSystem,
+                              llvm::sys::path::extension(Dir->getName()) ==
+                                  ".framework")) {
     case LMM_NewlyLoaded:
     case LMM_AlreadyLoaded:
       // Success. All of the directories we stepped through inherit this module
@@ -1114,11 +1121,10 @@
   return ModMap.findModuleForHeader(File);
 }
 
-static const FileEntry *getPrivateModuleMap(StringRef ModuleMapPath,
-                                            const DirectoryEntry *Directory,
+static const FileEntry *getPrivateModuleMap(const FileEntry *File,
                                             FileManager &FileMgr) {
-  StringRef Filename = llvm::sys::path::filename(ModuleMapPath);
-  SmallString<128>  PrivateFilename(Directory->getName());
+  StringRef Filename = llvm::sys::path::filename(File->getName());
+  SmallString<128>  PrivateFilename(File->getDir()->getName());
   if (Filename == "module.map")
     llvm::sys::path::append(PrivateFilename, "module_private.map");
   else if (Filename == "module.modulemap")
@@ -1129,7 +1135,25 @@
 }
 
 bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
-  switch (loadModuleMapFileImpl(File, IsSystem)) {
+  // Find the directory for the module. For frameworks, that may require going
+  // up from the 'Modules' directory.
+  const DirectoryEntry *Dir = nullptr;
+  if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
+    Dir = FileMgr.getDirectory(".");
+  else {
+    Dir = File->getDir();
+    StringRef DirName(Dir->getName());
+    if (llvm::sys::path::filename(DirName) == "Modules") {
+      DirName = llvm::sys::path::parent_path(DirName);
+      if (DirName.endswith(".framework"))
+        Dir = FileMgr.getDirectory(DirName);
+      // FIXME: This assert can fail if there's a race between the above check
+      // and the removal of the directory.
+      assert(Dir && "parent must exist");
+    }
+  }
+
+  switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
   case LMM_AlreadyLoaded:
   case LMM_NewlyLoaded:
     return false;
@@ -1141,7 +1165,8 @@
 }
 
 HeaderSearch::LoadModuleMapResult
-HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem) {
+HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
+                                    const DirectoryEntry *Dir) {
   assert(File && "expected FileEntry");
 
   // Check whether we've already loaded this module map, and mark it as being
@@ -1150,15 +1175,14 @@
   if (!AddResult.second)
     return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
 
-  if (ModMap.parseModuleMapFile(File, IsSystem)) {
+  if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
     LoadedModuleMaps[File] = false;
     return LMM_InvalidModuleMap;
   }
 
   // Try to load a corresponding private module map.
-  if (const FileEntry *PMMFile =
-          getPrivateModuleMap(File->getName(), File->getDir(), FileMgr)) {
-    if (ModMap.parseModuleMapFile(PMMFile, IsSystem)) {
+  if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
+    if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
       LoadedModuleMaps[File] = false;
       return LMM_InvalidModuleMap;
     }
@@ -1170,6 +1194,8 @@
 
 const FileEntry *
 HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
+  if (!LangOpts.ModulesImplicitMaps)
+    return nullptr;
   // For frameworks, the preferred spelling is Modules/module.modulemap, but
   // module.map at the framework root is also accepted.
   SmallString<128> ModuleMapFileName(Dir->getName());
@@ -1190,12 +1216,12 @@
                                           bool IsSystem) {
   if (Module *Module = ModMap.findModule(Name))
     return Module;
-  
+
   // Try to load a module map file.
   switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
   case LMM_InvalidModuleMap:
     break;
-    
+
   case LMM_AlreadyLoaded:
   case LMM_NoDirectory:
     return nullptr;
@@ -1206,7 +1232,10 @@
 
 
   // Try to infer a module map from the framework directory.
-  return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
+  if (LangOpts.ModulesImplicitMaps)
+    return ModMap.inferFrameworkModule(Name, Dir, IsSystem, /*Parent=*/nullptr);
+
+  return nullptr;
 }
 
 
@@ -1227,7 +1256,8 @@
     return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
 
   if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
-    LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem);
+    LoadModuleMapResult Result =
+        loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
     // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
     // E.g. Foo.framework/Modules/module.modulemap
     //      ^Dir                  ^ModuleMapFile
@@ -1242,45 +1272,49 @@
 
 void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
   Modules.clear();
-  
-  // Load module maps for each of the header search directories.
-  for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
-    bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
-    if (SearchDirs[Idx].isFramework()) {
-      std::error_code EC;
-      SmallString<128> DirNative;
-      llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
-                              DirNative);
-      
-      // Search each of the ".framework" directories to load them as modules.
-      for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
-           Dir != DirEnd && !EC; Dir.increment(EC)) {
-        if (llvm::sys::path::extension(Dir->path()) != ".framework")
-          continue;
-        
-        const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path());
-        if (!FrameworkDir)
-          continue;
-        
-        // Load this framework module.
-        loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
-                            IsSystem);
+
+  if (LangOpts.ModulesImplicitMaps) {
+    // Load module maps for each of the header search directories.
+    for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
+      bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
+      if (SearchDirs[Idx].isFramework()) {
+        std::error_code EC;
+        SmallString<128> DirNative;
+        llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
+                                DirNative);
+
+        // Search each of the ".framework" directories to load them as modules.
+        for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
+             Dir != DirEnd && !EC; Dir.increment(EC)) {
+          if (llvm::sys::path::extension(Dir->path()) != ".framework")
+            continue;
+
+          const DirectoryEntry *FrameworkDir =
+              FileMgr.getDirectory(Dir->path());
+          if (!FrameworkDir)
+            continue;
+
+          // Load this framework module.
+          loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
+                              IsSystem);
+        }
+        continue;
       }
-      continue;
+
+      // FIXME: Deal with header maps.
+      if (SearchDirs[Idx].isHeaderMap())
+        continue;
+
+      // Try to load a module map file for the search directory.
+      loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
+                        /*IsFramework*/ false);
+
+      // Try to load module map files for immediate subdirectories of this
+      // search directory.
+      loadSubdirectoryModuleMaps(SearchDirs[Idx]);
     }
-    
-    // FIXME: Deal with header maps.
-    if (SearchDirs[Idx].isHeaderMap())
-      continue;
-    
-    // Try to load a module map file for the search directory.
-    loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, /*IsFramework*/false);
-    
-    // Try to load module map files for immediate subdirectories of this search
-    // directory.
-    loadSubdirectoryModuleMaps(SearchDirs[Idx]);
   }
-  
+
   // Populate the list of modules.
   for (ModuleMap::module_iterator M = ModMap.module_begin(), 
                                MEnd = ModMap.module_end();
@@ -1290,6 +1324,9 @@
 }
 
 void HeaderSearch::loadTopLevelSystemModules() {
+  if (!LangOpts.ModulesImplicitMaps)
+    return;
+
   // Load module maps for each of the header search directories.
   for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
     // We only care about normal header directories.
@@ -1305,6 +1342,9 @@
 }
 
 void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
+  assert(LangOpts.ModulesImplicitMaps &&
+         "Should not be loading subdirectory module maps");
+
   if (SearchDir.haveSearchedAllModuleMaps())
     return;
 
@@ -1313,8 +1353,10 @@
   llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
   for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
        Dir != DirEnd && !EC; Dir.increment(EC)) {
-    loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
-                      SearchDir.isFramework());
+    bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
+    if (IsFramework == SearchDir.isFramework())
+      loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
+                        SearchDir.isFramework());
   }
 
   SearchDir.setSearchedAllModuleMaps(true);
diff --git a/lib/Lex/Lexer.cpp b/lib/Lex/Lexer.cpp
index c2e9716..ca5252e 100644
--- a/lib/Lex/Lexer.cpp
+++ b/lib/Lex/Lexer.cpp
@@ -2588,8 +2588,8 @@
   size_t Pos = RestOfBuffer.find(Terminator);
   while (Pos != StringRef::npos) {
     // Must occur at start of line.
-    if (RestOfBuffer[Pos-1] != '\r' &&
-        RestOfBuffer[Pos-1] != '\n') {
+    if (Pos == 0 ||
+        (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
       RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
       Pos = RestOfBuffer.find(Terminator);
       continue;
diff --git a/lib/Lex/ModuleMap.cpp b/lib/Lex/ModuleMap.cpp
index 6a470ef..0bb9856 100644
--- a/lib/Lex/ModuleMap.cpp
+++ b/lib/Lex/ModuleMap.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Lex/HeaderSearch.h"
+#include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/LiteralSupport.h"
@@ -88,7 +89,9 @@
                      HeaderSearch &HeaderInfo)
     : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
       HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr),
-      CompilingModule(nullptr), SourceModule(nullptr) {}
+      CompilingModule(nullptr), SourceModule(nullptr) {
+  MMapLangOpts.LineComment = true;
+}
 
 ModuleMap::~ModuleMap() {
   for (llvm::StringMap<Module *>::iterator I = Modules.begin(), 
@@ -220,12 +223,14 @@
   // as obtained from the lookup and as obtained from the module.
   // This check is not cheap, so enable it only for debugging.
   bool IsPrivate = false;
-  SmallVectorImpl<const FileEntry *> *HeaderList[] =
-      {&RequestedModule->PrivateHeaders,
-       &RequestedModule->PrivateTextualHeaders};
+  SmallVectorImpl<Module::Header> *HeaderList[] =
+      {&RequestedModule->Headers[Module::HK_Private],
+       &RequestedModule->Headers[Module::HK_PrivateTextual]};
   for (auto *Hdrs : HeaderList)
     IsPrivate |=
-        std::find(Hdrs->begin(), Hdrs->end(), IncFileEnt) != Hdrs->end();
+        std::find_if(Hdrs->begin(), Hdrs->end(), [&](const Module::Header &H) {
+          return H.Entry == IncFileEnt;
+        }) != Hdrs->end();
   assert(IsPrivate == IsPrivateRole && "inconsistent headers and roles");
 #endif
   return IsPrivateRole &&
@@ -283,14 +288,14 @@
 
   // We have found a header, but it is private.
   if (Private) {
-    Diags.Report(FilenameLoc, diag::error_use_of_private_header_outside_module)
+    Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
         << Filename;
     return;
   }
 
   // We have found a module, but we don't use it.
   if (NotUsed) {
-    Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
+    Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
         << RequestingModule->getFullModuleName() << Filename;
     return;
   }
@@ -301,7 +306,7 @@
   // At this point, only non-modular includes remain.
 
   if (LangOpts.ModulesStrictDeclUse) {
-    Diags.Report(FilenameLoc, diag::error_undeclared_use_of_module)
+    Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
         << RequestingModule->getFullModuleName() << Filename;
   } else if (RequestingModule) {
     diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
@@ -311,6 +316,22 @@
   }
 }
 
+static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
+                                const ModuleMap::KnownHeader &Old) {
+  // Prefer a public header over a private header.
+  if ((New.getRole() & ModuleMap::PrivateHeader) !=
+      (Old.getRole() & ModuleMap::PrivateHeader))
+    return !(New.getRole() & ModuleMap::PrivateHeader);
+
+  // Prefer a non-textual header over a textual header.
+  if ((New.getRole() & ModuleMap::TextualHeader) !=
+      (Old.getRole() & ModuleMap::TextualHeader))
+    return !(New.getRole() & ModuleMap::TextualHeader);
+
+  // Don't have a reason to choose between these. Just keep the first one.
+  return false;
+}
+
 ModuleMap::KnownHeader
 ModuleMap::findModuleForHeader(const FileEntry *File,
                                Module *RequestingModule,
@@ -345,8 +366,7 @@
           !directlyUses(RequestingModule, I->getModule()))
         continue;
 
-      // Prefer a public header over a private header.
-      if (!Result || (Result.getRole() & ModuleMap::PrivateHeader))
+      if (!Result || isBetterKnownHeader(*I, Result))
         Result = *I;
     }
     return MakeResult(Result);
@@ -560,30 +580,6 @@
   return std::make_pair(Result, true);
 }
 
-bool ModuleMap::canInferFrameworkModule(const DirectoryEntry *ParentDir,
-                                        StringRef Name, bool &IsSystem) const {
-  // Check whether we have already looked into the parent directory
-  // for a module map.
-  llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
-    inferred = InferredDirectories.find(ParentDir);
-  if (inferred == InferredDirectories.end())
-    return false;
-
-  if (!inferred->second.InferModules)
-    return false;
-
-  // We're allowed to infer for this directory, but make sure it's okay
-  // to infer this particular module.
-  bool canInfer = std::find(inferred->second.ExcludedModules.begin(),
-                            inferred->second.ExcludedModules.end(),
-                            Name) == inferred->second.ExcludedModules.end();
-
-  if (canInfer && inferred->second.InferSystemModules)
-    IsSystem = true;
-
-  return canInfer;
-}
-
 /// \brief For a framework module, infer the framework against which we
 /// should link.
 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
@@ -606,6 +602,15 @@
                                 const DirectoryEntry *FrameworkDir,
                                 bool IsSystem,
                                 Module *Parent) {
+  Attributes Attrs;
+  Attrs.IsSystem = IsSystem;
+  return inferFrameworkModule(ModuleName, FrameworkDir, Attrs, Parent);
+}
+
+Module *ModuleMap::inferFrameworkModule(StringRef ModuleName,
+                                        const DirectoryEntry *FrameworkDir,
+                                        Attributes Attrs, Module *Parent) {
+
   // Check whether we've already found this module.
   if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
     return Mod;
@@ -646,7 +651,7 @@
           bool IsFrameworkDir = Parent.endswith(".framework");
           if (const FileEntry *ModMapFile =
                 HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
-            parseModuleMapFile(ModMapFile, IsSystem);
+            parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
             inferred = InferredDirectories.find(ParentDir);
           }
 
@@ -663,8 +668,9 @@
                                inferred->second.ExcludedModules.end(),
                                Name) == inferred->second.ExcludedModules.end();
 
-          if (inferred->second.InferSystemModules)
-            IsSystem = true;
+          Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
+          Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
+          Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
           ModuleMapFile = inferred->second.ModuleMapFile;
         }
       }
@@ -696,9 +702,11 @@
     SourceModule = Result;
     SourceModuleName = ModuleName;
   }
-  if (IsSystem)
-    Result->IsSystem = IsSystem;
-  
+
+  Result->IsSystem |= Attrs.IsSystem;
+  Result->IsExternC |= Attrs.IsExternC;
+  Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
+
   if (!Parent)
     Modules[ModuleName] = Result;
   
@@ -753,8 +761,8 @@
       // FIXME: Do we want to warn about subframeworks without umbrella headers?
       SmallString<32> NameBuf;
       inferFrameworkModule(sanitizeFilenameAsIdentifier(
-                             llvm::sys::path::stem(Dir->path()), NameBuf),
-                           SubframeworkDir, IsSystem, Result);
+                               llvm::sys::path::stem(Dir->path()), NameBuf),
+                           SubframeworkDir, Attrs, Result);
     }
   }
 
@@ -778,40 +786,40 @@
   UmbrellaDirs[UmbrellaDir] = Mod;
 }
 
-void ModuleMap::addHeader(Module *Mod, const FileEntry *Header,
-                          ModuleHeaderRole Role) {
+static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) {
   switch ((int)Role) {
-  default:
-    llvm_unreachable("unknown header role");
-  case NormalHeader:
-    Mod->NormalHeaders.push_back(Header);
-    break;
-  case PrivateHeader:
-    Mod->PrivateHeaders.push_back(Header);
-    break;
-  case TextualHeader:
-    Mod->TextualHeaders.push_back(Header);
-    break;
-  case PrivateHeader | TextualHeader:
-    Mod->PrivateTextualHeaders.push_back(Header);
-    break;
+  default: llvm_unreachable("unknown header role");
+  case ModuleMap::NormalHeader:
+    return Module::HK_Normal;
+  case ModuleMap::PrivateHeader:
+    return Module::HK_Private;
+  case ModuleMap::TextualHeader:
+    return Module::HK_Textual;
+  case ModuleMap::PrivateHeader | ModuleMap::TextualHeader:
+    return Module::HK_PrivateTextual;
   }
-
-  if (!(Role & TextualHeader)) {
-    bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
-    HeaderInfo.MarkFileModuleHeader(Header, Role, isCompilingModuleHeader);
-  }
-  Headers[Header].push_back(KnownHeader(Mod, Role));
 }
 
-void ModuleMap::excludeHeader(Module *Mod, const FileEntry *Header) {
-  Mod->ExcludedHeaders.push_back(Header);
+void ModuleMap::addHeader(Module *Mod, Module::Header Header,
+                          ModuleHeaderRole Role) {
+  if (!(Role & TextualHeader)) {
+    bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule;
+    HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
+                                    isCompilingModuleHeader);
+  }
+  Headers[Header.Entry].push_back(KnownHeader(Mod, Role));
 
+  Mod->Headers[headerRoleToKind(Role)].push_back(std::move(Header));
+}
+
+void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) {
   // Add this as a known header so we won't implicitly add it to any
   // umbrella directory module.
   // FIXME: Should we only exclude it from umbrella modules within the
   // specified module?
-  (void) Headers[Header];
+  (void) Headers[Header.Entry];
+
+  Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
 }
 
 const FileEntry *
@@ -993,21 +1001,6 @@
     }
   };
 
-  /// \brief The set of attributes that can be attached to a module.
-  struct Attributes {
-    Attributes() : IsSystem(), IsExternC(), IsExhaustive() { }
-
-    /// \brief Whether this is a system module.
-    unsigned IsSystem : 1;
-
-    /// \brief Whether this is an extern "C" module.
-    unsigned IsExternC : 1;
-
-    /// \brief Whether this is an exhaustive set of configuration macros.
-    unsigned IsExhaustive : 1;
-  };
-  
-
   class ModuleMapParser {
     Lexer &L;
     SourceManager &SourceMgr;
@@ -1022,7 +1015,8 @@
     /// \brief The current module map file.
     const FileEntry *ModuleMapFile;
     
-    /// \brief The directory that this module map resides in.
+    /// \brief The directory that file names in this module map file should
+    /// be resolved relative to.
     const DirectoryEntry *Directory;
 
     /// \brief The directory containing Clang-supplied headers.
@@ -1065,6 +1059,8 @@
     void parseConfigMacros();
     void parseConflict();
     void parseInferredModuleDecl(bool Framework, bool Explicit);
+
+    typedef ModuleMap::Attributes Attributes;
     bool parseOptionalAttributes(Attributes &Attrs);
     
   public:
@@ -1447,6 +1443,7 @@
     ActiveModule->IsSystem = true;
   if (Attrs.IsExternC)
     ActiveModule->IsExternC = true;
+  ActiveModule->Directory = Directory;
 
   bool Done = false;
   do {
@@ -1588,7 +1585,11 @@
     FileNameRef = ModuleMapFileName.str();
   }
   if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
-    Map.parseModuleMapFile(File, /*IsSystem=*/false);
+    Map.parseModuleMapFile(
+        File, /*IsSystem=*/false,
+        Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
+            ? Directory
+            : File->getDir());
 }
 
 /// \brief Parse a requires declaration.
@@ -1699,7 +1700,7 @@
     HadError = true;
     return;
   }
-  Module::HeaderDirective Header;
+  Module::UnresolvedHeaderDirective Header;
   Header.FileName = Tok.getString();
   Header.FileNameLoc = consumeToken();
   
@@ -1714,33 +1715,39 @@
   // Look for this file.
   const FileEntry *File = nullptr;
   const FileEntry *BuiltinFile = nullptr;
-  SmallString<128> PathName;
+  SmallString<128> RelativePathName;
   if (llvm::sys::path::is_absolute(Header.FileName)) {
-    PathName = Header.FileName;
-    File = SourceMgr.getFileManager().getFile(PathName);
+    RelativePathName = Header.FileName;
+    File = SourceMgr.getFileManager().getFile(RelativePathName);
   } else {
     // Search for the header file within the search directory.
-    PathName = Directory->getName();
-    unsigned PathLength = PathName.size();
+    SmallString<128> FullPathName(Directory->getName());
+    unsigned FullPathLength = FullPathName.size();
     
     if (ActiveModule->isPartOfFramework()) {
-      appendSubframeworkPaths(ActiveModule, PathName);
+      appendSubframeworkPaths(ActiveModule, RelativePathName);
       
       // Check whether this file is in the public headers.
-      llvm::sys::path::append(PathName, "Headers", Header.FileName);
-      File = SourceMgr.getFileManager().getFile(PathName);
+      llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
+      llvm::sys::path::append(FullPathName, RelativePathName.str());
+      File = SourceMgr.getFileManager().getFile(FullPathName);
       
       if (!File) {
         // Check whether this file is in the private headers.
-        PathName.resize(PathLength);
-        llvm::sys::path::append(PathName, "PrivateHeaders", Header.FileName);
-        File = SourceMgr.getFileManager().getFile(PathName);
+        // FIXME: Should we retain the subframework paths here?
+        RelativePathName.clear();
+        FullPathName.resize(FullPathLength);
+        llvm::sys::path::append(RelativePathName, "PrivateHeaders",
+                                Header.FileName);
+        llvm::sys::path::append(FullPathName, RelativePathName.str());
+        File = SourceMgr.getFileManager().getFile(FullPathName);
       }
     } else {
       // Lookup for normal headers.
-      llvm::sys::path::append(PathName, Header.FileName);
-      File = SourceMgr.getFileManager().getFile(PathName);
-      
+      llvm::sys::path::append(RelativePathName, Header.FileName);
+      llvm::sys::path::append(FullPathName, RelativePathName.str());
+      File = SourceMgr.getFileManager().getFile(FullPathName);
+
       // If this is a system module with a top-level header, this header
       // may have a counterpart (or replacement) in the set of headers
       // supplied by Clang. Find that builtin header.
@@ -1750,18 +1757,19 @@
         SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName());
         llvm::sys::path::append(BuiltinPathName, Header.FileName);
         BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName);
-        
+
         // If Clang supplies this header but the underlying system does not,
         // just silently swap in our builtin version. Otherwise, we'll end
         // up adding both (later).
         if (!File && BuiltinFile) {
           File = BuiltinFile;
+          RelativePathName = BuiltinPathName;
           BuiltinFile = nullptr;
         }
       }
     }
   }
-  
+
   // FIXME: We shouldn't be eagerly stat'ing every file named in a module map.
   // Come up with a lazy way to do this.
   if (File) {
@@ -1776,16 +1784,23 @@
         Map.setUmbrellaHeader(ActiveModule, File);
       }
     } else if (LeadingToken == MMToken::ExcludeKeyword) {
-      Map.excludeHeader(ActiveModule, File);
+      Module::Header H = {RelativePathName.str(), File};
+      Map.excludeHeader(ActiveModule, H);
     } else {
       // If there is a builtin counterpart to this file, add it now, before
       // the "real" header, so we build the built-in one first when building
       // the module.
-      if (BuiltinFile)
-        Map.addHeader(ActiveModule, BuiltinFile, Role);
+      if (BuiltinFile) {
+        // FIXME: Taking the name from the FileEntry is unstable and can give
+        // different results depending on how we've previously named that file
+        // in this build.
+        Module::Header H = { BuiltinFile->getName(), BuiltinFile };
+        Map.addHeader(ActiveModule, H, Role);
+      }
 
       // Record this header.
-      Map.addHeader(ActiveModule, File, Role);
+      Module::Header H = { RelativePathName.str(), File };
+      Map.addHeader(ActiveModule, H, Role);
     }
   } else if (LeadingToken != MMToken::ExcludeKeyword) {
     // Ignore excluded header files. They're optional anyway.
@@ -2118,7 +2133,7 @@
   } else {
     // We'll be inferring framework modules for this directory.
     Map.InferredDirectories[Directory].InferModules = true;
-    Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem;
+    Map.InferredDirectories[Directory].Attrs = Attrs;
     Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
     // FIXME: Handle the 'framework' keyword.
   }
@@ -2316,7 +2331,8 @@
   } while (true);
 }
 
-bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem) {
+bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
+                                   const DirectoryEntry *Dir) {
   llvm::DenseMap<const FileEntry *, bool>::iterator Known
     = ParsedModuleMap.find(File);
   if (Known != ParsedModuleMap.end())
@@ -2329,17 +2345,6 @@
   if (!Buffer)
     return ParsedModuleMap[File] = true;
 
-  // Find the directory for the module. For frameworks, that may require going
-  // up from the 'Modules' directory.
-  const DirectoryEntry *Dir = File->getDir();
-  StringRef DirName(Dir->getName());
-  if (llvm::sys::path::filename(DirName) == "Modules") {
-    DirName = llvm::sys::path::parent_path(DirName);
-    if (DirName.endswith(".framework"))
-      Dir = SourceMgr.getFileManager().getDirectory(DirName);
-    assert(Dir && "parent must exist");
-  }
-  
   // Parse this module map file.
   Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts);
   ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
diff --git a/lib/Lex/PPDirectives.cpp b/lib/Lex/PPDirectives.cpp
index 04f3b29..bf0ce72 100644
--- a/lib/Lex/PPDirectives.cpp
+++ b/lib/Lex/PPDirectives.cpp
@@ -100,7 +100,56 @@
   } while (Tmp.isNot(tok::eod));
 }
 
-bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef) {
+/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
+enum MacroDiag {
+  MD_NoWarn,        //> Not a reserved identifier
+  MD_KeywordDef,    //> Macro hides keyword, enabled by default
+  MD_ReservedMacro  //> #define of #undef reserved id, disabled by default
+};
+
+/// \brief Checks if the specified identifier is reserved in the specified
+/// language.
+/// This function does not check if the identifier is a keyword.
+static bool isReservedId(StringRef Text, const LangOptions &Lang) {
+  // C++ [macro.names], C11 7.1.3:
+  // All identifiers that begin with an underscore and either an uppercase
+  // letter or another underscore are always reserved for any use.
+  if (Text.size() >= 2 && Text[0] == '_' &&
+      (isUppercase(Text[1]) || Text[1] == '_'))
+      return true;
+  // C++ [global.names]
+  // Each name that contains a double underscore ... is reserved to the
+  // implementation for any use.
+  if (Lang.CPlusPlus) {
+    if (Text.find("__") != StringRef::npos)
+      return true;
+  }
+  return false;
+}
+
+static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
+  const LangOptions &Lang = PP.getLangOpts();
+  StringRef Text = II->getName();
+  if (isReservedId(Text, Lang))
+    return MD_ReservedMacro;
+  if (II->isKeyword(Lang))
+    return MD_KeywordDef;
+  if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
+    return MD_KeywordDef;
+  return MD_NoWarn;
+}
+
+static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
+  const LangOptions &Lang = PP.getLangOpts();
+  StringRef Text = II->getName();
+  // Do not warn on keyword undef.  It is generally harmless and widely used.
+  if (isReservedId(Text, Lang))
+    return MD_ReservedMacro;
+  return MD_NoWarn;
+}
+
+bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
+                                  bool *ShadowFlag) {
   // Missing macro name?
   if (MacroNameTok.is(tok::eod))
     return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
@@ -140,6 +189,30 @@
     Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
   }
 
+  // If defining/undefining reserved identifier or a keyword, we need to issue
+  // a warning.
+  SourceLocation MacroNameLoc = MacroNameTok.getLocation();
+  if (ShadowFlag)
+    *ShadowFlag = false;
+  if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
+      (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
+    MacroDiag D = MD_NoWarn;
+    if (isDefineUndef == MU_Define) {
+      D = shouldWarnOnMacroDef(*this, II);
+    }
+    else if (isDefineUndef == MU_Undef)
+      D = shouldWarnOnMacroUndef(*this, II);
+    if (D == MD_KeywordDef) {
+      // We do not want to warn on some patterns widely used in configuration
+      // scripts.  This requires analyzing next tokens, so do not issue warnings
+      // now, only inform caller.
+      if (ShadowFlag)
+        *ShadowFlag = true;
+    }
+    if (D == MD_ReservedMacro)
+      Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
+  }
+
   // Okay, we got a good identifier.
   return false;
 }
@@ -151,8 +224,10 @@
 /// the macro name is invalid.
 ///
 /// \param MacroNameTok Token that is expected to be a macro name.
-/// \papam isDefineUndef Context in which macro is used.
-void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef) {
+/// \param isDefineUndef Context in which macro is used.
+/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
+void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
+                                 bool *ShadowFlag) {
   // Read the token, don't allow macro expansion on it.
   LexUnexpandedToken(MacroNameTok);
 
@@ -163,7 +238,7 @@
     LexUnexpandedToken(MacroNameTok);
   }
 
-  if (!CheckMacroName(MacroNameTok, isDefineUndef))
+  if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
     return;
 
   // Invalid macro name, read and discard the rest of the line and set the
@@ -550,14 +625,22 @@
     const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
 
     // If there is no file entry associated with this file, it must be the
-    // predefines buffer.  Any other file is not lexed with a normal lexer, so
-    // it won't be scanned for preprocessor directives.   If we have the
-    // predefines buffer, resolve #include references (which come from the
-    // -include command line argument) from the current working directory
-    // instead of relative to the main file.
+    // predefines buffer or the module includes buffer. Any other file is not
+    // lexed with a normal lexer, so it won't be scanned for preprocessor
+    // directives.
+    //
+    // If we have the predefines buffer, resolve #include references (which come
+    // from the -include command line argument) from the current working
+    // directory instead of relative to the main file.
+    //
+    // If we have the module includes buffer, resolve #include references (which
+    // come from header declarations in the module map) relative to the module
+    // map file.
     if (!FileEnt) {
-      FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
-      if (FileEnt)
+      if (FID == SourceMgr.getMainFileID() && MainFileDir)
+        Includers.push_back(std::make_pair(nullptr, MainFileDir));
+      else if ((FileEnt =
+                    SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
         Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
     } else {
       Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
@@ -715,7 +798,8 @@
       case tok::pp_import:
       case tok::pp_include_next:
       case tok::pp___include_macros:
-        Diag(Result, diag::err_embedded_include) << II->getName();
+      case tok::pp_pragma:
+        Diag(Result, diag::err_embedded_directive) << II->getName();
         DiscardUntilEndOfDirective();
         return;
       default:
@@ -1891,6 +1975,52 @@
   }
 }
 
+static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
+                                   const LangOptions &LOptions) {
+  if (MI->getNumTokens() == 1) {
+    const Token &Value = MI->getReplacementToken(0);
+
+    // Macro that is identity, like '#define inline inline' is a valid pattern.
+    if (MacroName.getKind() == Value.getKind())
+      return true;
+
+    // Macro that maps a keyword to the same keyword decorated with leading/
+    // trailing underscores is a valid pattern:
+    //    #define inline __inline
+    //    #define inline __inline__
+    //    #define inline _inline (in MS compatibility mode)
+    StringRef MacroText = MacroName.getIdentifierInfo()->getName();
+    if (IdentifierInfo *II = Value.getIdentifierInfo()) {
+      if (!II->isKeyword(LOptions))
+        return false;
+      StringRef ValueText = II->getName();
+      StringRef TrimmedValue = ValueText;
+      if (!ValueText.startswith("__")) {
+        if (ValueText.startswith("_"))
+          TrimmedValue = TrimmedValue.drop_front(1);
+        else
+          return false;
+      } else {
+        TrimmedValue = TrimmedValue.drop_front(2);
+        if (TrimmedValue.endswith("__"))
+          TrimmedValue = TrimmedValue.drop_back(2);
+      }
+      return TrimmedValue.equals(MacroText);
+    } else {
+      return false;
+    }
+  }
+
+  // #define inline
+  if ((MacroName.is(tok::kw_extern) || MacroName.is(tok::kw_inline) ||
+       MacroName.is(tok::kw_static) || MacroName.is(tok::kw_const)) &&
+      MI->getNumTokens() == 0) {
+    return true;
+  }
+
+  return false;
+}
+
 /// HandleDefineDirective - Implements \#define.  This consumes the entire macro
 /// line then lets the caller lex the next real token.
 void Preprocessor::HandleDefineDirective(Token &DefineTok,
@@ -1898,7 +2028,8 @@
   ++NumDefined;
 
   Token MacroNameTok;
-  ReadMacroName(MacroNameTok, MU_Define);
+  bool MacroShadowsKeyword;
+  ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
 
   // Error reading macro name?  If so, diagnostic already issued.
   if (MacroNameTok.is(tok::eod))
@@ -2075,6 +2206,10 @@
     }
   }
 
+  if (MacroShadowsKeyword &&
+      !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
+    Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
+  }
 
   // Disable __VA_ARGS__ again.
   Ident__VA_ARGS__->setIsPoisoned(true);
diff --git a/lib/Lex/PPExpressions.cpp b/lib/Lex/PPExpressions.cpp
index 9cf72cf..a6f16f8 100644
--- a/lib/Lex/PPExpressions.cpp
+++ b/lib/Lex/PPExpressions.cpp
@@ -310,7 +310,9 @@
     // Set the value.
     Val = Literal.getValue();
     // Set the signedness. UTF-16 and UTF-32 are always unsigned
-    if (!Literal.isUTF16() && !Literal.isUTF32())
+    if (Literal.isWide())
+      Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
+    else if (!Literal.isUTF16() && !Literal.isUTF32())
       Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
 
     if (Result.Val.getBitWidth() > Val.getBitWidth()) {
diff --git a/lib/Lex/PPMacroExpansion.cpp b/lib/Lex/PPMacroExpansion.cpp
index 1100dca..b986ada 100644
--- a/lib/Lex/PPMacroExpansion.cpp
+++ b/lib/Lex/PPMacroExpansion.cpp
@@ -118,6 +118,7 @@
   Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
   Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
+  Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
   Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
@@ -911,8 +912,11 @@
       .Case("objc_dictionary_literals", LangOpts.ObjC2)
       .Case("objc_boxed_expressions", LangOpts.ObjC2)
       .Case("arc_cf_code_audited", true)
+      .Case("objc_bridge_id", true)
+      .Case("objc_bridge_id_on_typedefs", true)
       // C11 features
       .Case("c_alignas", LangOpts.C11)
+      .Case("c_alignof", LangOpts.C11)
       .Case("c_atomic", LangOpts.C11)
       .Case("c_generic_selections", LangOpts.C11)
       .Case("c_static_assert", LangOpts.C11)
@@ -922,6 +926,7 @@
       .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
       .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
       .Case("cxx_alignas", LangOpts.CPlusPlus11)
+      .Case("cxx_alignof", LangOpts.CPlusPlus11)
       .Case("cxx_atomic", LangOpts.CPlusPlus11)
       .Case("cxx_attributes", LangOpts.CPlusPlus11)
       .Case("cxx_auto_type", LangOpts.CPlusPlus11)
@@ -1030,6 +1035,7 @@
   return llvm::StringSwitch<bool>(Extension)
            // C11 features supported by other languages as extensions.
            .Case("c_alignas", true)
+           .Case("c_alignof", true)
            .Case("c_atomic", true)
            .Case("c_generic_selections", true)
            .Case("c_static_assert", true)
@@ -1174,7 +1180,7 @@
   // __has_include_next is like __has_include, except that we start
   // searching after the current found directory.  If we can't do this,
   // issue a diagnostic.
-  // FIXME: Factor out duplication wiht
+  // FIXME: Factor out duplication with 
   // Preprocessor::HandleIncludeNextDirective.
   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
   const FileEntry *LookupFromFile = nullptr;
@@ -1378,6 +1384,7 @@
              II == Ident__has_builtin   ||
              II == Ident__is_identifier ||
              II == Ident__has_attribute ||
+             II == Ident__has_declspec  ||
              II == Ident__has_cpp_attribute) {
     // The argument to these builtins should be a parenthesized identifier.
     SourceLocation StartLoc = Tok.getLocation();
@@ -1409,6 +1416,10 @@
         if (IsScopeValid && Tok.is(tok::r_paren))
           IsValid = true;
       }
+      // Eat tokens until ')'.
+      while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
+             Tok.isNot(tok::eof))
+        LexUnexpandedToken(Tok);
     }
 
     int Value = 0;
@@ -1420,11 +1431,14 @@
       // Check for a builtin is trivial.
       Value = FeatureII->getBuiltinID() != 0;
     } else if (II == Ident__has_attribute)
-      Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
+      Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII,
                            getTargetInfo().getTriple(), getLangOpts());
     else if (II == Ident__has_cpp_attribute)
       Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
                            getTargetInfo().getTriple(), getLangOpts());
+    else if (II == Ident__has_declspec)
+      Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
+                           getTargetInfo().getTriple(), getLangOpts());
     else if (II == Ident__has_extension)
       Value = HasExtension(*this, FeatureII);
     else {
@@ -1432,9 +1446,10 @@
       Value = HasFeature(*this, FeatureII);
     }
 
+    if (!IsValid)
+      return;
     OS << Value;
-    if (IsValid)
-      Tok.setKind(tok::numeric_constant);
+    Tok.setKind(tok::numeric_constant);
   } else if (II == Ident__has_include ||
              II == Ident__has_include_next) {
     // The argument to these two builtins should be a parenthesized
@@ -1498,9 +1513,10 @@
                               WarningName.substr(2), Diags);
     } while (false);
 
+    if (!IsValid)
+      return;
     OS << (int)Value;
-    if (IsValid)
-      Tok.setKind(tok::numeric_constant);
+    Tok.setKind(tok::numeric_constant);
   } else if (II == Ident__building_module) {
     // The argument to this builtin should be an identifier. The
     // builtin evaluates to 1 when that identifier names the module we are
diff --git a/lib/Lex/PreprocessingRecord.cpp b/lib/Lex/PreprocessingRecord.cpp
index 41bb581..7abd340 100644
--- a/lib/Lex/PreprocessingRecord.cpp
+++ b/lib/Lex/PreprocessingRecord.cpp
@@ -45,22 +45,23 @@
 
 /// \brief Returns a pair of [Begin, End) iterators of preprocessed entities
 /// that source range \p Range encompasses.
-std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
+llvm::iterator_range<PreprocessingRecord::iterator>
 PreprocessingRecord::getPreprocessedEntitiesInRange(SourceRange Range) {
   if (Range.isInvalid())
-    return std::make_pair(iterator(), iterator());
+    return llvm::make_range(iterator(), iterator());
 
   if (CachedRangeQuery.Range == Range) {
-    return std::make_pair(iterator(this, CachedRangeQuery.Result.first),
-                          iterator(this, CachedRangeQuery.Result.second));
+    return llvm::make_range(iterator(this, CachedRangeQuery.Result.first),
+                            iterator(this, CachedRangeQuery.Result.second));
   }
 
   std::pair<int, int> Res = getPreprocessedEntitiesInRangeSlow(Range);
   
   CachedRangeQuery.Range = Range;
   CachedRangeQuery.Result = Res;
-  
-  return std::make_pair(iterator(this, Res.first), iterator(this, Res.second));
+
+  return llvm::make_range(iterator(this, Res.first),
+                          iterator(this, Res.second));
 }
 
 static bool isPreprocessedEntityIfInFileID(PreprocessedEntity *PPE, FileID FID,
diff --git a/lib/Lex/Preprocessor.cpp b/lib/Lex/Preprocessor.cpp
index 5da54ae..b2a6d93 100644
--- a/lib/Lex/Preprocessor.cpp
+++ b/lib/Lex/Preprocessor.cpp
@@ -71,7 +71,7 @@
       CodeComplete(nullptr), CodeCompletionFile(nullptr),
       CodeCompletionOffset(0), LastTokenWasAt(false),
       ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
-      SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
+      MainFileDir(nullptr), SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
       CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
       Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
       MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
@@ -672,7 +672,8 @@
   // keyword when we're in a caching lexer, because caching lexers only get
   // used in contexts where import declarations are disallowed.
   if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs && 
-      !DisableMacroExpansion && getLangOpts().Modules && 
+      !DisableMacroExpansion &&
+      (getLangOpts().Modules || getLangOpts().DebuggerSupport) && 
       CurLexerKind != CLK_CachingLexer) {
     ModuleImportLoc = Identifier.getLocation();
     ModuleImportPath.clear();
@@ -745,12 +746,14 @@
   }
 
   // If we have a non-empty module path, load the named module.
-  if (!ModuleImportPath.empty() && getLangOpts().Modules) {
-    Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
-                                                  ModuleImportPath,
-                                                  Module::MacrosVisible,
-                                                  /*IsIncludeDirective=*/false);
-    if (Callbacks)
+  if (!ModuleImportPath.empty()) {
+    Module *Imported = nullptr;
+    if (getLangOpts().Modules)
+      Imported = TheModuleLoader.loadModule(ModuleImportLoc,
+                                            ModuleImportPath,
+                                            Module::MacrosVisible,
+                                            /*IsIncludeDirective=*/false);
+    if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
       Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
   }
 }
diff --git a/lib/Lex/TokenLexer.cpp b/lib/Lex/TokenLexer.cpp
index 45c8b01..5f4705e 100644
--- a/lib/Lex/TokenLexer.cpp
+++ b/lib/Lex/TokenLexer.cpp
@@ -206,6 +206,7 @@
                                            ExpansionLocStart,
                                            ExpansionLocEnd);
       }
+      Res.setFlag(Token::StringifiedInMacro);
 
       // The stringified/charified string leading space flag gets set to match
       // the #/#@ operator.
@@ -405,6 +406,14 @@
   }
 }
 
+/// \brief Checks if two tokens form wide string literal.
+static bool isWideStringLiteralFromMacro(const Token &FirstTok,
+                                         const Token &SecondTok) {
+  return FirstTok.is(tok::identifier) &&
+         FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() &&
+         SecondTok.stringifiedInMacro();
+}
+
 /// Lex - Lex and return a token from this macro stream.
 ///
 bool TokenLexer::Lex(Token &Tok) {
@@ -435,7 +444,13 @@
 
   // If this token is followed by a token paste (##) operator, paste the tokens!
   // Note that ## is a normal token when not expanding a macro.
-  if (!isAtEnd() && Tokens[CurToken].is(tok::hashhash) && Macro) {
+  if (!isAtEnd() && Macro &&
+      (Tokens[CurToken].is(tok::hashhash) ||
+       // Special processing of L#x macros in -fms-compatibility mode.
+       // Microsoft compiler is able to form a wide string literal from
+       // 'L#macro_arg' construct in a function-like macro.
+       (PP.getLangOpts().MSVCCompat &&
+        isWideStringLiteralFromMacro(Tok, Tokens[CurToken])))) {
     // When handling the microsoft /##/ extension, the final token is
     // returned by PasteTokens, not the pasted token.
     if (PasteTokens(Tok))
@@ -511,9 +526,10 @@
   SourceLocation StartLoc = Tok.getLocation();
   SourceLocation PasteOpLoc;
   do {
-    // Consume the ## operator.
+    // Consume the ## operator if any.
     PasteOpLoc = Tokens[CurToken].getLocation();
-    ++CurToken;
+    if (Tokens[CurToken].is(tok::hashhash))
+      ++CurToken;
     assert(!isAtEnd() && "No token on the RHS of a paste operator!");
 
     // Get the RHS token.
diff --git a/lib/Parse/ParseAST.cpp b/lib/Parse/ParseAST.cpp
index 0f5a1b3..6727afc 100644
--- a/lib/Parse/ParseAST.cpp
+++ b/lib/Parse/ParseAST.cpp
@@ -14,7 +14,6 @@
 #include "clang/Parse/ParseAST.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/DeclCXX.h"
 #include "clang/AST/ExternalASTSource.h"
 #include "clang/AST/Stmt.h"
 #include "clang/Parse/ParseDiagnostic.h"
@@ -146,10 +145,8 @@
   }
 
   // Process any TopLevelDecls generated by #pragma weak.
-  for (SmallVectorImpl<Decl *>::iterator
-       I = S.WeakTopLevelDecls().begin(),
-       E = S.WeakTopLevelDecls().end(); I != E; ++I)
-    Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
+  for (Decl *D : S.WeakTopLevelDecls())
+    Consumer->HandleTopLevelDecl(DeclGroupRef(D));
   
   Consumer->HandleTranslationUnit(S.getASTContext());
 
diff --git a/lib/Parse/ParseCXXInlineMethods.cpp b/lib/Parse/ParseCXXInlineMethods.cpp
index e1a5b8e..a53079b 100644
--- a/lib/Parse/ParseCXXInlineMethods.cpp
+++ b/lib/Parse/ParseCXXInlineMethods.cpp
@@ -218,6 +218,7 @@
   Eof.startToken();
   Eof.setKind(tok::eof);
   Eof.setLocation(Tok.getLocation());
+  Eof.setEofData(VarD);
   Toks.push_back(Eof);
 }
 
@@ -305,13 +306,21 @@
   ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
                             Scope::FunctionDeclarationScope | Scope::DeclScope);
   for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) {
+    auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param);
     // Introduce the parameter into scope.
-    Actions.ActOnDelayedCXXMethodParameter(getCurScope(),
-                                           LM.DefaultArgs[I].Param);
-
+    bool HasUnparsed = Param->hasUnparsedDefaultArg();
+    Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param);
     if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) {
-      // Save the current token position.
-      SourceLocation origLoc = Tok.getLocation();
+      // Mark the end of the default argument so that we know when to stop when
+      // we parse it later on.
+      Token LastDefaultArgToken = Toks->back();
+      Token DefArgEnd;
+      DefArgEnd.startToken();
+      DefArgEnd.setKind(tok::eof);
+      DefArgEnd.setLocation(LastDefaultArgToken.getLocation().getLocWithOffset(
+          LastDefaultArgToken.getLength()));
+      DefArgEnd.setEofData(Param);
+      Toks->push_back(DefArgEnd);
 
       // Parse the default argument from its saved token stream.
       Toks->push_back(Tok); // So that the current token doesn't get lost
@@ -328,7 +337,7 @@
       // used.
       EnterExpressionEvaluationContext Eval(Actions,
                                             Sema::PotentiallyEvaluatedIfUsed,
-                                            LM.DefaultArgs[I].Param);
+                                            Param);
 
       ExprResult DefArgResult;
       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
@@ -337,11 +346,10 @@
       } else
         DefArgResult = ParseAssignmentExpression();
       DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
-      if (DefArgResult.isInvalid())
-        Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param,
-                                               EqualLoc);
-      else {
-        if (!TryConsumeToken(tok::cxx_defaultarg_end)) {
+      if (DefArgResult.isInvalid()) {
+        Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
+      } else {
+        if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) {
           // The last two tokens are the terminator and the saved value of
           // Tok; the last token in the default argument is the one before
           // those.
@@ -350,27 +358,45 @@
             << SourceRange(Tok.getLocation(),
                            (*Toks)[Toks->size() - 3].getLocation());
         }
-        Actions.ActOnParamDefaultArgument(LM.DefaultArgs[I].Param, EqualLoc,
+        Actions.ActOnParamDefaultArgument(Param, EqualLoc,
                                           DefArgResult.get());
       }
 
-      assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
-                                                         Tok.getLocation()) &&
-             "ParseAssignmentExpression went over the default arg tokens!");
       // There could be leftover tokens (e.g. because of an error).
-      // Skip through until we reach the original token position.
-      while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
+      // Skip through until we reach the 'end of default argument' token.
+      while (Tok.isNot(tok::eof))
+        ConsumeAnyToken();
+
+      if (Tok.is(tok::eof) && Tok.getEofData() == Param)
         ConsumeAnyToken();
 
       delete Toks;
       LM.DefaultArgs[I].Toks = nullptr;
+    } else if (HasUnparsed) {
+      assert(Param->hasInheritedDefaultArg());
+      FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl();
+      ParmVarDecl *OldParam = Old->getParamDecl(I);
+      assert (!OldParam->hasUnparsedDefaultArg());
+      if (OldParam->hasUninstantiatedDefaultArg())
+        Param->setUninstantiatedDefaultArg(
+                                      Param->getUninstantiatedDefaultArg());
+      else
+        Param->setDefaultArg(OldParam->getInit());
     }
   }
 
   // Parse a delayed exception-specification, if there is one.
   if (CachedTokens *Toks = LM.ExceptionSpecTokens) {
-    // Save the current token position.
-    SourceLocation origLoc = Tok.getLocation();
+    // Add the 'stop' token.
+    Token LastExceptionSpecToken = Toks->back();
+    Token ExceptionSpecEnd;
+    ExceptionSpecEnd.startToken();
+    ExceptionSpecEnd.setKind(tok::eof);
+    ExceptionSpecEnd.setLocation(
+        LastExceptionSpecToken.getLocation().getLocWithOffset(
+            LastExceptionSpecToken.getLength()));
+    ExceptionSpecEnd.setEofData(LM.Method);
+    Toks->push_back(ExceptionSpecEnd);
 
     // Parse the default argument from its saved token stream.
     Toks->push_back(Tok); // So that the current token doesn't get lost
@@ -409,10 +435,7 @@
                                        DynamicExceptionRanges, NoexceptExpr,
                                        ExceptionSpecTokens);
 
-    // Clean up the remaining tokens.
-    if (Tok.is(tok::cxx_exceptspec_end))
-      ConsumeToken();
-    else if (EST != EST_None)
+    if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method)
       Diag(Tok.getLocation(), diag::err_except_spec_unparsed);
 
     // Attach the exception-specification to the method.
@@ -423,13 +446,13 @@
                                                NoexceptExpr.isUsable()?
                                                  NoexceptExpr.get() : nullptr);
 
-    assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
-                                                            Tok.getLocation()) &&
-           "tryParseExceptionSpecification went over the exception tokens!");
-
     // There could be leftover tokens (e.g. because of an error).
     // Skip through until we reach the original token position.
-    while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
+    while (Tok.isNot(tok::eof))
+      ConsumeAnyToken();
+
+    // Clean up the remaining EOF token.
+    if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method)
       ConsumeAnyToken();
 
     delete Toks;
@@ -470,10 +493,16 @@
     Actions.ActOnReenterTemplateScope(getCurScope(), LM.D);
     ++CurTemplateDepthTracker;
   }
-  // Save the current token position.
-  SourceLocation origLoc = Tok.getLocation();
 
   assert(!LM.Toks.empty() && "Empty body!");
+  Token LastBodyToken = LM.Toks.back();
+  Token BodyEnd;
+  BodyEnd.startToken();
+  BodyEnd.setKind(tok::eof);
+  BodyEnd.setLocation(
+      LastBodyToken.getLocation().getLocWithOffset(LastBodyToken.getLength()));
+  BodyEnd.setEofData(LM.D);
+  LM.Toks.push_back(BodyEnd);
   // Append the current token at the end of the new token stream so that it
   // doesn't get lost.
   LM.Toks.push_back(Tok);
@@ -491,12 +520,11 @@
 
   if (Tok.is(tok::kw_try)) {
     ParseFunctionTryBlock(LM.D, FnScope);
-    assert(!PP.getSourceManager().isBeforeInTranslationUnit(origLoc,
-                                                         Tok.getLocation()) &&
-           "ParseFunctionTryBlock went over the cached tokens!");
-    // There could be leftover tokens (e.g. because of an error).
-    // Skip through until we reach the original token position.
-    while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
+
+    while (Tok.isNot(tok::eof))
+      ConsumeAnyToken();
+
+    if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
       ConsumeAnyToken();
     return;
   }
@@ -507,7 +535,11 @@
     if (!Tok.is(tok::l_brace)) {
       FnScope.Exit();
       Actions.ActOnFinishFunctionBody(LM.D, nullptr);
-      while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
+
+      while (Tok.isNot(tok::eof))
+        ConsumeAnyToken();
+
+      if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
         ConsumeAnyToken();
       return;
     }
@@ -527,17 +559,11 @@
   if (LM.D)
     LM.D->getAsFunction()->setLateTemplateParsed(false);
 
-  if (Tok.getLocation() != origLoc) {
-    // Due to parsing error, we either went over the cached tokens or
-    // there are still cached tokens left. If it's the latter case skip the
-    // leftover tokens.
-    // Since this is an uncommon situation that should be avoided, use the
-    // expensive isBeforeInTranslationUnit call.
-    if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
-                                                        origLoc))
-      while (Tok.getLocation() != origLoc && Tok.isNot(tok::eof))
-        ConsumeAnyToken();
-  }
+  while (Tok.isNot(tok::eof))
+    ConsumeAnyToken();
+
+  if (Tok.is(tok::eof) && Tok.getEofData() == LM.D)
+    ConsumeAnyToken();
 
   if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D))
     Actions.ActOnFinishInlineMethodDef(MD);
@@ -622,7 +648,9 @@
     while (Tok.isNot(tok::eof))
       ConsumeAnyToken();
   }
-  ConsumeAnyToken();
+  // Make sure this is *our* artificial EOF token.
+  if (Tok.getEofData() == MI.Field)
+    ConsumeAnyToken();
 }
 
 /// ConsumeAndStoreUntil - Consume and store the token at the passed token
@@ -1016,7 +1044,7 @@
         case CIK_DefaultArgument:
           bool InvalidAsDeclaration = false;
           Result = TryParseParameterDeclarationClause(
-              &InvalidAsDeclaration, /*VersusTemplateArgument*/true);
+              &InvalidAsDeclaration, /*VersusTemplateArgument=*/true);
           // If this is an expression or a declaration with a missing
           // 'typename', assume it's not a declaration.
           if (Result == TPResult::Ambiguous && InvalidAsDeclaration)
diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp
index 518197e..b6264d4 100644
--- a/lib/Parse/ParseDecl.cpp
+++ b/lib/Parse/ParseDecl.cpp
@@ -143,10 +143,12 @@
         continue;
 
       // Expect an identifier or declaration specifier (const, int, etc.)
-      if (Tok.isNot(tok::identifier) && !isDeclarationSpecifier())
+      if (Tok.isAnnotation())
+        break;
+      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
+      if (!AttrName)
         break;
 
-      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
       SourceLocation AttrNameLoc = ConsumeToken();
 
       if (Tok.isNot(tok::l_paren)) {
@@ -614,6 +616,42 @@
   }
 }
 
+void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
+  SourceLocation StartLoc = Tok.getLocation();
+  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
+
+  if (EndLoc.isValid()) {
+    SourceRange Range(StartLoc, EndLoc);
+    Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
+  }
+}
+
+SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
+  SourceLocation EndLoc;
+
+  while (true) {
+    switch (Tok.getKind()) {
+    case tok::kw_const:
+    case tok::kw_volatile:
+    case tok::kw___fastcall:
+    case tok::kw___stdcall:
+    case tok::kw___thiscall:
+    case tok::kw___cdecl:
+    case tok::kw___vectorcall:
+    case tok::kw___ptr32:
+    case tok::kw___ptr64:
+    case tok::kw___w64:
+    case tok::kw___unaligned:
+    case tok::kw___sptr:
+    case tok::kw___uptr:
+      EndLoc = ConsumeToken();
+      break;
+    default:
+      return EndLoc;
+    }
+  }
+}
+
 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
   // Treat these like attributes
   while (Tok.is(tok::kw___pascal)) {
@@ -1109,8 +1147,14 @@
 /// to the Attribute list for the decl.
 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
                                  bool EnterScope, bool OnDefinition) {
-  // Save the current token position.
-  SourceLocation OrigLoc = Tok.getLocation();
+  // Create a fake EOF so that attribute parsing won't go off the end of the
+  // attribute.
+  Token AttrEnd;
+  AttrEnd.startToken();
+  AttrEnd.setKind(tok::eof);
+  AttrEnd.setLocation(Tok.getLocation());
+  AttrEnd.setEofData(LA.Toks.data());
+  LA.Toks.push_back(AttrEnd);
 
   // Append the current token at the end of the new token stream so that it
   // doesn't get lost.
@@ -1175,16 +1219,13 @@
   for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
     Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
 
-  if (Tok.getLocation() != OrigLoc) {
-    // Due to a parsing error, we either went over the cached tokens or
-    // there are still cached tokens left, so we skip the leftover tokens.
-    // Since this is an uncommon situation that should be avoided, use the
-    // expensive isBeforeInTranslationUnit call.
-    if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
-                                                        OrigLoc))
-    while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
-      ConsumeAnyToken();
-  }
+  // Due to a parsing error, we either went over the cached tokens or
+  // there are still cached tokens left, so we skip the leftover tokens.
+  while (Tok.isNot(tok::eof))
+    ConsumeAnyToken();
+
+  if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
+    ConsumeAnyToken();
 }
 
 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
@@ -1430,7 +1471,7 @@
   }
 
   DS.takeAttributesFrom(Attrs);
-  return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
+  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
 }
 
 /// Returns true if this might be the start of a declarator, or a common typo
@@ -1585,7 +1626,6 @@
 /// result.
 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
                                               unsigned Context,
-                                              bool AllowFunctionDefinitions,
                                               SourceLocation *DeclEnd,
                                               ForRangeInit *FRI) {
   // Parse the first declarator.
@@ -1633,7 +1673,10 @@
       // start of a function definition in GCC-extended K&R C.
       !isDeclarationAfterDeclarator()) {
 
-    if (AllowFunctionDefinitions) {
+    // Function definitions are only allowed at file scope and in C++ classes.
+    // The C++ inline method definition case is handled elsewhere, so we only
+    // need to handle the file scope definition case.
+    if (Context == Declarator::FileContext) {
       if (isStartOfFunctionDefinition(D)) {
         if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
           Diag(Tok, diag::err_function_declared_typedef);
@@ -1648,11 +1691,12 @@
       }
 
       if (isDeclarationSpecifier()) {
-        // If there is an invalid declaration specifier right after the function
-        // prototype, then we must be in a missing semicolon case where this isn't
-        // actually a body.  Just fall through into the code that handles it as a
-        // prototype, and let the top-level code handle the erroneous declspec
-        // where it would otherwise expect a comma or semicolon.
+        // If there is an invalid declaration specifier right after the
+        // function prototype, then we must be in a missing semicolon case
+        // where this isn't actually a body.  Just fall through into the code
+        // that handles it as a prototype, and let the top-level code handle
+        // the erroneous declspec where it would otherwise expect a comma or
+        // semicolon.
       } else {
         Diag(Tok, diag::err_expected_fn_body);
         SkipUntil(tok::semi);
@@ -1732,6 +1776,10 @@
     //    short x, __attribute__((common)) var;    -> declarator
     MaybeParseGNUAttributes(D);
 
+    // MSVC parses but ignores qualifiers after the comma as an extension.
+    if (getLangOpts().MicrosoftExt)
+      DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
+
     ParseDeclarator(D);
     if (!D.isInvalidType()) {
       Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
@@ -1946,7 +1994,11 @@
       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
     }
 
-    if (ParseExpressionList(Exprs, CommaLocs)) {
+    if (ParseExpressionList(Exprs, CommaLocs, [&] {
+          Actions.CodeCompleteConstructor(getCurScope(),
+                 cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
+                                          ThisDecl->getLocation(), Exprs);
+       })) {
       Actions.ActOnInitializerError(ThisDecl);
       SkipUntil(tok::r_paren, StopAtSemi);
 
@@ -2520,6 +2572,7 @@
   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
   while (1) {
     bool isInvalid = false;
+    bool isStorageClass = false;
     const char *PrevSpec = nullptr;
     unsigned DiagID = 0;
 
@@ -2823,9 +2876,9 @@
                             Tok.getLocation(), getCurScope());
 
       // MSVC: If we weren't able to parse a default template argument, and it's
-      // just a simple identifier, create a DependentNameType.  This will allow us
-      // to defer the name lookup to template instantiation time, as long we forge a
-      // NestedNameSpecifier for the current context.
+      // just a simple identifier, create a DependentNameType.  This will allow
+      // us to defer the name lookup to template instantiation time, as long we
+      // forge a NestedNameSpecifier for the current context.
       if (!TypeRep && DSContext == DSC_template_type_arg &&
           getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) {
         TypeRep = Actions.ActOnDelayedDefaultTemplateArg(
@@ -2943,22 +2996,26 @@
     case tok::kw_typedef:
       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
                                          PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw_extern:
       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
         Diag(Tok, diag::ext_thread_before) << "extern";
       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
                                          PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw___private_extern__:
       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
                                          Loc, PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw_static:
       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
         Diag(Tok, diag::ext_thread_before) << "static";
       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
                                          PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw_auto:
       if (getLangOpts().CPlusPlus11) {
@@ -2974,18 +3031,22 @@
       } else
         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
                                            PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw_register:
       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
                                          PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw_mutable:
       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
                                          PrevSpec, DiagID, Policy);
+      isStorageClass = true;
       break;
     case tok::kw___thread:
       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
                                                PrevSpec, DiagID);
+      isStorageClass = true;
       break;
     case tok::kw_thread_local:
       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
@@ -2994,6 +3055,7 @@
     case tok::kw__Thread_local:
       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
                                                Loc, PrevSpec, DiagID);
+      isStorageClass = true;
       break;
 
     // function-specifier
@@ -3146,6 +3208,9 @@
     case tok::kw___pixel:
       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
       break;
+    case tok::kw___bool:
+      isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
+      break;
     case tok::kw___unknown_anytype:
       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
                                      PrevSpec, DiagID, Policy);
@@ -3232,6 +3297,15 @@
       break;
 
     // OpenCL qualifiers:
+    case tok::kw___generic:
+      // generic address space is introduced only in OpenCL v2.0
+      // see OpenCL C Spec v2.0 s6.5.5
+      if (Actions.getLangOpts().OpenCLVersion < 200) {
+        DiagID = diag::err_opencl_unknown_type_specifier;
+        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
+        isInvalid = true;
+        break;
+      };
     case tok::kw___private:
     case tok::kw___global:
     case tok::kw___local:
@@ -3266,6 +3340,8 @@
       if (DiagID == diag::ext_duplicate_declspec)
         Diag(Tok, DiagID)
           << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
+      else if (DiagID == diag::err_opencl_unknown_type_specifier)
+        Diag(Tok, DiagID) << PrevSpec << isStorageClass;
       else
         Diag(Tok, DiagID) << PrevSpec;
     }
@@ -3573,11 +3649,12 @@
     // if a fixed underlying type is allowed.
     ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
 
-    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
+    CXXScopeSpec Spec;
+    if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(),
                                        /*EnteringContext=*/true))
       return;
 
-    if (SS.isSet() && Tok.isNot(tok::identifier)) {
+    if (Spec.isSet() && Tok.isNot(tok::identifier)) {
       Diag(Tok, diag::err_expected) << tok::identifier;
       if (Tok.isNot(tok::l_brace)) {
         // Has no name and is not a definition.
@@ -3586,6 +3663,8 @@
         return;
       }
     }
+
+    SS = Spec;
   }
 
   // Must have either 'enum name' or 'enum {...}'.
@@ -3982,6 +4061,7 @@
   case tok::kw___local:
   case tok::kw___global:
   case tok::kw___constant:
+  case tok::kw___generic:
   case tok::kw___read_only:
   case tok::kw___read_write:
   case tok::kw___write_only:
@@ -4131,6 +4211,7 @@
   case tok::kw___local:
   case tok::kw___global:
   case tok::kw___constant:
+  case tok::kw___generic:
   case tok::kw___read_only:
   case tok::kw___read_write:
   case tok::kw___write_only:
@@ -4303,6 +4384,7 @@
   case tok::kw___local:
   case tok::kw___global:
   case tok::kw___constant:
+  case tok::kw___generic:
   case tok::kw___read_only:
   case tok::kw___read_write:
   case tok::kw___write_only:
@@ -4491,6 +4573,7 @@
     case tok::kw___global:
     case tok::kw___local:
     case tok::kw___constant:
+    case tok::kw___generic:
     case tok::kw___read_only:
     case tok::kw___write_only:
     case tok::kw___read_write:
@@ -4658,7 +4741,7 @@
       // Sema will have to catch (syntactically invalid) pointers into global
       // scope. It has to catch pointers into namespace scope anyway.
       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
-                                                      Loc),
+                                                      DS.getLocEnd()),
                     DS.getAttributes(),
                     /* Don't replace range end. */SourceLocation());
       return;
@@ -4841,26 +4924,28 @@
     }
 
     if (D.getCXXScopeSpec().isValid()) {
-      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
+      if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
+                                             D.getCXXScopeSpec()))
         // Change the declaration context for name lookup, until this function
         // is exited (and the declarator has been parsed).
         DeclScopeObj.EnterDeclaratorScope();
     }
 
     // C++0x [dcl.fct]p14:
-    //   There is a syntactic ambiguity when an ellipsis occurs at the end
-    //   of a parameter-declaration-clause without a preceding comma. In
-    //   this case, the ellipsis is parsed as part of the
-    //   abstract-declarator if the type of the parameter names a template
-    //   parameter pack that has not been expanded; otherwise, it is parsed
-    //   as part of the parameter-declaration-clause.
+    //   There is a syntactic ambiguity when an ellipsis occurs at the end of a
+    //   parameter-declaration-clause without a preceding comma. In this case,
+    //   the ellipsis is parsed as part of the abstract-declarator if the type
+    //   of the parameter either names a template parameter pack that has not
+    //   been expanded or contains auto; otherwise, it is parsed as part of the
+    //   parameter-declaration-clause.
     if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
         !((D.getContext() == Declarator::PrototypeContext ||
            D.getContext() == Declarator::LambdaExprParameterContext ||
            D.getContext() == Declarator::BlockLiteralContext) &&
           NextToken().is(tok::r_paren) &&
           !D.hasGroupingParens() &&
-          !Actions.containsUnexpandedParameterPacks(D))) {
+          !Actions.containsUnexpandedParameterPacks(D) &&
+          D.getDeclSpec().getTypeSpecType() != TST_auto)) {
       SourceLocation EllipsisLoc = ConsumeToken();
       if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
         // The ellipsis was put in the wrong place. Recover, and explain to
@@ -4892,6 +4977,7 @@
         AllowConstructorName = (D.getContext() == Declarator::MemberContext);
 
       SourceLocation TemplateKWLoc;
+      bool HadScope = D.getCXXScopeSpec().isValid();
       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
                              /*EnteringContext=*/true,
                              /*AllowDestructorName=*/true,
@@ -4905,6 +4991,13 @@
         D.SetIdentifier(nullptr, Tok.getLocation());
         D.setInvalidType(true);
       } else {
+        // ParseUnqualifiedId might have parsed a scope specifier during error
+        // recovery. If it did so, enter that scope.
+        if (!HadScope && D.getCXXScopeSpec().isValid() &&
+            Actions.ShouldEnterDeclaratorScope(getCurScope(),
+                                               D.getCXXScopeSpec()))
+          DeclScopeObj.EnterDeclaratorScope();
+
         // Parsed the unqualified-id; update range information and move along.
         if (D.getSourceRange().getBegin().isInvalid())
           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
@@ -4946,7 +5039,8 @@
       // If there was an error parsing parenthesized declarator, declarator
       // scope may have been entered before. Don't do it again.
       if (!D.isInvalidType() &&
-          Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
+          Actions.ShouldEnterDeclaratorScope(getCurScope(),
+                                             D.getCXXScopeSpec()))
         // Change the declaration context for name lookup, until this function
         // is exited (and the declarator has been parsed).
         DeclScopeObj.EnterDeclaratorScope();
@@ -5552,20 +5646,14 @@
           // FIXME: Can we use a smart pointer for Toks?
           DefArgToks = new CachedTokens;
 
+          SourceLocation ArgStartLoc = NextToken().getLocation();
           if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
             delete DefArgToks;
             DefArgToks = nullptr;
             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
           } else {
-            // Mark the end of the default argument so that we know when to
-            // stop when we parse it later on.
-            Token DefArgEnd;
-            DefArgEnd.startToken();
-            DefArgEnd.setKind(tok::cxx_defaultarg_end);
-            DefArgEnd.setLocation(Tok.getLocation());
-            DefArgToks->push_back(DefArgEnd);
             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
-                                                (*DefArgToks)[1].getLocation());
+                                                      ArgStartLoc);
           }
         } else {
           // Consume the '='.
@@ -5724,7 +5812,8 @@
     } else {
       EnterExpressionEvaluationContext Unevaluated(Actions,
                                                    Sema::ConstantEvaluated);
-      NumElements = ParseAssignmentExpression();
+      NumElements =
+          Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
     }
   } else {
     if (StaticLoc.isValid()) {
@@ -5863,8 +5952,8 @@
   bool isCastExpr;
   ParsedType CastTy;
   SourceRange CastRange;
-  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
-                                                          CastTy, CastRange);
+  ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
+      ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
   if (hasParens)
     DS.setTypeofParensRange(CastRange);
 
@@ -5964,6 +6053,7 @@
   case tok::kw_float:
   case tok::kw_double:
   case tok::kw_bool:
+  case tok::kw___bool:
   case tok::kw___pixel:
     Tok.setKind(tok::kw___vector);
     return true;
@@ -5997,6 +6087,7 @@
     case tok::kw_float:
     case tok::kw_double:
     case tok::kw_bool:
+    case tok::kw___bool:
     case tok::kw___pixel:
       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
       return true;
diff --git a/lib/Parse/ParseDeclCXX.cpp b/lib/Parse/ParseDeclCXX.cpp
index 79ae878..5f7893c 100644
--- a/lib/Parse/ParseDeclCXX.cpp
+++ b/lib/Parse/ParseDeclCXX.cpp
@@ -17,8 +17,8 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/Attributes.h"
 #include "clang/Basic/CharInfo.h"
-#include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/OperatorKinds.h"
+#include "clang/Basic/TargetInfo.h"
 #include "clang/Parse/ParseDiagnostic.h"
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/ParsedTemplate.h"
@@ -1095,6 +1095,7 @@
   case tok::kw_volatile:        // struct foo {...} volatile  x;
   case tok::kw_restrict:        // struct foo {...} restrict  x;
   case tok::kw__Atomic:         // struct foo {...} _Atomic   x;
+  case tok::kw___unaligned:     // struct foo {...} __unaligned *x;
   // Function specifiers
   // Note, no 'explicit'. An explicit function must be either a conversion
   // operator or a constructor. Either way, it can't have a return type.
@@ -1243,7 +1244,8 @@
   SourceLocation AttrFixitLoc = Tok.getLocation();
 
   if (TagType == DeclSpec::TST_struct &&
-      !Tok.is(tok::identifier) &&
+      Tok.isNot(tok::identifier) &&
+      !Tok.isAnnotation() &&
       Tok.getIdentifierInfo() &&
       (Tok.is(tok::kw___is_abstract) ||
        Tok.is(tok::kw___is_arithmetic) ||
@@ -1308,11 +1310,19 @@
     // is a base-specifier-list.
     ColonProtectionRAIIObject X(*this);
 
-    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
+    CXXScopeSpec Spec;
+    bool HasValidSpec = true;
+    if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), EnteringContext)) {
       DS.SetTypeSpecError();
-    if (SS.isSet())
-      if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
+      HasValidSpec = false;
+    }
+    if (Spec.isSet())
+      if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
         Diag(Tok, diag::err_expected) << tok::identifier;
+        HasValidSpec = false;
+      }
+    if (HasValidSpec)
+      SS = Spec;
   }
 
   TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
@@ -1880,51 +1890,40 @@
 /// the class definition.
 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
                                             Decl *ThisDecl) {
-  // We just declared a member function. If this member function
-  // has any default arguments or an exception-specification, we'll need to
-  // parse them later.
-  LateParsedMethodDeclaration *LateMethod = nullptr;
   DeclaratorChunk::FunctionTypeInfo &FTI
     = DeclaratorInfo.getFunctionTypeInfo();
+  // If there was a late-parsed exception-specification, we'll need a
+  // late parse
+  bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
 
-  // If there was a late-parsed exception-specification, hold onto its tokens.
-  if (FTI.getExceptionSpecType() == EST_Unparsed) {
+  if (!NeedLateParse) {
+    // Look ahead to see if there are any default args
+    for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
+      auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
+      if (Param->hasUnparsedDefaultArg()) {
+        NeedLateParse = true;
+        break;
+      }
+    }
+  }
+
+  if (NeedLateParse) {
     // Push this method onto the stack of late-parsed method
     // declarations.
-    LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
+    auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
     getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
     LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
 
-    // Stash the exception-specification tokens in the late-pased mthod.
+    // Stash the exception-specification tokens in the late-pased method.
     LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
     FTI.ExceptionSpecTokens = 0;
 
-    // Reserve space for the parameters.
+    // Push tokens for each parameter.  Those that do not have
+    // defaults will be NULL.
     LateMethod->DefaultArgs.reserve(FTI.NumParams);
-  }
-
-  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
-    if (LateMethod || FTI.Params[ParamIdx].DefaultArgTokens) {
-      if (!LateMethod) {
-        // Push this method onto the stack of late-parsed method
-        // declarations.
-        LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
-        getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
-        LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
-
-        // Add all of the parameters prior to this one (they don't
-        // have default arguments).
-        LateMethod->DefaultArgs.reserve(FTI.NumParams);
-        for (unsigned I = 0; I < ParamIdx; ++I)
-          LateMethod->DefaultArgs.push_back(
-              LateParsedDefaultArgument(FTI.Params[I].Param));
-      }
-
-      // Add this parameter to the list of parameters (it may or may
-      // not have a default argument).
+    for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
       LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
-          FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
-    }
+        FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
   }
 }
 
@@ -2017,7 +2016,7 @@
 
 /// \brief Parse a C++ member-declarator up to, but not including, the optional
 /// brace-or-equal-initializer or pure-specifier.
-void Parser::ParseCXXMemberDeclaratorBeforeInitializer(
+bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
     Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
     LateParsedAttrList &LateParsedAttrs) {
   // member-declarator:
@@ -2071,6 +2070,15 @@
       }
     }
   }
+
+  // If this has neither a name nor a bit width, something has gone seriously
+  // wrong. Skip until the semi-colon or }.
+  if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
+    // If so, skip until the semi-colon or a }.
+    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
+    return true;
+  }
+  return false;
 }
 
 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
@@ -2296,14 +2304,8 @@
   bool ExpectSemi = true;
 
   // Parse the first declarator.
-  ParseCXXMemberDeclaratorBeforeInitializer(DeclaratorInfo, VS, BitfieldSize,
-                                            LateParsedAttrs);
-
-  // If this has neither a name nor a bit width, something has gone seriously
-  // wrong. Skip until the semi-colon or }.
-  if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
-    // If so, skip until the semi-colon or a }.
-    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
+  if (ParseCXXMemberDeclaratorBeforeInitializer(
+          DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
     TryConsumeToken(tok::semi);
     return;
   }
@@ -2352,7 +2354,7 @@
       ProhibitAttributes(FnAttrs);
     }
 
-    if (DefinitionKind) {
+    if (DefinitionKind != FDK_Declaration) {
       if (!DeclaratorInfo.isFunctionDeclarator()) {
         Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
         ConsumeBrace();
@@ -2528,16 +2530,17 @@
     // Parse the next declarator.
     DeclaratorInfo.clear();
     VS.clear();
-    BitfieldSize = true;
-    Init = true;
+    BitfieldSize = ExprResult(/*Invalid=*/false);
+    Init = ExprResult(/*Invalid=*/false);
     HasInitializer = false;
     DeclaratorInfo.setCommaLoc(CommaLoc);
 
     // GNU attributes are allowed before the second and subsequent declarator.
     MaybeParseGNUAttributes(DeclaratorInfo);
 
-    ParseCXXMemberDeclaratorBeforeInitializer(DeclaratorInfo, VS, BitfieldSize,
-                                              LateParsedAttrs);
+    if (ParseCXXMemberDeclaratorBeforeInitializer(
+            DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
+      break;
   }
 
   if (ExpectSemi &&
@@ -2607,7 +2610,10 @@
         Diag(ConsumeToken(), diag::err_default_special_members);
       return ExprError();
     }
-
+  }
+  if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
+    Diag(Tok, diag::err_ms_property_initializer) << PD;
+    return ExprError();
   }
   return ParseInitializer();
 }
@@ -2701,6 +2707,19 @@
     // and the only possible place for them to appertain
     // to the class would be between class-key and class-name.
     CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
+
+    // ParseClassSpecifier() does only a superficial check for attributes before
+    // deciding to call this method.  For example, for
+    // `class C final alignas ([l) {` it will decide that this looks like a
+    // misplaced attribute since it sees `alignas '(' ')'`.  But the actual
+    // attribute parsing code will try to parse the '[' as a constexpr lambda
+    // and consume enough tokens that the alignas parsing code will eat the
+    // opening '{'.  So bail out if the next token isn't one we expect.
+    if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
+      if (TagDecl)
+        Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
+      return;
+    }
   }
 
   if (Tok.is(tok::colon)) {
@@ -3131,23 +3150,11 @@
     ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
     ExceptionSpecTokens->push_back(Tok); // '('
     SpecificationRange.setEnd(ConsumeParen()); // '('
-    
-    if (!ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
-                              /*StopAtSemi=*/true,
-                              /*ConsumeFinalToken=*/true)) {
-      NoexceptExpr = 0;
-      delete ExceptionSpecTokens;
-      ExceptionSpecTokens = 0;
-      return IsNoexcept? EST_BasicNoexcept : EST_DynamicNone;
-    }
+
+    ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
+                         /*StopAtSemi=*/true,
+                         /*ConsumeFinalToken=*/true);
     SpecificationRange.setEnd(Tok.getLocation());
-    
-    // Add the 'stop' token.
-    Token End;
-    End.startToken();
-    End.setKind(tok::cxx_exceptspec_end);
-    End.setLocation(Tok.getLocation());
-    ExceptionSpecTokens->push_back(End);
     return EST_Unparsed;
   }
   
@@ -3368,9 +3375,11 @@
   switch (Tok.getKind()) {
   default:
     // Identifiers and keywords have identifier info attached.
-    if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
-      Loc = ConsumeToken();
-      return II;
+    if (!Tok.isAnnotation()) {
+      if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
+        Loc = ConsumeToken();
+        return II;
+      }
     }
     return nullptr;
 
@@ -3465,16 +3474,14 @@
       if (Attr->getMaxArgs() && !NumArgs) {
         // The attribute was allowed to have arguments, but none were provided
         // even though the attribute parsed successfully. This is an error.
-        // FIXME: This is a good place for a fixit which removes the parens.
         Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
-        return false;
       } else if (!Attr->getMaxArgs()) {
         // The attribute parsed successfully, but was not allowed to have any
         // arguments. It doesn't matter whether any were provided -- the
         // presence of the argument list (even if empty) is diagnosed.
         Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
-            << AttrName;
-        return false;
+            << AttrName
+            << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
       }
     }
   }
diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp
index 3d57ba9..07af62f 100644
--- a/lib/Parse/ParseExpr.cpp
+++ b/lib/Parse/ParseExpr.cpp
@@ -446,8 +446,8 @@
 namespace {
 class CastExpressionIdValidator : public CorrectionCandidateCallback {
  public:
-  CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes)
-      : AllowNonTypes(AllowNonTypes) {
+  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
+      : NextToken(Next), AllowNonTypes(AllowNonTypes) {
     WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
   }
 
@@ -458,11 +458,24 @@
 
     if (isa<TypeDecl>(ND))
       return WantTypeSpecifiers;
-    return AllowNonTypes &&
-           CorrectionCandidateCallback::ValidateCandidate(candidate);
+
+    if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
+      return false;
+
+    if (!(NextToken.is(tok::equal) || NextToken.is(tok::arrow) ||
+          NextToken.is(tok::period)))
+      return true;
+
+    for (auto *C : candidate) {
+      NamedDecl *ND = C->getUnderlyingDecl();
+      if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
+        return true;
+    }
+    return false;
   }
 
  private:
+  Token NextToken;
   bool AllowNonTypes;
 };
 }
@@ -908,8 +921,9 @@
     SourceLocation TemplateKWLoc;
     Token Replacement;
     auto Validator = llvm::make_unique<CastExpressionIdValidator>(
-        isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
+        Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
     Validator->IsAddressOfOperand = isAddressOfOperand;
+    Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
     Name.setIdentifier(&II, ILoc);
     Res = Actions.ActOnIdExpression(
         getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
@@ -1363,8 +1377,12 @@
       if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
         LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
                                               Idx.get(), RLoc);
-      } else
+      } else {
+        (void)Actions.CorrectDelayedTyposInExpr(LHS);
+        (void)Actions.CorrectDelayedTyposInExpr(Idx);
         LHS = ExprError();
+        Idx = ExprError();
+      }
 
       // Match the ']'.
       T.consumeClose();
@@ -1387,6 +1405,7 @@
         SourceLocation OpenLoc = ConsumeToken();
 
         if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
+          (void)Actions.CorrectDelayedTyposInExpr(LHS);
           LHS = ExprError();
         }
 
@@ -1435,8 +1454,10 @@
 
       if (OpKind == tok::l_paren || !LHS.isInvalid()) {
         if (Tok.isNot(tok::r_paren)) {
-          if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall,
-                                  LHS.get())) {
+          if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
+                Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
+             })) {
+            (void)Actions.CorrectDelayedTyposInExpr(LHS);
             LHS = ExprError();
           }
         }
@@ -1503,14 +1524,14 @@
         cutOffParsing();
         return ExprError();
       }
-      
+
       if (MayBePseudoDestructor && !LHS.isInvalid()) {
         LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, 
                                        ObjectType);
         break;
       }
 
-      // Either the action has told is that this cannot be a
+      // Either the action has told us that this cannot be a
       // pseudo-destructor expression (based on the type of base
       // expression), or we didn't see a '~' in the right place. We
       // can still parse a destructor name here, but in that case it
@@ -1519,7 +1540,8 @@
       // FIXME: Add support for explicit call of template constructor.
       SourceLocation TemplateKWLoc;
       UnqualifiedId Name;
-      if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) {
+      if (getLangOpts().ObjC2 && OpKind == tok::period &&
+          Tok.is(tok::kw_class)) {
         // Objective-C++:
         //   After a '.' in a member access expression, treat the keyword
         //   'class' as if it were an identifier.
@@ -1535,15 +1557,16 @@
                                     /*AllowDestructorName=*/true,
                                     /*AllowConstructorName=*/
                                       getLangOpts().MicrosoftExt, 
-                                    ObjectType, TemplateKWLoc, Name))
+                                    ObjectType, TemplateKWLoc, Name)) {
+        (void)Actions.CorrectDelayedTyposInExpr(LHS);
         LHS = ExprError();
+      }
       
       if (!LHS.isInvalid())
         LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, 
                                             OpKind, SS, TemplateKWLoc, Name,
                                  CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
-                                                   : nullptr,
-                                            Tok.is(tok::l_paren));
+                                                   : nullptr);
       break;
     }
     case tok::plusplus:    // postfix-expression: postfix-expression '++'
@@ -2075,16 +2098,21 @@
   // unless they've already reported an error.
   if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
     Diag(Tok, diag::ext_gnu_statement_expr);
-    Actions.ActOnStartStmtExpr();
 
-    StmtResult Stmt(ParseCompoundStatement(true));
-    ExprType = CompoundStmt;
-
-    // If the substmt parsed correctly, build the AST node.
-    if (!Stmt.isInvalid()) {
-      Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
+    if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
+      Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
     } else {
-      Actions.ActOnStmtExprError();
+      Actions.ActOnStartStmtExpr();
+
+      StmtResult Stmt(ParseCompoundStatement(true));
+      ExprType = CompoundStmt;
+
+      // If the substmt parsed correctly, build the AST node.
+      if (!Stmt.isInvalid()) {
+        Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
+      } else {
+        Actions.ActOnStmtExprError();
+      }
     }
   } else if (ExprType >= CompoundLiteral && BridgeCast) {
     tok::TokenKind tokenKind = Tok.getKind();
@@ -2479,17 +2507,14 @@
 /// [C++0x]   assignment-expression
 /// [C++0x]   braced-init-list
 /// \endverbatim
-bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
+bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
                                  SmallVectorImpl<SourceLocation> &CommaLocs,
-                                 void (Sema::*Completer)(Scope *S,
-                                                         Expr *Data,
-                                                         ArrayRef<Expr *> Args),
-                                 Expr *Data) {
+                                 std::function<void()> Completer) {
   bool SawError = false;
   while (1) {
     if (Tok.is(tok::code_completion)) {
       if (Completer)
-        (Actions.*Completer)(getCurScope(), Data, Exprs);
+        Completer();
       else
         Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
       cutOffParsing();
@@ -2513,10 +2538,19 @@
     }
 
     if (Tok.isNot(tok::comma))
-      return SawError;
+      break;
     // Move to the next argument, remember where the comma was.
     CommaLocs.push_back(ConsumeToken());
   }
+  if (SawError) {
+    // Ensure typos get diagnosed when errors were encountered while parsing the
+    // expression list.
+    for (auto &E : Exprs) {
+      ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
+      if (Expr.isUsable()) E = Expr.get();
+    }
+  }
+  return SawError;
 }
 
 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
diff --git a/lib/Parse/ParseExprCXX.cpp b/lib/Parse/ParseExprCXX.cpp
index 613246e..6cff1c5 100644
--- a/lib/Parse/ParseExprCXX.cpp
+++ b/lib/Parse/ParseExprCXX.cpp
@@ -108,35 +108,37 @@
   if (!Tok.is(tok::l_paren))
     return;
 
-  SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
-  Token Tok1 = getCurToken();
-  if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
+  Token LParen = Tok;
+  Token NextTok = GetLookAheadToken(1);
+  Token StarTok = NextTok;
+  // Check for (identifier or (*identifier
+  Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
+  if (IdentifierTok.isNot(tok::identifier))
     return;
-
-  if (Tok1.is(tok::identifier)) {
-    Token Tok2 = GetLookAheadToken(1);
-    if (Tok2.is(tok::r_paren)) {
+  // Eat the '('.
+  ConsumeParen();
+  Token RParen;
+  // Do we have a ')' ?
+  NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
+  if (NextTok.is(tok::r_paren)) {
+    RParen = NextTok;
+    // Eat the '*' if it is present.
+    if (StarTok.is(tok::star))
       ConsumeToken();
-      PP.EnterToken(Tok1);
-      r_parenLoc = ConsumeParen();
-    }
-  } else if (Tok1.is(tok::star)) {
-    Token Tok2 = GetLookAheadToken(1);
-    if (Tok2.is(tok::identifier)) {
-      Token Tok3 = GetLookAheadToken(2);
-      if (Tok3.is(tok::r_paren)) {
-        ConsumeToken();
-        ConsumeToken();
-        PP.EnterToken(Tok2);
-        PP.EnterToken(Tok1);
-        r_parenLoc = ConsumeParen();
-      }
-    }
+    // Eat the identifier.
+    ConsumeToken();
+    // Add the identifier token back.
+    PP.EnterToken(IdentifierTok);
+    // Add the '*' back if it was present.
+    if (StarTok.is(tok::star))
+      PP.EnterToken(StarTok);
+    // Eat the ')'.
+    ConsumeParen();
   }
 
-  Diag(l_parenLoc, diag::err_paren_after_colon_colon)
-      << FixItHint::CreateRemoval(l_parenLoc)
-      << FixItHint::CreateRemoval(r_parenLoc);
+  Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
+      << FixItHint::CreateRemoval(LParen.getLocation())
+      << FixItHint::CreateRemoval(RParen.getLocation());
 }
 
 /// \brief Parse global scope or nested-name-specifier if present.
@@ -192,6 +194,7 @@
 
   if (Tok.is(tok::annot_cxxscope)) {
     assert(!LastII && "want last identifier but have already annotated scope");
+    assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
     Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
                                                  Tok.getAnnotationRange(),
                                                  SS);
@@ -206,6 +209,13 @@
     SS = TemplateId->SS;
   }
 
+  // Has to happen before any "return false"s in this function.
+  bool CheckForDestructor = false;
+  if (MayBePseudoDestructor && *MayBePseudoDestructor) {
+    CheckForDestructor = true;
+    *MayBePseudoDestructor = false;
+  }
+
   if (LastII)
     *LastII = nullptr;
 
@@ -217,13 +227,19 @@
     if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
       return false;
 
-    // '::' - Global scope qualifier.
-    if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
-      return true;
+    if (NextKind == tok::l_brace) {
+      // It is invalid to have :: {, consume the scope qualifier and pretend
+      // like we never saw it.
+      Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
+    } else {
+      // '::' - Global scope qualifier.
+      if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
+        return true;
 
-    CheckForLParenAfterColonColon();
+      CheckForLParenAfterColonColon();
 
-    HasScopeSpecifier = true;
+      HasScopeSpecifier = true;
+    }
   }
 
   if (Tok.is(tok::kw___super)) {
@@ -236,12 +252,6 @@
     return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
   }
 
-  bool CheckForDestructor = false;
-  if (MayBePseudoDestructor && *MayBePseudoDestructor) {
-    CheckForDestructor = true;
-    *MayBePseudoDestructor = false;
-  }
-
   if (!HasScopeSpecifier &&
       (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
     DeclSpec DS(AttrFactory);
@@ -434,7 +444,18 @@
         Next.setKind(tok::coloncolon);
       }
     }
-    
+
+    if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
+      // It is invalid to have :: {, consume the scope qualifier and pretend
+      // like we never saw it.
+      Token Identifier = Tok; // Stash away the identifier.
+      ConsumeToken();         // Eat the identifier, current token is now '::'.
+      Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
+          << tok::identifier;
+      UnconsumeToken(Identifier); // Stick the identifier back.
+      Next = NextToken();         // Point Next at the '{' token.
+    }
+
     if (Next.is(tok::coloncolon)) {
       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
           !Actions.isNonTypeNestedNameSpecifier(
@@ -640,7 +661,8 @@
   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
 
   Token Replacement;
-  ExprResult Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
+  ExprResult Result =
+      tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
   if (Result.isUnset()) {
     // If the ExprResult is valid but null, then typo correction suggested a
     // keyword replacement that needs to be reparsed.
@@ -875,11 +897,16 @@
         // to save the necessary state, and restore it later.
         EnterExpressionEvaluationContext EC(Actions,
                                             Sema::PotentiallyEvaluated);
-        TryConsumeToken(tok::equal);
+        bool HadEquals = TryConsumeToken(tok::equal);
 
-        if (!SkippedInits)
+        if (!SkippedInits) {
+          // Warn on constructs that will change meaning when we implement N3922
+          if (!HadEquals && Tok.is(tok::l_brace)) {
+            Diag(Tok, diag::warn_init_capture_direct_list_init)
+              << FixItHint::CreateInsertion(Tok.getLocation(), "=");
+          }
           Init = ParseInitializer();
-        else if (Tok.is(tok::l_brace)) {
+        } else if (Tok.is(tok::l_brace)) {
           BalancedDelimiterTracker Braces(*this, tok::l_brace);
           Braces.consumeOpen();
           Braces.skipToEnd();
@@ -1033,6 +1060,7 @@
   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
   Actions.PushLambdaScope();    
 
+  TypeResult TrailingReturnType;
   if (Tok.is(tok::l_paren)) {
     ParseScope PrototypeScope(this,
                               Scope::FunctionPrototypeScope |
@@ -1065,6 +1093,11 @@
     // compatible with GCC.
     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
 
+    // MSVC-style attributes must be parsed before the mutable specifier to be
+    // compatible with MSVC.
+    while (Tok.is(tok::kw___declspec))
+      ParseMicrosoftDeclSpec(Attr);
+
     // Parse 'mutable'[opt].
     SourceLocation MutableLoc;
     if (TryConsumeToken(tok::kw_mutable, MutableLoc))
@@ -1093,7 +1126,6 @@
     SourceLocation FunLocalRangeEnd = DeclEndLoc;
 
     // Parse trailing-return-type[opt].
-    TypeResult TrailingReturnType;
     if (Tok.is(tok::arrow)) {
       FunLocalRangeEnd = Tok.getLocation();
       SourceRange Range;
@@ -1163,12 +1195,11 @@
     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
 
     // Parse the return type, if there is one.
-    TypeResult TrailingReturnType;
     if (Tok.is(tok::arrow)) {
       SourceRange Range;
       TrailingReturnType = ParseTrailingReturnType(Range);
       if (Range.getEnd().isValid())
-        DeclEndLoc = Range.getEnd();      
+        DeclEndLoc = Range.getEnd();
     }
 
     SourceLocation NoLoc;
@@ -1216,9 +1247,9 @@
   StmtResult Stmt(ParseCompoundStatementBody());
   BodyScope.Exit();
 
-  if (!Stmt.isInvalid())
+  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
     return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
- 
+
   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
   return ExprError();
 }
@@ -1462,9 +1493,8 @@
     ParseDecltypeSpecifier(DS);
     if (DS.getTypeSpecType() == TST_error)
       return ExprError();
-    return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, 
-                                             OpKind, TildeLoc, DS, 
-                                             Tok.is(tok::l_paren));
+    return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
+                                             TildeLoc, DS);
   }
 
   if (!Tok.is(tok::identifier)) {
@@ -1487,11 +1517,9 @@
                                    /*AssumeTemplateName=*/true))
     return ExprError();
 
-  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
-                                           OpLoc, OpKind,
-                                           SS, FirstTypeName, CCLoc,
-                                           TildeLoc, SecondTypeName,
-                                           Tok.is(tok::l_paren));
+  return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
+                                           SS, FirstTypeName, CCLoc, TildeLoc,
+                                           SecondTypeName);
 }
 
 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
@@ -1579,7 +1607,11 @@
     CommaLocsTy CommaLocs;
 
     if (Tok.isNot(tok::r_paren)) {
-      if (ParseExpressionList(Exprs, CommaLocs)) {
+      if (ParseExpressionList(Exprs, CommaLocs, [&] {
+            Actions.CodeCompleteConstructor(getCurScope(),
+                                      TypeRep.get()->getCanonicalTypeInternal(),
+                                            DS.getLocEnd(), Exprs);
+         })) {
         SkipUntil(tok::r_paren, StopAtSemi);
         return ExprError();
       }
@@ -2486,14 +2518,23 @@
     }
 
     // If the user wrote ~T::T, correct it to T::~T.
+    DeclaratorScopeObj DeclScopeObj(*this, SS);
     if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
+      // Don't let ParseOptionalCXXScopeSpecifier() "correct"
+      // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
+      // it will confuse this recovery logic.
+      ColonProtectionRAIIObject ColonRAII(*this, false);
+
       if (SS.isSet()) {
         AnnotateScopeToken(SS, /*NewAnnotation*/true);
         SS.clear();
       }
       if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
         return true;
-      if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
+      if (SS.isNotEmpty())
+        ObjectType = ParsedType();
+      if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
+          SS.isInvalid()) {
         Diag(TildeLoc, diag::err_destructor_tilde_scope);
         return true;
       }
@@ -2502,6 +2543,10 @@
       Diag(TildeLoc, diag::err_destructor_tilde_scope)
         << FixItHint::CreateRemoval(TildeLoc)
         << FixItHint::CreateInsertion(Tok.getLocation(), "~");
+
+      // Temporarily enter the scope for the rest of this function.
+      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
+        DeclScopeObj.EnterDeclaratorScope();
     }
 
     // Parse the class-name (or template-name in a simple-template-id).
@@ -2645,7 +2690,14 @@
     ConstructorLParen = T.getOpenLocation();
     if (Tok.isNot(tok::r_paren)) {
       CommaLocsTy CommaLocs;
-      if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
+      if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
+            ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
+                                                       DeclaratorInfo).get();
+            Actions.CodeCompleteConstructor(getCurScope(),
+                                      TypeRep.get()->getCanonicalTypeInternal(),
+                                            DeclaratorInfo.getLocEnd(),
+                                            ConstructorArgs);
+      })) {
         SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
         return ExprError();
       }
diff --git a/lib/Parse/ParseInit.cpp b/lib/Parse/ParseInit.cpp
index 8536420..7fe9862 100644
--- a/lib/Parse/ParseInit.cpp
+++ b/lib/Parse/ParseInit.cpp
@@ -423,9 +423,11 @@
 
     if (Tok.is(tok::ellipsis))
       SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
-    
+
+    SubElt = Actions.CorrectDelayedTyposInExpr(SubElt.get());
+
     // If we couldn't parse the subelement, bail out.
-    if (!SubElt.isInvalid()) {
+    if (SubElt.isUsable()) {
       InitExprs.push_back(SubElt.get());
     } else {
       InitExprsOk = false;
diff --git a/lib/Parse/ParseObjc.cpp b/lib/Parse/ParseObjc.cpp
index 0d0f110..a597a16 100644
--- a/lib/Parse/ParseObjc.cpp
+++ b/lib/Parse/ParseObjc.cpp
@@ -79,7 +79,7 @@
     SingleDecl = ParseObjCPropertyDynamic(AtLoc);
     break;
   case tok::objc_import:
-    if (getLangOpts().Modules)
+    if (getLangOpts().Modules || getLangOpts().DebuggerSupport)
       return ParseModuleImport(AtLoc);
     Diag(AtLoc, diag::err_atimport);
     SkipUntil(tok::semi);
@@ -2024,7 +2024,13 @@
 
   if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
     return ParseObjCAutoreleasePoolStmt(AtLoc);
-  
+
+  if (Tok.isObjCAtKeyword(tok::objc_import) &&
+      getLangOpts().DebuggerSupport) {
+    SkipUntil(tok::semi);
+    return Actions.ActOnNullStmt(Tok.getLocation());
+  }
+
   ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
   if (Res.isInvalid()) {
     // If the expression is invalid, skip ahead to the next semicolon. Not
@@ -2350,7 +2356,7 @@
   }
   
   // Otherwise, an arbitrary expression can be the receiver of a send.
-  ExprResult Res(ParseExpression());
+  ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
   if (Res.isInvalid()) {
     SkipUntil(tok::r_square, StopAtSemi);
     return Res;
@@ -2509,6 +2515,8 @@
       SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
       ///  Parse the expression after ','
       ExprResult Res(ParseAssignmentExpression());
+      if (Tok.is(tok::colon))
+        Res = Actions.CorrectDelayedTyposInExpr(Res);
       if (Res.isInvalid()) {
         if (Tok.is(tok::colon)) {
           Diag(commaLoc, diag::note_extra_comma_message_arg) <<
diff --git a/lib/Parse/ParseOpenMP.cpp b/lib/Parse/ParseOpenMP.cpp
index 7851c40..764619a 100644
--- a/lib/Parse/ParseOpenMP.cpp
+++ b/lib/Parse/ParseOpenMP.cpp
@@ -715,7 +715,8 @@
                      Tok.isNot(tok::annot_pragma_openmp_end))) {
     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
     // Parse variable
-    ExprResult VarExpr = ParseAssignmentExpression();
+    ExprResult VarExpr =
+        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
     if (VarExpr.isUsable()) {
       Vars.push_back(VarExpr.get());
     } else {
diff --git a/lib/Parse/ParsePragma.cpp b/lib/Parse/ParsePragma.cpp
index 473be54..5f89f01 100644
--- a/lib/Parse/ParsePragma.cpp
+++ b/lib/Parse/ParsePragma.cpp
@@ -219,6 +219,9 @@
     PP.AddPragmaHandler(MSCodeSeg.get());
     MSSection.reset(new PragmaMSPragma("section"));
     PP.AddPragmaHandler(MSSection.get());
+  } else if (getTargetInfo().getTriple().isPS4()) {
+    MSCommentHandler.reset(new PragmaCommentHandler(Actions));
+    PP.AddPragmaHandler(MSCommentHandler.get());
   }
 
   OptimizeHandler.reset(new PragmaOptimizeHandler(Actions));
@@ -282,6 +285,9 @@
     MSCodeSeg.reset();
     PP.RemovePragmaHandler(MSSection.get());
     MSSection.reset();
+  } else if (getTargetInfo().getTriple().isPS4()) {
+    PP.RemovePragmaHandler(MSCommentHandler.get());
+    MSCommentHandler.reset();
   }
 
   PP.RemovePragmaHandler("STDC", FPContractHandler.get());
diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp
index 1bfce60..e77f07a 100644
--- a/lib/Parse/ParseStmt.cpp
+++ b/lib/Parse/ParseStmt.cpp
@@ -408,12 +408,6 @@
   return Actions.ActOnExprStmt(Expr);
 }
 
-StmtResult Parser::ParseSEHTryBlock() {
-  assert(Tok.is(tok::kw___try) && "Expected '__try'");
-  SourceLocation Loc = ConsumeToken();
-  return ParseSEHTryBlockCommon(Loc);
-}
-
 /// ParseSEHTryBlockCommon
 ///
 /// seh-try-block:
@@ -423,8 +417,11 @@
 ///   seh-except-block
 ///   seh-finally-block
 ///
-StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) {
-  if(Tok.isNot(tok::l_brace))
+StmtResult Parser::ParseSEHTryBlock() {
+  assert(Tok.is(tok::kw___try) && "Expected '__try'");
+  SourceLocation TryLoc = ConsumeToken();
+
+  if (Tok.isNot(tok::l_brace))
     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
 
   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
@@ -441,7 +438,7 @@
     SourceLocation Loc = ConsumeToken();
     Handler = ParseSEHFinallyBlock(Loc);
   } else {
-    return StmtError(Diag(Tok,diag::err_seh_expected_handler));
+    return StmtError(Diag(Tok, diag::err_seh_expected_handler));
   }
 
   if(Handler.isInvalid())
@@ -466,14 +463,21 @@
   if (ExpectAndConsume(tok::l_paren))
     return StmtError();
 
-  ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
+  ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
+                                   Scope::SEHExceptScope);
 
   if (getLangOpts().Borland) {
     Ident__exception_info->setIsPoisoned(false);
     Ident___exception_info->setIsPoisoned(false);
     Ident_GetExceptionInfo->setIsPoisoned(false);
   }
-  ExprResult FilterExpr(ParseExpression());
+
+  ExprResult FilterExpr;
+  {
+    ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
+                                          Scope::SEHFilterScope);
+    FilterExpr = ParseExpression();
+  }
 
   if (getLangOpts().Borland) {
     Ident__exception_info->setIsPoisoned(true);
@@ -487,6 +491,9 @@
   if (ExpectAndConsume(tok::r_paren))
     return StmtError();
 
+  if (Tok.isNot(tok::l_brace))
+    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
+
   StmtResult Block(ParseCompoundStatement());
 
   if(Block.isInvalid())
@@ -505,6 +512,9 @@
     raii2(Ident___abnormal_termination, false),
     raii3(Ident_AbnormalTermination, false);
 
+  if (Tok.isNot(tok::l_brace))
+    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
+
   StmtResult Block(ParseCompoundStatement());
   if(Block.isInvalid())
     return Block;
@@ -1520,9 +1530,7 @@
     else
       ForRangeInit.RangeExpr = ParseExpression();
 
-    Diag(Loc, getLangOpts().CPlusPlus1z
-                  ? diag::warn_cxx14_compat_for_range_identifier
-                  : diag::ext_for_range_identifier)
+    Diag(Loc, diag::err_for_range_identifier)
       << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z)
               ? FixItHint::CreateInsertion(Loc, "auto &&")
               : FixItHint());
@@ -1803,7 +1811,7 @@
              diag::ext_generalized_initializer_lists)
           << R.get()->getSourceRange();
     } else
-        R = ParseExpression();
+      R = ParseExpression();
     if (R.isInvalid()) {
       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
       return StmtError();
@@ -1961,7 +1969,6 @@
 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
   if (Tok.isNot(tok::l_brace))
     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
-  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
 
   StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false,
                       Scope::DeclScope | Scope::TryScope |
diff --git a/lib/Parse/ParseStmtAsm.cpp b/lib/Parse/ParseStmtAsm.cpp
index 6f89953..9523ec3 100644
--- a/lib/Parse/ParseStmtAsm.cpp
+++ b/lib/Parse/ParseStmtAsm.cpp
@@ -615,6 +615,11 @@
     msAsm = true;
     return ParseMicrosoftAsmStatement(AsmLoc);
   }
+
+  // Check if GNU-style inline Asm is disabled.
+  if (!getLangOpts().GNUAsm)
+    Diag(AsmLoc, diag::err_gnu_inline_asm_disabled);
+
   DeclSpec DS(AttrFactory);
   SourceLocation Loc = Tok.getLocation();
   ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
@@ -774,7 +779,7 @@
     // Read the parenthesized expression.
     BalancedDelimiterTracker T(*this, tok::l_paren);
     T.consumeOpen();
-    ExprResult Res(ParseExpression());
+    ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
     T.consumeClose();
     if (Res.isInvalid()) {
       SkipUntil(tok::r_paren, StopAtSemi);
diff --git a/lib/Parse/ParseTemplate.cpp b/lib/Parse/ParseTemplate.cpp
index 2f1c189..53de72c 100644
--- a/lib/Parse/ParseTemplate.cpp
+++ b/lib/Parse/ParseTemplate.cpp
@@ -231,6 +231,16 @@
 
   if (DeclaratorInfo.isFunctionDeclarator() &&
       isStartOfFunctionDefinition(DeclaratorInfo)) {
+
+    // Function definitions are only allowed at file scope and in C++ classes.
+    // The C++ inline method definition case is handled elsewhere, so we only
+    // need to handle the file scope definition case.
+    if (Context != Declarator::FileContext) {
+      Diag(Tok, diag::err_function_definition_not_allowed);
+      SkipMalformedDecl();
+      return nullptr;
+    }
+
     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
       // Recover by ignoring the 'typedef'. This was probably supposed to be
       // the 'typename' keyword, which we should have already suggested adding
@@ -676,7 +686,7 @@
     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
 
-    DefaultArg = ParseAssignmentExpression();
+    DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
     if (DefaultArg.isInvalid())
       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
   }
diff --git a/lib/Parse/ParseTentative.cpp b/lib/Parse/ParseTentative.cpp
index 1f39c25..abf16fa 100644
--- a/lib/Parse/ParseTentative.cpp
+++ b/lib/Parse/ParseTentative.cpp
@@ -195,7 +195,9 @@
       }
     }
 
-    if (TryAnnotateCXXScopeToken())
+    if ((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
+         Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id)) &&
+        TryAnnotateCXXScopeToken())
       return TPResult::Error;
     if (Tok.is(tok::annot_cxxscope))
       ConsumeToken();
@@ -990,6 +992,7 @@
   case tok::kw___unaligned:
   case tok::kw___vector:
   case tok::kw___pixel:
+  case tok::kw___bool:
   case tok::kw__Atomic:
   case tok::kw___unknown_anytype:
     return TPResult::False;
diff --git a/lib/Parse/Parser.cpp b/lib/Parse/Parser.cpp
index 2bac56c..7ccd209 100644
--- a/lib/Parse/Parser.cpp
+++ b/lib/Parse/Parser.cpp
@@ -890,7 +890,7 @@
     return Actions.ConvertDeclToDeclGroup(TheDecl);
   }
 
-  return ParseDeclGroup(DS, Declarator::FileContext, true);
+  return ParseDeclGroup(DS, Declarator::FileContext);
 }
 
 Parser::DeclGroupPtrTy
@@ -927,7 +927,7 @@
 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
                                       const ParsedTemplateInfo &TemplateInfo,
                                       LateParsedAttrList *LateParsedAttrs) {
-  // Poison the SEH identifiers so they are flagged as illegal in function bodies
+  // Poison SEH identifiers so they are flagged as illegal in function bodies.
   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
 
@@ -1224,26 +1224,23 @@
 ///         string-literal
 ///
 ExprResult Parser::ParseAsmStringLiteral() {
-  switch (Tok.getKind()) {
-    case tok::string_literal:
-      break;
-    case tok::utf8_string_literal:
-    case tok::utf16_string_literal:
-    case tok::utf32_string_literal:
-    case tok::wide_string_literal: {
-      SourceLocation L = Tok.getLocation();
-      Diag(Tok, diag::err_asm_operand_wide_string_literal)
-        << (Tok.getKind() == tok::wide_string_literal)
-        << SourceRange(L, L);
-      return ExprError();
-    }
-    default:
-      Diag(Tok, diag::err_expected_string_literal)
-        << /*Source='in...'*/0 << "'asm'";
-      return ExprError();
+  if (!isTokenStringLiteral()) {
+    Diag(Tok, diag::err_expected_string_literal)
+      << /*Source='in...'*/0 << "'asm'";
+    return ExprError();
   }
 
-  return ParseStringLiteralExpression();
+  ExprResult AsmString(ParseStringLiteralExpression());
+  if (!AsmString.isInvalid()) {
+    const auto *SL = cast<StringLiteral>(AsmString.get());
+    if (!SL->isAscii()) {
+      Diag(Tok, diag::err_asm_operand_wide_string_literal)
+        << SL->isWide()
+        << SL->getSourceRange();
+      return ExprError();
+    }
+  }
+  return AsmString;
 }
 
 /// ParseSimpleAsm
@@ -1728,7 +1725,8 @@
 
   for (Scope *S = getCurScope(); S; S = S->getParent()) {
     if (S->getFlags() & Scope::FnScope) {
-      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction);
+      Actions.CodeCompleteOrdinaryName(getCurScope(),
+                                       Sema::PCC_RecoveryInFunction);
       cutOffParsing();
       return PrevTokLocation;
     }
@@ -1766,7 +1764,7 @@
 void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro,
                                        MacroInfo *MacroInfo,
                                        unsigned ArgumentIndex) {
-  Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, 
+  Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo,
                                                 ArgumentIndex);
 }
 
@@ -1788,8 +1786,9 @@
   }
   
   // Parse nested-name-specifier.
-  ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), 
-                                 /*EnteringContext=*/false);
+  if (getLangOpts().CPlusPlus)
+    ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),
+                                   /*EnteringContext=*/false);
 
   // Check nested-name specifier.
   if (Result.SS.isInvalid()) {
@@ -1810,7 +1809,7 @@
   
   // Check if the symbol exists.
   switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc,
-                                               Result.IsIfExists, Result.SS, 
+                                               Result.IsIfExists, Result.SS,
                                                Result.Name)) {
   case Sema::IER_Exists:
     Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip;
diff --git a/lib/Parse/RAIIObjectsForParser.h b/lib/Parse/RAIIObjectsForParser.h
index a0c9c1f..71cfec4 100644
--- a/lib/Parse/RAIIObjectsForParser.h
+++ b/lib/Parse/RAIIObjectsForParser.h
@@ -87,8 +87,8 @@
     Sema::ParsingDeclState State;
     bool Popped;
 
-    ParsingDeclRAIIObject(const ParsingDeclRAIIObject &) LLVM_DELETED_FUNCTION;
-    void operator=(const ParsingDeclRAIIObject &) LLVM_DELETED_FUNCTION;
+    ParsingDeclRAIIObject(const ParsingDeclRAIIObject &) = delete;
+    void operator=(const ParsingDeclRAIIObject &) = delete;
 
   public:
     enum NoParent_t { NoParent };
@@ -244,8 +244,8 @@
   /// the way they used to be.  This is used to handle __extension__ in the
   /// parser.
   class ExtensionRAIIObject {
-    ExtensionRAIIObject(const ExtensionRAIIObject &) LLVM_DELETED_FUNCTION;
-    void operator=(const ExtensionRAIIObject &) LLVM_DELETED_FUNCTION;
+    ExtensionRAIIObject(const ExtensionRAIIObject &) = delete;
+    void operator=(const ExtensionRAIIObject &) = delete;
 
     DiagnosticsEngine &Diags;
   public:
diff --git a/lib/Sema/AnalysisBasedWarnings.cpp b/lib/Sema/AnalysisBasedWarnings.cpp
index f666a9b..f52bc6e 100644
--- a/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/lib/Sema/AnalysisBasedWarnings.cpp
@@ -117,6 +117,7 @@
   reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
 }
 
+namespace {
 /// \brief Warn on logical operator errors in CFGBuilder
 class LogicalErrorHandler : public CFGCallback {
   Sema &S;
@@ -156,7 +157,7 @@
         << DiagRange << isAlwaysTrue;
   }
 };
-
+} // namespace
 
 //===----------------------------------------------------------------------===//
 // Check for infinite self-recursion in functions
@@ -1679,6 +1680,22 @@
     Warnings.push_back(DelayedDiag(Warning, getNotes()));
   }
 
+
+  virtual void handleLockAcquiredBefore(StringRef Kind, Name L1Name,
+                                        Name L2Name, SourceLocation Loc)
+      override {
+    PartialDiagnosticAt Warning(Loc,
+      S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
+    Warnings.push_back(DelayedDiag(Warning, getNotes()));
+  }
+
+  virtual void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc)
+      override {
+    PartialDiagnosticAt Warning(Loc,
+      S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
+    Warnings.push_back(DelayedDiag(Warning, getNotes()));
+  }
+
   void enterFunction(const FunctionDecl* FD) override {
     CurrentFunction = FD;
   }
@@ -1704,7 +1721,7 @@
   DiagList Warnings;
   
 public:
-  
+
   ConsumedWarningsHandler(Sema &S) : S(S) {}
 
   void emitDiagnostics() override {
@@ -1981,7 +1998,8 @@
     if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
       Reporter.setVerbose(true);
 
-    threadSafety::runThreadSafetyAnalysis(AC, Reporter);
+    threadSafety::runThreadSafetyAnalysis(AC, Reporter,
+                                          &S.ThreadSafetyDeclCache);
     Reporter.emitDiagnostics();
   }
 
diff --git a/lib/Sema/CodeCompleteConsumer.cpp b/lib/Sema/CodeCompleteConsumer.cpp
index b2dc2d7..92d2aeb 100644
--- a/lib/Sema/CodeCompleteConsumer.cpp
+++ b/lib/Sema/CodeCompleteConsumer.cpp
@@ -483,6 +483,31 @@
   }
 }
 
+// This function is used solely to preserve the former presentation of overloads
+// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
+// needs to be improved for printing the newer and more detailed overload
+// chunks.
+static std::string getOverloadAsString(const CodeCompletionString &CCS) {
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+
+  for (auto &C : CCS) {
+    switch (C.Kind) {
+    case CodeCompletionString::CK_Informative:
+    case CodeCompletionString::CK_ResultType:
+      OS << "[#" << C.Text << "#]";
+      break;
+
+    case CodeCompletionString::CK_CurrentParameter:
+      OS << "<#" << C.Text << "#>";
+      break;
+
+    default: OS << C.Text; break;
+    }
+  }
+  return OS.str();
+}
+
 void 
 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
                                                         unsigned CurrentArg,
@@ -491,8 +516,9 @@
   for (unsigned I = 0; I != NumCandidates; ++I) {
     if (CodeCompletionString *CCS
           = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
-                                                getAllocator(), CCTUInfo)) {
-      OS << "OVERLOAD: " << CCS->getAsString() << "\n";
+                                                getAllocator(), CCTUInfo,
+                                                includeBriefComments())) {
+      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
     }
   }
 }
diff --git a/lib/Sema/DeclSpec.cpp b/lib/Sema/DeclSpec.cpp
index 7b2e7ff..7bf3e51 100644
--- a/lib/Sema/DeclSpec.cpp
+++ b/lib/Sema/DeclSpec.cpp
@@ -508,14 +508,14 @@
     case SCS_private_extern:
     case SCS_static:
         if (S.getLangOpts().OpenCLVersion < 120) {
-          DiagID   = diag::err_not_opencl_storage_class_specifier;
+          DiagID   = diag::err_opencl_unknown_type_specifier;
           PrevSpec = getSpecifierName(SC);
           return true;
         }
         break;
     case SCS_auto:
     case SCS_register:
-      DiagID   = diag::err_not_opencl_storage_class_specifier;
+      DiagID   = diag::err_opencl_unknown_type_specifier;
       PrevSpec = getSpecifierName(SC);
       return true;
     default:
diff --git a/lib/Sema/JumpDiagnostics.cpp b/lib/Sema/JumpDiagnostics.cpp
index fd75c02..03fcc94 100644
--- a/lib/Sema/JumpDiagnostics.cpp
+++ b/lib/Sema/JumpDiagnostics.cpp
@@ -338,6 +338,36 @@
     return;
   }
 
+  case Stmt::SEHTryStmtClass: {
+    SEHTryStmt *TS = cast<SEHTryStmt>(S);
+    unsigned newParentScope;
+    Scopes.push_back(GotoScope(ParentScope,
+                               diag::note_protected_by_seh_try,
+                               diag::note_exits_seh_try,
+                               TS->getSourceRange().getBegin()));
+    if (Stmt *TryBlock = TS->getTryBlock())
+      BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
+
+    // Jump from __except or __finally into the __try are not allowed either.
+    if (SEHExceptStmt *Except = TS->getExceptHandler()) {
+      Scopes.push_back(GotoScope(ParentScope,
+                                 diag::note_protected_by_seh_except,
+                                 diag::note_exits_seh_except,
+                                 Except->getSourceRange().getBegin()));
+      BuildScopeInformation(Except->getBlock(), 
+                            (newParentScope = Scopes.size()-1));
+    } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
+      Scopes.push_back(GotoScope(ParentScope,
+                                 diag::note_protected_by_seh_finally,
+                                 diag::note_exits_seh_finally,
+                                 Finally->getSourceRange().getBegin()));
+      BuildScopeInformation(Finally->getBlock(), 
+                            (newParentScope = Scopes.size()-1));
+    }
+
+    return;
+  }
+
   default:
     break;
   }
@@ -417,7 +447,8 @@
     unsigned newParentScope;
     // Disallow jumps into the protected statement of an @synchronized, but
     // allow jumps into the object expression it protects.
-    if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
+    if (ObjCAtSynchronizedStmt *AS =
+            dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)) {
       // Recursively walk the AST for the @synchronized object expr, it is
       // evaluated in the normal scope.
       BuildScopeInformation(AS->getSynchExpr(), ParentScope);
@@ -434,14 +465,16 @@
     }
 
     // Disallow jumps into the protected statement of an @autoreleasepool.
-    if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
-      // Recursively walk the AST for the @autoreleasepool part, protected by a new
-      // scope.
+    if (ObjCAutoreleasePoolStmt *AS =
+            dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)) {
+      // Recursively walk the AST for the @autoreleasepool part, protected by a
+      // new scope.
       Scopes.push_back(GotoScope(ParentScope,
                                  diag::note_protected_by_objc_autoreleasepool,
                                  diag::note_exits_objc_autoreleasepool,
                                  AS->getAtLoc()));
-      BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
+      BuildScopeInformation(AS->getSubStmt(),
+                            (newParentScope = Scopes.size() - 1));
       continue;
     }
 
diff --git a/lib/Sema/Scope.cpp b/lib/Sema/Scope.cpp
index 6c79778..eeb2e01 100644
--- a/lib/Sema/Scope.cpp
+++ b/lib/Sema/Scope.cpp
@@ -185,6 +185,9 @@
     } else if (Flags & SEHTryScope) {
       OS << "SEHTryScope";
       Flags &= ~SEHTryScope;
+    } else if (Flags & SEHExceptScope) {
+      OS << "SEHExceptScope";
+      Flags &= ~SEHExceptScope;
     } else if (Flags & OpenMPDirectiveScope) {
       OS << "OpenMPDirectiveScope";
       Flags &= ~OpenMPDirectiveScope;
diff --git a/lib/Sema/ScopeInfo.cpp b/lib/Sema/ScopeInfo.cpp
index 00d9982..f80eadf 100644
--- a/lib/Sema/ScopeInfo.cpp
+++ b/lib/Sema/ScopeInfo.cpp
@@ -33,6 +33,8 @@
   ObjCWarnForNoDesignatedInitChain = false;
   ObjCIsSecondaryInit = false;
   ObjCWarnForNoInitDelegation = false;
+  FirstCXXTryLoc = SourceLocation();
+  FirstSEHTryLoc = SourceLocation();
 
   SwitchStack.clear();
   Returns.clear();
@@ -176,6 +178,8 @@
   // Has this weak object been seen before?
   FunctionScopeInfo::WeakObjectUseMap::iterator Uses;
   if (const ObjCPropertyRefExpr *RefExpr = dyn_cast<ObjCPropertyRefExpr>(E)) {
+    if (!RefExpr->isObjectReceiver())
+      return;
     if (isa<OpaqueValueExpr>(RefExpr->getBase()))
      Uses = WeakObjectUses.find(WeakObjectProfileTy(RefExpr));
     else {
diff --git a/lib/Sema/Sema.cpp b/lib/Sema/Sema.cpp
index 66a0443..5170c24 100644
--- a/lib/Sema/Sema.cpp
+++ b/lib/Sema/Sema.cpp
@@ -102,7 +102,7 @@
     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
     CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
-    TyposCorrected(0), AnalysisWarnings(*this),
+    TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
     VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
     Ident_super(nullptr), Ident___float128(nullptr)
 {
@@ -122,9 +122,7 @@
   PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
                                        &Context);
 
-  ExprEvalContexts.push_back(
-        ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
-                                          false, nullptr, false));
+  ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, false, nullptr, false);
 
   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
 
@@ -195,8 +193,9 @@
   }
 
   // Initialize Microsoft "predefined C++ types".
-  if (PP.getLangOpts().MSVCCompat && PP.getLangOpts().CPlusPlus) {
-    if (IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
+  if (PP.getLangOpts().MSVCCompat) {
+    if (PP.getLangOpts().CPlusPlus &&
+        IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
                         TUScope);
 
@@ -243,8 +242,12 @@
   if (isMultiplexExternalSource)
     delete ExternalSource;
 
+  threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
+
   // Destroys data sharing attributes stack for OpenMP
   DestroyDataSharingAttributesStack();
+
+  assert(DelayedTypos.empty() && "Uncorrected typos!");
 }
 
 /// makeUnavailableInSystemHeader - There is an error in the current
@@ -335,18 +338,6 @@
   if (ExprTy == TypeTy)
     return E;
 
-  // If this is a derived-to-base cast to a through a virtual base, we
-  // need a vtable.
-  if (Kind == CK_DerivedToBase &&
-      BasePathInvolvesVirtualBase(*BasePath)) {
-    QualType T = E->getType();
-    if (const PointerType *Pointer = T->getAs<PointerType>())
-      T = Pointer->getPointeeType();
-    if (const RecordType *RecordTy = T->getAs<RecordType>())
-      MarkVTableUsed(E->getLocStart(),
-                     cast<CXXRecordDecl>(RecordTy->getDecl()));
-  }
-
   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
       ImpCast->setType(Ty);
@@ -678,7 +669,7 @@
   // All delayed member exception specs should be checked or we end up accepting
   // incompatible declarations.
   assert(DelayedDefaultedMemberExceptionSpecs.empty());
-  assert(DelayedDestructorExceptionSpecChecks.empty());
+  assert(DelayedExceptionSpecChecks.empty());
 
   // Remove file scoped decls that turned out to be used.
   UnusedFileScopedDecls.erase(
diff --git a/lib/Sema/SemaAccess.cpp b/lib/Sema/SemaAccess.cpp
index ffdb0aa..37240c2 100644
--- a/lib/Sema/SemaAccess.cpp
+++ b/lib/Sema/SemaAccess.cpp
@@ -1749,14 +1749,14 @@
     return AR_accessible;
 
   CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
-  assert(method->getQualifier());
 
   AccessTarget entity(Context, AccessTarget::Member,
                       cast<CXXRecordDecl>(target->getDeclContext()),
                       DeclAccessPair::make(target, access),
                       /*no instance context*/ QualType());
   entity.setDiag(diag::err_access_friend_function)
-    << method->getQualifierLoc().getSourceRange();
+      << (method->getQualifier() ? method->getQualifierLoc().getSourceRange()
+                                 : method->getNameInfo().getSourceRange());
 
   // We need to bypass delayed-diagnostics because we might be called
   // while the ParsingDeclarator is active.
diff --git a/lib/Sema/SemaAttr.cpp b/lib/Sema/SemaAttr.cpp
index 7629797..e3b66bf 100644
--- a/lib/Sema/SemaAttr.cpp
+++ b/lib/Sema/SemaAttr.cpp
@@ -131,7 +131,7 @@
 
 void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
   if (MSStructPragmaOn)
-    RD->addAttr(MsStructAttr::CreateImplicit(Context));
+    RD->addAttr(MSStructAttr::CreateImplicit(Context));
 
   // FIXME: We should merge AddAlignmentAttributesForRecord with
   // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
diff --git a/lib/Sema/SemaCUDA.cpp b/lib/Sema/SemaCUDA.cpp
index 6671520..6033821 100644
--- a/lib/Sema/SemaCUDA.cpp
+++ b/lib/Sema/SemaCUDA.cpp
@@ -14,6 +14,7 @@
 #include "clang/Sema/Sema.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/SemaDiagnostic.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
@@ -61,32 +62,52 @@
 
 bool Sema::CheckCUDATarget(const FunctionDecl *Caller,
                            const FunctionDecl *Callee) {
-  return CheckCUDATarget(IdentifyCUDATarget(Caller),
-                         IdentifyCUDATarget(Callee));
-}
+  CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
+                     CalleeTarget = IdentifyCUDATarget(Callee);
 
-bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
-                           CUDAFunctionTarget CalleeTarget) {
   // If one of the targets is invalid, the check always fails, no matter what
   // the other target is.
   if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
     return true;
 
-  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
+  // CUDA B.1.1 "The __device__ qualifier declares a function that is [...]
   // Callable from the device only."
   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
     return true;
 
-  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
+  // CUDA B.1.2 "The __global__ qualifier declares a function that is [...]
   // Callable from the host only."
-  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
+  // CUDA B.1.3 "The __host__ qualifier declares a function that is [...]
   // Callable from the host only."
   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
     return true;
 
-  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
-    return true;
+  // CUDA B.1.3 "The __device__ and __host__ qualifiers can be used together
+  // however, in which case the function is compiled for both the host and the
+  // device. The __CUDA_ARCH__ macro [...] can be used to differentiate code
+  // paths between host and device."
+  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) {
+    // If the caller is implicit then the check always passes.
+    if (Caller->isImplicit()) return false;
+
+    bool InDeviceMode = getLangOpts().CUDAIsDevice;
+    if (!InDeviceMode && CalleeTarget != CFT_Host)
+        return true;
+    if (InDeviceMode && CalleeTarget != CFT_Device) {
+      // Allow host device functions to call host functions if explicitly
+      // requested.
+      if (CalleeTarget == CFT_Host &&
+          getLangOpts().CUDAAllowHostCallsFromHostDevice) {
+        Diag(Caller->getLocation(),
+             diag::warn_host_calls_from_host_device)
+            << Callee->getNameAsString() << Caller->getNameAsString();
+        return false;
+      }
+
+      return true;
+    }
+  }
 
   return false;
 }
diff --git a/lib/Sema/SemaCXXScopeSpec.cpp b/lib/Sema/SemaCXXScopeSpec.cpp
index 49e8a15..438ad61 100644
--- a/lib/Sema/SemaCXXScopeSpec.cpp
+++ b/lib/Sema/SemaCXXScopeSpec.cpp
@@ -282,7 +282,11 @@
 
 /// \brief Determines whether the given declaration is an valid acceptable
 /// result for name lookup of a nested-name-specifier.
-bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD) {
+/// \param SD Declaration checked for nested-name-specifier.
+/// \param IsExtension If not null and the declaration is accepted as an
+/// extension, the pointed variable is assigned true.
+bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,
+                                           bool *IsExtension) {
   if (!SD)
     return false;
 
@@ -298,14 +302,23 @@
   QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
   if (T->isDependentType())
     return true;
-  else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
-    if (TD->getUnderlyingType()->isRecordType() ||
-        (Context.getLangOpts().CPlusPlus11 &&
-         TD->getUnderlyingType()->isEnumeralType()))
+  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
+    if (TD->getUnderlyingType()->isRecordType())
       return true;
-  } else if (isa<RecordDecl>(SD) ||
-             (Context.getLangOpts().CPlusPlus11 && isa<EnumDecl>(SD)))
+    if (TD->getUnderlyingType()->isEnumeralType()) {
+      if (Context.getLangOpts().CPlusPlus11)
+        return true;
+      if (IsExtension)
+        *IsExtension = true;
+    }
+  } else if (isa<RecordDecl>(SD)) {
     return true;
+  } else if (isa<EnumDecl>(SD)) {
+    if (Context.getLangOpts().CPlusPlus11)
+      return true;
+    if (IsExtension)
+      *IsExtension = true;
+  }
 
   return false;
 }
@@ -410,9 +423,6 @@
 /// \brief Build a new nested-name-specifier for "identifier::", as described
 /// by ActOnCXXNestedNameSpecifier.
 ///
-/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
-/// that it contains an extra parameter \p ScopeLookupResult.
-///
 /// \param S Scope in which the nested-name-specifier occurs.
 /// \param Identifier Identifier in the sequence "identifier" "::".
 /// \param IdentifierLoc Location of the \p Identifier.
@@ -602,7 +612,13 @@
   }
 
   NamedDecl *SD = Found.getAsSingle<NamedDecl>();
-  if (isAcceptableNestedNameSpecifier(SD)) {
+  bool IsExtension = false;
+  bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);
+  if (!AcceptSpec && IsExtension) {
+    AcceptSpec = true;
+    Diag(IdentifierLoc, diag::ext_nested_name_spec_is_enum);
+  }
+  if (AcceptSpec) {
     if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
         !getLangOpts().CPlusPlus11) {
       // C++03 [basic.lookup.classref]p4:
diff --git a/lib/Sema/SemaCast.cpp b/lib/Sema/SemaCast.cpp
index ae5436c..d28a244 100644
--- a/lib/Sema/SemaCast.cpp
+++ b/lib/Sema/SemaCast.cpp
@@ -142,9 +142,6 @@
   };
 }
 
-static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
-                               bool CheckCVR, bool CheckObjCLifetime);
-
 // The Try functions attempt a specific way of casting. If they succeed, they
 // return TC_Success. If their way of casting is not appropriate for the given
 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
@@ -243,10 +240,8 @@
   QualType DestType = DestTInfo->getType();
 
   // If the type is dependent, we won't do the semantic analysis now.
-  // FIXME: should we check this in a more fine-grained manner?
-  bool TypeDependent = DestType->isDependentType() ||
-                       Ex.get()->isTypeDependent() ||
-                       Ex.get()->isValueDependent();
+  bool TypeDependent =
+      DestType->isDependentType() || Ex.get()->isTypeDependent();
 
   CastOperation Op(*this, DestType, E);
   Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
@@ -394,6 +389,33 @@
 
   S.Diag(opRange.getBegin(), msg) << castType
     << src->getType() << destType << opRange << src->getSourceRange();
+
+  // Detect if both types are (ptr to) class, and note any incompleteness.
+  int DifferentPtrness = 0;
+  QualType From = destType;
+  if (auto Ptr = From->getAs<PointerType>()) {
+    From = Ptr->getPointeeType();
+    DifferentPtrness++;
+  }
+  QualType To = src->getType();
+  if (auto Ptr = To->getAs<PointerType>()) {
+    To = Ptr->getPointeeType();
+    DifferentPtrness--;
+  }
+  if (!DifferentPtrness) {
+    auto RecFrom = From->getAs<RecordType>();
+    auto RecTo = To->getAs<RecordType>();
+    if (RecFrom && RecTo) {
+      auto DeclFrom = RecFrom->getAsCXXRecordDecl();
+      if (!DeclFrom->isCompleteDefinition())
+        S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
+          << DeclFrom->getDeclName();
+      auto DeclTo = RecTo->getAsCXXRecordDecl();
+      if (!DeclTo->isCompleteDefinition())
+        S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
+          << DeclTo->getDeclName();
+    }
+  }
 }
 
 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
@@ -462,7 +484,10 @@
 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
 static bool
 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
-                   bool CheckCVR, bool CheckObjCLifetime) {
+                   bool CheckCVR, bool CheckObjCLifetime,
+                   QualType *TheOffendingSrcType = nullptr,
+                   QualType *TheOffendingDestType = nullptr,
+                   Qualifiers *CastAwayQualifiers = nullptr) {
   // If the only checking we care about is for Objective-C lifetime qualifiers,
   // and we're not in ARC mode, there's nothing to check.
   if (!CheckCVR && CheckObjCLifetime && 
@@ -487,6 +512,8 @@
   // Find the qualifiers. We only care about cvr-qualifiers for the 
   // purpose of this check, because other qualifiers (address spaces, 
   // Objective-C GC, etc.) are part of the type's identity.
+  QualType PrevUnwrappedSrcType = UnwrappedSrcType;
+  QualType PrevUnwrappedDestType = UnwrappedDestType;
   while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
     // Determine the relevant qualifiers at this level.
     Qualifiers SrcQuals, DestQuals;
@@ -497,6 +524,13 @@
     if (CheckCVR) {
       RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
       RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
+
+      if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
+          TheOffendingDestType && CastAwayQualifiers) {
+        *TheOffendingSrcType = PrevUnwrappedSrcType;
+        *TheOffendingDestType = PrevUnwrappedDestType;
+        *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
+      }
     }
     
     if (CheckObjCLifetime &&
@@ -505,6 +539,9 @@
     
     cv1.push_back(RetainedSrcQuals);
     cv2.push_back(RetainedDestQuals);
+
+    PrevUnwrappedSrcType = UnwrappedSrcType;
+    PrevUnwrappedDestType = UnwrappedDestType;
   }
   if (cv1.empty())
     return false;
@@ -655,12 +692,6 @@
     }
 
     Kind = CK_DerivedToBase;
-
-    // If we are casting to or through a virtual base class, we need a
-    // vtable.
-    if (Self.BasePathInvolvesVirtualBase(BasePath))
-      Self.MarkVTableUsed(OpRange.getBegin(), 
-                          cast<CXXRecordDecl>(SrcRecord->getDecl()));
     return;
   }
 
@@ -672,8 +703,6 @@
       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
     SrcExpr = ExprError();
   }
-  Self.MarkVTableUsed(OpRange.getBegin(), 
-                      cast<CXXRecordDecl>(SrcRecord->getDecl()));
 
   // dynamic_cast is not available with -fno-rtti.
   // As an exception, dynamic_cast to void* is available because it doesn't
@@ -1077,6 +1106,14 @@
   if (!CStyle &&
       Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
     return TC_Success;
+
+  // See if it looks like the user is trying to convert between
+  // related record types, and select a better diagnostic if so.
+  if (auto SrcPointer = SrcType->getAs<PointerType>())
+    if (auto DestPointer = DestType->getAs<PointerType>())
+      if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
+          DestPointer->getPointeeType()->getAs<RecordType>())
+       msg = diag::err_bad_cxx_cast_unrelated_class;
   
   // We tried everything. Everything! Nothing works! :-(
   return TC_NotApplicable;
@@ -2200,8 +2237,8 @@
   // address space B is illegal.
   if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
       SrcType->isPointerType()) {
-    if (DestType->getPointeeType().getAddressSpace() !=
-        SrcType->getPointeeType().getAddressSpace()) {
+    const PointerType *DestPtr = DestType->getAs<PointerType>();
+    if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
       Self.Diag(OpRange.getBegin(),
                 diag::err_typecheck_incompatible_address_space)
           << SrcType << DestType << Sema::AA_Casting
@@ -2371,6 +2408,30 @@
 
   if (Kind == CK_BitCast)
     checkCastAlign();
+
+  // -Wcast-qual
+  QualType TheOffendingSrcType, TheOffendingDestType;
+  Qualifiers CastAwayQualifiers;
+  if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
+      CastsAwayConstness(Self, SrcType, DestType, true, false,
+                         &TheOffendingSrcType, &TheOffendingDestType,
+                         &CastAwayQualifiers)) {
+    int qualifiers = -1;
+    if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
+      qualifiers = 0;
+    } else if (CastAwayQualifiers.hasConst()) {
+      qualifiers = 1;
+    } else if (CastAwayQualifiers.hasVolatile()) {
+      qualifiers = 2;
+    }
+    // This is a variant of int **x; const int **y = (const int **)x;
+    if (qualifiers == -1)
+      Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
+        SrcType << DestType;
+    else
+      Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
+        TheOffendingSrcType << TheOffendingDestType << qualifiers;
+  }
 }
 
 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp
index 91ba91e..5a0d8d4 100644
--- a/lib/Sema/SemaChecking.cpp
+++ b/lib/Sema/SemaChecking.cpp
@@ -139,6 +139,91 @@
   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
 }
 
+static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
+  if (checkArgCount(S, BuiltinCall, 2))
+    return true;
+
+  SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
+  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
+  Expr *Call = BuiltinCall->getArg(0);
+  Expr *Chain = BuiltinCall->getArg(1);
+
+  if (Call->getStmtClass() != Stmt::CallExprClass) {
+    S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
+        << Call->getSourceRange();
+    return true;
+  }
+
+  auto CE = cast<CallExpr>(Call);
+  if (CE->getCallee()->getType()->isBlockPointerType()) {
+    S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
+        << Call->getSourceRange();
+    return true;
+  }
+
+  const Decl *TargetDecl = CE->getCalleeDecl();
+  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
+    if (FD->getBuiltinID()) {
+      S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
+          << Call->getSourceRange();
+      return true;
+    }
+
+  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
+    S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
+        << Call->getSourceRange();
+    return true;
+  }
+
+  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
+  if (ChainResult.isInvalid())
+    return true;
+  if (!ChainResult.get()->getType()->isPointerType()) {
+    S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
+        << Chain->getSourceRange();
+    return true;
+  }
+
+  QualType ReturnTy = CE->getCallReturnType(S.Context);
+  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
+  QualType BuiltinTy = S.Context.getFunctionType(
+      ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
+  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
+
+  Builtin =
+      S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
+
+  BuiltinCall->setType(CE->getType());
+  BuiltinCall->setValueKind(CE->getValueKind());
+  BuiltinCall->setObjectKind(CE->getObjectKind());
+  BuiltinCall->setCallee(Builtin);
+  BuiltinCall->setArg(1, ChainResult.get());
+
+  return false;
+}
+
+static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
+                                     Scope::ScopeFlags NeededScopeFlags,
+                                     unsigned DiagID) {
+  // Scopes aren't available during instantiation. Fortunately, builtin
+  // functions cannot be template args so they cannot be formed through template
+  // instantiation. Therefore checking once during the parse is sufficient.
+  if (!SemaRef.ActiveTemplateInstantiations.empty())
+    return false;
+
+  Scope *S = SemaRef.getCurScope();
+  while (S && !S->isSEHExceptScope())
+    S = S->getParent();
+  if (!S || !(S->getFlags() & NeededScopeFlags)) {
+    auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
+    SemaRef.Diag(TheCall->getExprLoc(), DiagID)
+        << DRE->getDecl()->getIdentifier();
+    return true;
+  }
+
+  return false;
+}
+
 ExprResult
 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
                                CallExpr *TheCall) {
@@ -393,6 +478,27 @@
   case Builtin::BI__builtin___vsnprintf_chk:
     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
     break;
+
+  case Builtin::BI__builtin_call_with_static_chain:
+    if (SemaBuiltinCallWithStaticChain(*this, TheCall))
+      return ExprError();
+    break;
+
+  case Builtin::BI__exception_code:
+  case Builtin::BI_exception_code: {
+    if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
+                                 diag::err_seh___except_block))
+      return ExprError();
+    break;
+  }
+  case Builtin::BI__exception_info:
+  case Builtin::BI_exception_info: {
+    if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
+                                 diag::err_seh___except_filter))
+      return ExprError();
+    break;
+  }
+
   }
 
   // Since the target specific builtins for each arch overlap, only check those
@@ -768,12 +874,71 @@
 }
 
 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
+  unsigned i = 0, l = 0, u = 0;
   switch (BuiltinID) {
-  case X86::BI_mm_prefetch:
-    // This is declared to take (const char*, int)
-    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
+  default: return false;
+  case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
+  case X86::BI__builtin_ia32_vextractf128_pd256:
+  case X86::BI__builtin_ia32_vextractf128_ps256:
+  case X86::BI__builtin_ia32_vextractf128_si256:
+  case X86::BI__builtin_ia32_extract128i256: i = 1, l = 0, u = 1; break;
+  case X86::BI__builtin_ia32_vinsertf128_pd256:
+  case X86::BI__builtin_ia32_vinsertf128_ps256:
+  case X86::BI__builtin_ia32_vinsertf128_si256:
+  case X86::BI__builtin_ia32_insert128i256: i = 2, l = 0; u = 1; break;
+  case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
+  case X86::BI__builtin_ia32_vpermil2pd:
+  case X86::BI__builtin_ia32_vpermil2pd256:
+  case X86::BI__builtin_ia32_vpermil2ps:
+  case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
+  case X86::BI__builtin_ia32_cmpb128_mask:
+  case X86::BI__builtin_ia32_cmpw128_mask:
+  case X86::BI__builtin_ia32_cmpd128_mask:
+  case X86::BI__builtin_ia32_cmpq128_mask:
+  case X86::BI__builtin_ia32_cmpb256_mask:
+  case X86::BI__builtin_ia32_cmpw256_mask:
+  case X86::BI__builtin_ia32_cmpd256_mask:
+  case X86::BI__builtin_ia32_cmpq256_mask:
+  case X86::BI__builtin_ia32_cmpb512_mask:
+  case X86::BI__builtin_ia32_cmpw512_mask:
+  case X86::BI__builtin_ia32_cmpd512_mask:
+  case X86::BI__builtin_ia32_cmpq512_mask:
+  case X86::BI__builtin_ia32_ucmpb128_mask:
+  case X86::BI__builtin_ia32_ucmpw128_mask:
+  case X86::BI__builtin_ia32_ucmpd128_mask:
+  case X86::BI__builtin_ia32_ucmpq128_mask:
+  case X86::BI__builtin_ia32_ucmpb256_mask:
+  case X86::BI__builtin_ia32_ucmpw256_mask:
+  case X86::BI__builtin_ia32_ucmpd256_mask:
+  case X86::BI__builtin_ia32_ucmpq256_mask:
+  case X86::BI__builtin_ia32_ucmpb512_mask:
+  case X86::BI__builtin_ia32_ucmpw512_mask:
+  case X86::BI__builtin_ia32_ucmpd512_mask:
+  case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
+  case X86::BI__builtin_ia32_roundps:
+  case X86::BI__builtin_ia32_roundpd:
+  case X86::BI__builtin_ia32_roundps256:
+  case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
+  case X86::BI__builtin_ia32_roundss:
+  case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
+  case X86::BI__builtin_ia32_cmpps:
+  case X86::BI__builtin_ia32_cmpss:
+  case X86::BI__builtin_ia32_cmppd:
+  case X86::BI__builtin_ia32_cmpsd:
+  case X86::BI__builtin_ia32_cmpps256:
+  case X86::BI__builtin_ia32_cmppd256:
+  case X86::BI__builtin_ia32_cmpps512_mask:
+  case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
+  case X86::BI__builtin_ia32_vpcomub:
+  case X86::BI__builtin_ia32_vpcomuw:
+  case X86::BI__builtin_ia32_vpcomud:
+  case X86::BI__builtin_ia32_vpcomuq:
+  case X86::BI__builtin_ia32_vpcomb:
+  case X86::BI__builtin_ia32_vpcomw:
+  case X86::BI__builtin_ia32_vpcomd:
+  case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
   }
-  return false;
+  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
 }
 
 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
@@ -1268,6 +1433,11 @@
         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
       return ExprError();
     }
+    if (IsC11 && ValType->isPointerType() &&
+        RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
+                            diag::err_incomplete_type)) {
+      return ExprError();
+    }
   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
     // For __atomic_*_n operations, the value type must be a scalar integral or
     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
@@ -2205,7 +2375,7 @@
   if (Arg->isInstantiationDependent()) return false;
 
   if (Arg->HasSideEffects(Context))
-    return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
+    Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
       << Arg->getSourceRange()
       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
 
@@ -2507,6 +2677,8 @@
   .Case("strftime", FST_Strftime)
   .Case("strfmon", FST_Strfmon)
   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
+  .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
+  .Case("os_trace", FST_OSTrace)
   .Default(FST_Unknown);
 }
 
@@ -2977,10 +3149,7 @@
   if (InFunctionCall) {
     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
     D << StringRange;
-    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
-         I != E; ++I) {
-      D << *I;
-    }
+    D << FixIt;
   } else {
     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
       << ArgumentExpr->getSourceRange();
@@ -2990,10 +3159,7 @@
              diag::note_format_string_defined);
 
     Note << StringRange;
-    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
-         I != E; ++I) {
-      Note << *I;
-    }
+    Note << FixIt;
   }
 }
 
@@ -3288,6 +3454,43 @@
     CoveredArgs.set(argIndex);
   }
 
+  // FreeBSD kernel extensions.
+  if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
+      CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
+    // We need at least two arguments.
+    if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
+      return false;
+
+    // Claim the second argument.
+    CoveredArgs.set(argIndex + 1);
+
+    // Type check the first argument (int for %b, pointer for %D)
+    const Expr *Ex = getDataArg(argIndex);
+    const analyze_printf::ArgType &AT =
+      (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
+        ArgType(S.Context.IntTy) : ArgType::CPointerTy;
+    if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
+      EmitFormatDiagnostic(
+        S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
+        << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
+        << false << Ex->getSourceRange(),
+        Ex->getLocStart(), /*IsStringLocation*/false,
+        getSpecifierRange(startSpecifier, specifierLen));
+
+    // Type check the second argument (char * for both %b and %D)
+    Ex = getDataArg(argIndex + 1);
+    const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
+    if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
+      EmitFormatDiagnostic(
+        S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
+        << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
+        << false << Ex->getSourceRange(),
+        Ex->getLocStart(), /*IsStringLocation*/false,
+        getSpecifierRange(startSpecifier, specifierLen));
+
+     return true;
+  }
+
   // Check for using an Objective-C specific conversion specifier
   // in a non-ObjC literal.
   if (!ObjCContext && CS.isObjCArg()) {
@@ -3911,15 +4114,17 @@
     return;
   }
   
-  if (Type == FST_Printf || Type == FST_NSString) {
+  if (Type == FST_Printf || Type == FST_NSString ||
+      Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
-                         numDataArgs, (Type == FST_NSString),
+                         numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
                          Str, HasVAListArg, Args, format_idx,
                          inFunctionCall, CallType, CheckedVarArgs);
   
     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
                                                   getLangOpts(),
-                                                  Context.getTargetInfo()))
+                                                  Context.getTargetInfo(),
+                                                  Type == FST_FreeBSDKPrintf))
       H.DoneProcessing();
   } else if (Type == FST_Scanf) {
     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
@@ -4904,7 +5109,7 @@
     DeclRefExpr *DR = cast<DeclRefExpr>(E);
 
     // If we leave the immediate function, the lifetime isn't about to end.
-    if (DR->refersToEnclosingLocal())
+    if (DR->refersToEnclosingVariableOrCapture())
       return nullptr;
 
     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
@@ -5071,7 +5276,7 @@
     DeclRefExpr *DR = cast<DeclRefExpr>(E);
 
     // If we leave the immediate function, the lifetime isn't about to end.
-    if (DR->refersToEnclosingLocal())
+    if (DR->refersToEnclosingVariableOrCapture())
       return nullptr;
 
     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
@@ -6569,8 +6774,11 @@
       E = POE->getResultExpr();
   }
   
-  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
-    return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
+  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
+    if (OVE->getSourceExpr())
+      AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
+    return;
+  }
   
   // Skip past explicit casts.
   if (isa<ExplicitCastExpr>(E)) {
@@ -6617,11 +6825,11 @@
   if (BO && BO->isLogicalOp()) {
     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
-      ::CheckBoolLikeConversion(S, SubExpr, SubExpr->getExprLoc());
+      ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
 
     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
-      ::CheckBoolLikeConversion(S, SubExpr, SubExpr->getExprLoc());
+      ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
   }
 
   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
@@ -6652,7 +6860,7 @@
     if (!M->getMemberDecl()->getType()->isReferenceType())
       return false;
   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
-    if (!Call->getCallReturnType()->isReferenceType())
+    if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
       return false;
     FD = Call->getDirectCallee();
   } else {
@@ -6766,7 +6974,8 @@
         }
         if (!AttrNonNull.empty())
           for (unsigned i = 0; i < NumArgs; ++i)
-            if (FD->getParamDecl(i) == PV && AttrNonNull[i]) {
+            if (FD->getParamDecl(i) == PV &&
+                (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
               std::string Str;
               llvm::raw_string_ostream S(Str);
               E->printPretty(S, nullptr, getPrintingPolicy());
@@ -7014,11 +7223,12 @@
       Self.ModAsSideEffect = &ModAsSideEffect;
     }
     ~SequencedSubexpression() {
-      for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
-        UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
-        U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
-        Self.addUsage(U, ModAsSideEffect[I].first,
-                      ModAsSideEffect[I].second.Use, UK_ModAsValue);
+      for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
+           MI != ME; ++MI) {
+        UsageInfo &U = Self.UsageMap[MI->first];
+        auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
+        Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
+        SideEffectUsage = MI->second;
       }
       Self.ModAsSideEffect = OldModAsSideEffect;
     }
@@ -8251,6 +8461,96 @@
   }
 }
 
+//===--- CHECK: Warn on self move with std::move. -------------------------===//
+
+/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
+void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
+                             SourceLocation OpLoc) {
+
+  if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
+    return;
+
+  if (!ActiveTemplateInstantiations.empty())
+    return;
+
+  // Strip parens and casts away.
+  LHSExpr = LHSExpr->IgnoreParenImpCasts();
+  RHSExpr = RHSExpr->IgnoreParenImpCasts();
+
+  // Check for a call expression
+  const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
+  if (!CE || CE->getNumArgs() != 1)
+    return;
+
+  // Check for a call to std::move
+  const FunctionDecl *FD = CE->getDirectCallee();
+  if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
+      !FD->getIdentifier()->isStr("move"))
+    return;
+
+  // Get argument from std::move
+  RHSExpr = CE->getArg(0);
+
+  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
+  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
+
+  // Two DeclRefExpr's, check that the decls are the same.
+  if (LHSDeclRef && RHSDeclRef) {
+    if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
+      return;
+    if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
+        RHSDeclRef->getDecl()->getCanonicalDecl())
+      return;
+
+    Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
+                                        << LHSExpr->getSourceRange()
+                                        << RHSExpr->getSourceRange();
+    return;
+  }
+
+  // Member variables require a different approach to check for self moves.
+  // MemberExpr's are the same if every nested MemberExpr refers to the same
+  // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
+  // the base Expr's are CXXThisExpr's.
+  const Expr *LHSBase = LHSExpr;
+  const Expr *RHSBase = RHSExpr;
+  const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
+  const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
+  if (!LHSME || !RHSME)
+    return;
+
+  while (LHSME && RHSME) {
+    if (LHSME->getMemberDecl()->getCanonicalDecl() !=
+        RHSME->getMemberDecl()->getCanonicalDecl())
+      return;
+
+    LHSBase = LHSME->getBase();
+    RHSBase = RHSME->getBase();
+    LHSME = dyn_cast<MemberExpr>(LHSBase);
+    RHSME = dyn_cast<MemberExpr>(RHSBase);
+  }
+
+  LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
+  RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
+  if (LHSDeclRef && RHSDeclRef) {
+    if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
+      return;
+    if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
+        RHSDeclRef->getDecl()->getCanonicalDecl())
+      return;
+
+    Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
+                                        << LHSExpr->getSourceRange()
+                                        << RHSExpr->getSourceRange();
+    return;
+  }
+
+  if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
+    Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
+                                        << LHSExpr->getSourceRange()
+                                        << RHSExpr->getSourceRange();
+}
+
 //===--- Layout compatibility ----------------------------------------------//
 
 namespace {
diff --git a/lib/Sema/SemaCodeComplete.cpp b/lib/Sema/SemaCodeComplete.cpp
index 50d5134..80238e5 100644
--- a/lib/Sema/SemaCodeComplete.cpp
+++ b/lib/Sema/SemaCodeComplete.cpp
@@ -495,7 +495,6 @@
   AsNestedNameSpecifier = false;
 
   ND = ND->getUnderlyingDecl();
-  unsigned IDNS = ND->getIdentifierNamespace();
 
   // Skip unnamed entities.
   if (!ND->getDeclName())
@@ -503,7 +502,7 @@
   
   // Friend declarations and declarations introduced due to friends are never
   // added as results.
-  if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
+  if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
     return false;
   
   // Class template (partial) specializations are never added as results.
@@ -800,8 +799,8 @@
   DeclarationName ConstructorName
     = Context.DeclarationNames.getCXXConstructorName(
                                            Context.getCanonicalType(RecordTy));
-  DeclContext::lookup_const_result Ctors = Record->lookup(ConstructorName);
-  for (DeclContext::lookup_const_iterator I = Ctors.begin(),
+  DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
+  for (DeclContext::lookup_iterator I = Ctors.begin(),
                                           E = Ctors.end();
        I != E; ++I) {
     R.Declaration = *I;
@@ -2309,7 +2308,11 @@
                                        unsigned Start = 0,
                                        bool InDefaultArg = false) {
   bool FirstParameter = true;
-  
+
+  // Prefer to take the template parameter names from the first declaration of
+  // the template.
+  Template = cast<TemplateDecl>(Template->getCanonicalDecl());
+
   TemplateParameterList *Params = Template->getTemplateParameters();
   TemplateParameterList::iterator PEnd = Params->end();
   if (MaxParameters)
@@ -2812,73 +2815,116 @@
   return Result.TakeString();
 }
 
+/// \brief Add function overload parameter chunks to the given code completion
+/// string.
+static void AddOverloadParameterChunks(ASTContext &Context,
+                                       const PrintingPolicy &Policy,
+                                       const FunctionDecl *Function,
+                                       const FunctionProtoType *Prototype,
+                                       CodeCompletionBuilder &Result,
+                                       unsigned CurrentArg,
+                                       unsigned Start = 0,
+                                       bool InOptional = false) {
+  bool FirstParameter = true;
+  unsigned NumParams = Function ? Function->getNumParams()
+                                : Prototype->getNumParams();
+
+  for (unsigned P = Start; P != NumParams; ++P) {
+    if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
+      // When we see an optional default argument, put that argument and
+      // the remaining default arguments into a new, optional string.
+      CodeCompletionBuilder Opt(Result.getAllocator(),
+                                Result.getCodeCompletionTUInfo());
+      if (!FirstParameter)
+        Opt.AddChunk(CodeCompletionString::CK_Comma);
+      // Optional sections are nested.
+      AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
+                                 CurrentArg, P, /*InOptional=*/true);
+      Result.AddOptionalChunk(Opt.TakeString());
+      return;
+    }
+
+    if (FirstParameter)
+      FirstParameter = false;
+    else
+      Result.AddChunk(CodeCompletionString::CK_Comma);
+
+    InOptional = false;
+
+    // Format the placeholder string.
+    std::string Placeholder;
+    if (Function)
+      Placeholder = FormatFunctionParameter(Context, Policy,
+                                            Function->getParamDecl(P));
+    else
+      Placeholder = Prototype->getParamType(P).getAsString(Policy);
+
+    if (P == CurrentArg)
+      Result.AddCurrentParameterChunk(
+        Result.getAllocator().CopyString(Placeholder));
+    else
+      Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
+  }
+
+  if (Prototype && Prototype->isVariadic()) {
+    CodeCompletionBuilder Opt(Result.getAllocator(),
+                              Result.getCodeCompletionTUInfo());
+    if (!FirstParameter)
+      Opt.AddChunk(CodeCompletionString::CK_Comma);
+
+    if (CurrentArg < NumParams)
+      Opt.AddPlaceholderChunk("...");
+    else
+      Opt.AddCurrentParameterChunk("...");
+
+    Result.AddOptionalChunk(Opt.TakeString());
+  }
+}
+
 CodeCompletionString *
 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
-                                                          unsigned CurrentArg,
-                                                               Sema &S,
-                                     CodeCompletionAllocator &Allocator,
-                                     CodeCompletionTUInfo &CCTUInfo) const {
+                                             unsigned CurrentArg, Sema &S,
+                                             CodeCompletionAllocator &Allocator,
+                                             CodeCompletionTUInfo &CCTUInfo,
+                                             bool IncludeBriefComments) const {
   PrintingPolicy Policy = getCompletionPrintingPolicy(S);
 
   // FIXME: Set priority, availability appropriately.
   CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
   FunctionDecl *FDecl = getFunction();
-  AddResultTypeChunk(S.Context, Policy, FDecl, Result);
-  const FunctionProtoType *Proto 
+  const FunctionProtoType *Proto
     = dyn_cast<FunctionProtoType>(getFunctionType());
   if (!FDecl && !Proto) {
     // Function without a prototype. Just give the return type and a 
     // highlighted ellipsis.
     const FunctionType *FT = getFunctionType();
-    Result.AddTextChunk(GetCompletionTypeString(FT->getReturnType(), S.Context,
-                                                Policy, Result.getAllocator()));
+    Result.AddResultTypeChunk(Result.getAllocator().CopyString(
+      FT->getReturnType().getAsString(Policy)));
     Result.AddChunk(CodeCompletionString::CK_LeftParen);
     Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
     Result.AddChunk(CodeCompletionString::CK_RightParen);
     return Result.TakeString();
   }
-  
-  if (FDecl)
+
+  if (FDecl) {
+    if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
+      if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
+          FDecl->getParamDecl(CurrentArg)))
+        Result.addBriefComment(RC->getBriefText(S.getASTContext()));
+    AddResultTypeChunk(S.Context, Policy, FDecl, Result);
     Result.AddTextChunk(
-                    Result.getAllocator().CopyString(FDecl->getNameAsString()));
-  else
-    Result.AddTextChunk(Result.getAllocator().CopyString(
+      Result.getAllocator().CopyString(FDecl->getNameAsString()));
+  } else {
+    Result.AddResultTypeChunk(
+      Result.getAllocator().CopyString(
         Proto->getReturnType().getAsString(Policy)));
+  }
 
   Result.AddChunk(CodeCompletionString::CK_LeftParen);
-  unsigned NumParams = FDecl ? FDecl->getNumParams() : Proto->getNumParams();
-  for (unsigned I = 0; I != NumParams; ++I) {
-    if (I)
-      Result.AddChunk(CodeCompletionString::CK_Comma);
-    
-    std::string ArgString;
-    QualType ArgType;
-    
-    if (FDecl) {
-      ArgString = FDecl->getParamDecl(I)->getNameAsString();
-      ArgType = FDecl->getParamDecl(I)->getOriginalType();
-    } else {
-      ArgType = Proto->getParamType(I);
-    }
-    
-    ArgType.getAsStringInternal(ArgString, Policy);
-    
-    if (I == CurrentArg)
-      Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
-                      Result.getAllocator().CopyString(ArgString));
-    else
-      Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
-  }
-  
-  if (Proto && Proto->isVariadic()) {
-    Result.AddChunk(CodeCompletionString::CK_Comma);
-    if (CurrentArg < NumParams)
-      Result.AddTextChunk("...");
-    else
-      Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
-  }
+  AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
+                             CurrentArg);
   Result.AddChunk(CodeCompletionString::CK_RightParen);
-  
+
   return Result.TakeString();
 }
 
@@ -3816,7 +3862,74 @@
   return false;
 }
 
-void Sema::CodeCompleteCall(Scope *S, Expr *FnIn, ArrayRef<Expr *> Args) {
+typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
+
+static void mergeCandidatesWithResults(Sema &SemaRef,
+                                      SmallVectorImpl<ResultCandidate> &Results,
+                                       OverloadCandidateSet &CandidateSet,
+                                       SourceLocation Loc) {
+  if (!CandidateSet.empty()) {
+    // Sort the overload candidate set by placing the best overloads first.
+    std::stable_sort(
+        CandidateSet.begin(), CandidateSet.end(),
+        [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
+          return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
+        });
+
+    // Add the remaining viable overload candidates as code-completion results.
+    for (auto &Candidate : CandidateSet)
+      if (Candidate.Viable)
+        Results.push_back(ResultCandidate(Candidate.Function));
+  }
+}
+
+/// \brief Get the type of the Nth parameter from a given set of overload
+/// candidates.
+static QualType getParamType(Sema &SemaRef,
+                             ArrayRef<ResultCandidate> Candidates,
+                             unsigned N) {
+
+  // Given the overloads 'Candidates' for a function call matching all arguments
+  // up to N, return the type of the Nth parameter if it is the same for all
+  // overload candidates.
+  QualType ParamType;
+  for (auto &Candidate : Candidates) {
+    if (auto FType = Candidate.getFunctionType())
+      if (auto Proto = dyn_cast<FunctionProtoType>(FType))
+        if (N < Proto->getNumParams()) {
+          if (ParamType.isNull())
+            ParamType = Proto->getParamType(N);
+          else if (!SemaRef.Context.hasSameUnqualifiedType(
+                        ParamType.getNonReferenceType(),
+                        Proto->getParamType(N).getNonReferenceType()))
+            // Otherwise return a default-constructed QualType.
+            return QualType();
+        }
+  }
+
+  return ParamType;
+}
+
+static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
+                                    MutableArrayRef<ResultCandidate> Candidates,
+                                        unsigned CurrentArg,
+                                 bool CompleteExpressionWithCurrentArg = true) {
+  QualType ParamType;
+  if (CompleteExpressionWithCurrentArg)
+    ParamType = getParamType(SemaRef, Candidates, CurrentArg);
+
+  if (ParamType.isNull())
+    SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
+  else
+    SemaRef.CodeCompleteExpression(S, ParamType);
+
+  if (!Candidates.empty())
+    SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
+                                                     Candidates.data(),
+                                                     Candidates.size());
+}
+
+void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
   if (!CodeCompleter)
     return;
 
@@ -3825,7 +3938,7 @@
   // results. We may want to revisit this strategy in the future,
   // e.g., by merging the two kinds of results.
 
-  Expr *Fn = (Expr *)FnIn;
+  // FIXME: Provide support for variadic template functions.
 
   // Ignore type-dependent call expressions entirely.
   if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
@@ -3838,92 +3951,114 @@
   SourceLocation Loc = Fn->getExprLoc();
   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
 
-  // FIXME: What if we're calling something that isn't a function declaration?
-  // FIXME: What if we're calling a pseudo-destructor?
-  // FIXME: What if we're calling a member function?
-  
-  typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
   SmallVector<ResultCandidate, 8> Results;
 
   Expr *NakedFn = Fn->IgnoreParenCasts();
-  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
+  if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
     AddOverloadedCallCandidates(ULE, Args, CandidateSet,
-                                /*PartialOverloading=*/ true);
-  else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
-    FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
-    if (FDecl) {
-      if (!getLangOpts().CPlusPlus || 
-          !FDecl->getType()->getAs<FunctionProtoType>())
-        Results.push_back(ResultCandidate(FDecl));
-      else
-        // FIXME: access?
-        AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), Args,
-                             CandidateSet, false, /*PartialOverloading*/true);
+                                /*PartialOverloading=*/true);
+  else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
+    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
+    if (UME->hasExplicitTemplateArgs()) {
+      UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
+      TemplateArgs = &TemplateArgsBuffer;
     }
-  }
-  
-  QualType ParamType;
-  
-  if (!CandidateSet.empty()) {
-    // Sort the overload candidate set by placing the best overloads first.
-    std::stable_sort(
-        CandidateSet.begin(), CandidateSet.end(),
-        [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
-          return isBetterOverloadCandidate(*this, X, Y, Loc);
-        });
-
-    // Add the remaining viable overload candidates as code-completion reslults.
-    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
-                                     CandEnd = CandidateSet.end();
-         Cand != CandEnd; ++Cand) {
-      if (Cand->Viable)
-        Results.push_back(ResultCandidate(Cand->Function));
-    }
-
-    // From the viable candidates, try to determine the type of this parameter.
-    for (unsigned I = 0, N = Results.size(); I != N; ++I) {
-      if (const FunctionType *FType = Results[I].getFunctionType())
-        if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
-          if (Args.size() < Proto->getNumParams()) {
-            if (ParamType.isNull())
-              ParamType = Proto->getParamType(Args.size());
-            else if (!Context.hasSameUnqualifiedType(
-                          ParamType.getNonReferenceType(),
-                          Proto->getParamType(Args.size())
-                              .getNonReferenceType())) {
-              ParamType = QualType();
-              break;
-            }
-          }
-    }
+    SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
+    ArgExprs.append(Args.begin(), Args.end());
+    UnresolvedSet<8> Decls;
+    Decls.append(UME->decls_begin(), UME->decls_end());
+    AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
+                          /*SuppressUsedConversions=*/false,
+                          /*PartialOverloading=*/true);
   } else {
-    // Try to determine the parameter type from the type of the expression
-    // being called.
-    QualType FunctionType = Fn->getType();
-    if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
-      FunctionType = Ptr->getPointeeType();
-    else if (const BlockPointerType *BlockPtr
-                                    = FunctionType->getAs<BlockPointerType>())
-      FunctionType = BlockPtr->getPointeeType();
-    else if (const MemberPointerType *MemPtr
-                                    = FunctionType->getAs<MemberPointerType>())
-      FunctionType = MemPtr->getPointeeType();
-    
-    if (const FunctionProtoType *Proto
-                                  = FunctionType->getAs<FunctionProtoType>()) {
-      if (Args.size() < Proto->getNumParams())
-        ParamType = Proto->getParamType(Args.size());
+    FunctionDecl *FD = nullptr;
+    if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
+      FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
+    else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
+      FD = dyn_cast<FunctionDecl>(DRE->getDecl());
+    if (FD) { // We check whether it's a resolved function declaration.
+      if (!getLangOpts().CPlusPlus ||
+          !FD->getType()->getAs<FunctionProtoType>())
+        Results.push_back(ResultCandidate(FD));
+      else
+        AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
+                             Args, CandidateSet,
+                             /*SuppressUsedConversions=*/false,
+                             /*PartialOverloading=*/true);
+
+    } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
+      // If expression's type is CXXRecordDecl, it may overload the function
+      // call operator, so we check if it does and add them as candidates.
+      // A complete type is needed to lookup for member function call operators.
+      if (!RequireCompleteType(Loc, NakedFn->getType(), 0)) {
+        DeclarationName OpName = Context.DeclarationNames
+                                 .getCXXOperatorName(OO_Call);
+        LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
+        LookupQualifiedName(R, DC);
+        R.suppressDiagnostics();
+        SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
+        ArgExprs.append(Args.begin(), Args.end());
+        AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
+                              /*ExplicitArgs=*/nullptr,
+                              /*SuppressUsedConversions=*/false,
+                              /*PartialOverloading=*/true);
+      }
+    } else {
+      // Lastly we check whether expression's type is function pointer or
+      // function.
+      QualType T = NakedFn->getType();
+      if (!T->getPointeeType().isNull())
+        T = T->getPointeeType();
+
+      if (auto FP = T->getAs<FunctionProtoType>()) {
+        if (!TooManyArguments(FP->getNumParams(), Args.size(),
+                             /*PartialOverloading=*/true) ||
+            FP->isVariadic())
+          Results.push_back(ResultCandidate(FP));
+      } else if (auto FT = T->getAs<FunctionType>())
+        // No prototype and declaration, it may be a K & R style function.
+        Results.push_back(ResultCandidate(FT));
     }
   }
 
-  if (ParamType.isNull())
-    CodeCompleteOrdinaryName(S, PCC_Expression);
-  else
-    CodeCompleteExpression(S, ParamType);
-  
-  if (!Results.empty())
-    CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.data(),
-                                             Results.size());
+  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
+  CodeCompleteOverloadResults(*this, S, Results, Args.size(),
+                              !CandidateSet.empty());
+}
+
+void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
+                                   ArrayRef<Expr *> Args) {
+  if (!CodeCompleter)
+    return;
+
+  // A complete type is needed to lookup for constructors.
+  if (RequireCompleteType(Loc, Type, 0))
+    return;
+
+  // FIXME: Provide support for member initializers.
+  // FIXME: Provide support for variadic template constructors.
+
+  OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
+
+  for (auto C : LookupConstructors(Type->getAsCXXRecordDecl())) {
+    if (auto FD = dyn_cast<FunctionDecl>(C)) {
+      AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
+                           Args, CandidateSet,
+                           /*SuppressUsedConversions=*/false,
+                           /*PartialOverloading=*/true);
+    } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
+      AddTemplateOverloadCandidate(FTD,
+                                   DeclAccessPair::make(FTD, C->getAccess()),
+                                   /*ExplicitTemplateArgs=*/nullptr,
+                                   Args, CandidateSet,
+                                   /*SuppressUsedConversions=*/false,
+                                   /*PartialOverloading=*/true);
+    }
+  }
+
+  SmallVector<ResultCandidate, 8> Results;
+  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
+  CodeCompleteOverloadResults(*this, S, Results, Args.size());
 }
 
 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
@@ -5404,13 +5539,13 @@
                                        MEnd = SemaRef.MethodPool.end();
          M != MEnd; ++M) {
       for (ObjCMethodList *MethList = &M->second.second;
-           MethList && MethList->Method; 
+           MethList && MethList->getMethod(); 
            MethList = MethList->getNext()) {
-        if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents))
+        if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
           continue;
 
-        Result R(MethList->Method, Results.getBasePriority(MethList->Method),
-                 nullptr);
+        Result R(MethList->getMethod(),
+                 Results.getBasePriority(MethList->getMethod()), nullptr);
         R.StartParameter = SelIdents.size();
         R.AllParametersAreInformative = false;
         Results.MaybeAddResult(R, SemaRef.CurContext);
@@ -5577,16 +5712,16 @@
                                     MEnd = MethodPool.end();
          M != MEnd; ++M) {
       for (ObjCMethodList *MethList = &M->second.first;
-           MethList && MethList->Method; 
+           MethList && MethList->getMethod(); 
            MethList = MethList->getNext()) {
-        if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents))
+        if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
           continue;
         
-        if (!Selectors.insert(MethList->Method->getSelector()).second)
+        if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
           continue;
 
-        Result R(MethList->Method, Results.getBasePriority(MethList->Method),
-                 nullptr);
+        Result R(MethList->getMethod(),
+                 Results.getBasePriority(MethList->getMethod()), nullptr);
         R.StartParameter = SelIdents.size();
         R.AllParametersAreInformative = false;
         Results.MaybeAddResult(R, CurContext);
@@ -6994,16 +7129,18 @@
        M != MEnd; ++M) {
     for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
                                                        &M->second.second;
-         MethList && MethList->Method; 
+         MethList && MethList->getMethod(); 
          MethList = MethList->getNext()) {
-      if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents))
+      if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
         continue;
       
       if (AtParameterName) {
         // Suggest parameter names we've seen before.
         unsigned NumSelIdents = SelIdents.size();
-        if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
-          ParmVarDecl *Param = MethList->Method->parameters()[NumSelIdents-1];
+        if (NumSelIdents &&
+            NumSelIdents <= MethList->getMethod()->param_size()) {
+          ParmVarDecl *Param =
+              MethList->getMethod()->parameters()[NumSelIdents - 1];
           if (Param->getIdentifier()) {
             CodeCompletionBuilder Builder(Results.getAllocator(),
                                           Results.getCodeCompletionTUInfo());
@@ -7016,8 +7153,8 @@
         continue;
       }
 
-      Result R(MethList->Method, Results.getBasePriority(MethList->Method),
-               nullptr);
+      Result R(MethList->getMethod(),
+               Results.getBasePriority(MethList->getMethod()), nullptr);
       R.StartParameter = SelIdents.size();
       R.AllParametersAreInformative = false;
       R.DeclaringEntity = true;
diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp
index b63863e..e254773 100644
--- a/lib/Sema/SemaDecl.cpp
+++ b/lib/Sema/SemaDecl.cpp
@@ -128,45 +128,85 @@
   return false;
 }
 
+namespace {
+enum class UnqualifiedTypeNameLookupResult {
+  NotFound,
+  FoundNonType,
+  FoundType
+};
+} // namespace
+
+/// \brief Tries to perform unqualified lookup of the type decls in bases for
+/// dependent class.
+/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
+/// type decl, \a FoundType if only type decls are found.
+static UnqualifiedTypeNameLookupResult
+lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
+                                SourceLocation NameLoc,
+                                const CXXRecordDecl *RD) {
+  if (!RD->hasDefinition())
+    return UnqualifiedTypeNameLookupResult::NotFound;
+  // Look for type decls in base classes.
+  UnqualifiedTypeNameLookupResult FoundTypeDecl =
+      UnqualifiedTypeNameLookupResult::NotFound;
+  for (const auto &Base : RD->bases()) {
+    const CXXRecordDecl *BaseRD = nullptr;
+    if (auto *BaseTT = Base.getType()->getAs<TagType>())
+      BaseRD = BaseTT->getAsCXXRecordDecl();
+    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
+      // Look for type decls in dependent base classes that have known primary
+      // templates.
+      if (!TST || !TST->isDependentType())
+        continue;
+      auto *TD = TST->getTemplateName().getAsTemplateDecl();
+      if (!TD)
+        continue;
+      auto *BasePrimaryTemplate =
+          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
+      if (!BasePrimaryTemplate)
+        continue;
+      BaseRD = BasePrimaryTemplate;
+    }
+    if (BaseRD) {
+      for (NamedDecl *ND : BaseRD->lookup(&II)) {
+        if (!isa<TypeDecl>(ND))
+          return UnqualifiedTypeNameLookupResult::FoundNonType;
+        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
+      }
+      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
+        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
+        case UnqualifiedTypeNameLookupResult::FoundNonType:
+          return UnqualifiedTypeNameLookupResult::FoundNonType;
+        case UnqualifiedTypeNameLookupResult::FoundType:
+          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
+          break;
+        case UnqualifiedTypeNameLookupResult::NotFound:
+          break;
+        }
+      }
+    }
+  }
+
+  return FoundTypeDecl;
+}
+
 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
                                                       const IdentifierInfo &II,
                                                       SourceLocation NameLoc) {
-  // Find the first parent class template context, if any.
-  // FIXME: Perform the lookup in all enclosing class templates.
+  // Lookup in the parent class template context, if any.
   const CXXRecordDecl *RD = nullptr;
-  for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) {
+  UnqualifiedTypeNameLookupResult FoundTypeDecl =
+      UnqualifiedTypeNameLookupResult::NotFound;
+  for (DeclContext *DC = S.CurContext;
+       DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
+       DC = DC->getParent()) {
+    // Look for type decls in dependent base classes that have known primary
+    // templates.
     RD = dyn_cast<CXXRecordDecl>(DC);
     if (RD && RD->getDescribedClassTemplate())
-      break;
+      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
   }
-  if (!RD)
-    return ParsedType();
-
-  // Look for type decls in dependent base classes that have known primary
-  // templates.
-  bool FoundTypeDecl = false;
-  for (const auto &Base : RD->bases()) {
-    auto *TST = Base.getType()->getAs<TemplateSpecializationType>();
-    if (!TST || !TST->isDependentType())
-      continue;
-    auto *TD = TST->getTemplateName().getAsTemplateDecl();
-    if (!TD)
-      continue;
-    auto *BasePrimaryTemplate =
-        dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
-    if (!BasePrimaryTemplate)
-      continue;
-    // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly
-    // by calling or integrating with the main LookupQualifiedName mechanism.
-    for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) {
-      if (FoundTypeDecl)
-        return ParsedType();
-      FoundTypeDecl = isa<TypeDecl>(ND);
-      if (!FoundTypeDecl)
-        return ParsedType();
-    }
-  }
-  if (!FoundTypeDecl)
+  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
     return ParsedType();
 
   // We found some types in dependent base classes.  Recover as if the user
@@ -2154,6 +2194,14 @@
     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
                                        AttrSpellingListIndex,
                                        IA->getSemanticSpelling());
+  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
+    NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
+                                      &S.Context.Idents.get(AA->getSpelling()),
+                                      AttrSpellingListIndex);
+  else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
+    NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
+  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
+    NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
   else if (isa<AlignedAttr>(Attr))
     // AlignedAttrs are handled separately, because we need to handle all
     // such attributes on a declaration at the same time.
@@ -2753,6 +2801,7 @@
             << New << New->getType();
         }
         Diag(OldLocation, PrevDiag) << Old << Old->getType();
+        return true;
 
       // Complain if this is an explicit declaration of a special
       // member that was initially declared implicitly.
@@ -3231,8 +3280,15 @@
   }
 
   // Merge the types.
-  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
+  VarDecl *MostRecent = Old->getMostRecentDecl();
+  if (MostRecent != Old) {
+    MergeVarDeclTypes(New, MostRecent,
+                      mergeTypeWithPrevious(*this, New, MostRecent, Previous));
+    if (New->isInvalidDecl())
+      return;
+  }
 
+  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
   if (New->isInvalidDecl())
     return;
 
@@ -3277,12 +3333,12 @@
 
   // Check if extern is followed by non-extern and vice-versa.
   if (New->hasExternalStorage() &&
-      !Old->hasLinkage() && Old->isLocalVarDecl()) {
+      !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
     Diag(OldLocation, PrevDiag);
     return New->setInvalidDecl();
   }
-  if (Old->hasLinkage() && New->isLocalVarDecl() &&
+  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
       !New->hasExternalStorage()) {
     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
     Diag(OldLocation, PrevDiag);
@@ -3456,7 +3512,7 @@
     return ActOnFriendTypeDecl(S, DS, TemplateParams);
   }
 
-  CXXScopeSpec &SS = DS.getTypeSpecScope();
+  const CXXScopeSpec &SS = DS.getTypeSpecScope();
   bool IsExplicitSpecialization =
     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
@@ -3483,7 +3539,8 @@
         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
       if (getLangOpts().CPlusPlus ||
           Record->getDeclContext()->isRecord())
-        return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
+        return BuildAnonymousStructOrUnion(S, DS, AS, Record,
+                                           Context.getPrintingPolicy());
 
       DeclaresAnything = false;
     }
@@ -3711,8 +3768,7 @@
         //   anonymous union is declared.
         unsigned OldChainingSize = Chaining.size();
         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
-          for (auto *PI : IF->chain())
-            Chaining.push_back(PI);
+          Chaining.append(IF->chain_begin(), IF->chain_end());
         else
           Chaining.push_back(VD);
 
@@ -5087,6 +5143,18 @@
     if (ND.isExternallyVisible()) {
       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
       ND.dropAttr<WeakRefAttr>();
+      ND.dropAttr<AliasAttr>();
+    }
+  }
+
+  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
+    if (VD->hasInit()) {
+      if (const auto *Attr = VD->getAttr<AliasAttr>()) {
+        assert(VD->isThisDeclarationADefinition() &&
+               !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
+        S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
+        VD->dropAttr<AliasAttr>();
+      }
     }
   }
 
@@ -5550,8 +5618,9 @@
         }
       }
     } else {
-      assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
-             "should have a 'template<>' for this decl");
+      assert(
+          (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
+          "should have a 'template<>' for this decl");
     }
 
     if (IsVariableTemplateSpecialization) {
@@ -5613,22 +5682,20 @@
     NewVD->setLocalExternDecl();
 
   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
-    if (NewVD->hasLocalStorage()) {
-      // C++11 [dcl.stc]p4:
-      //   When thread_local is applied to a variable of block scope the
-      //   storage-class-specifier static is implied if it does not appear
-      //   explicitly.
-      // Core issue: 'static' is not implied if the variable is declared
-      //   'extern'.
-      if (SCSpec == DeclSpec::SCS_unspecified &&
-          TSCS == DeclSpec::TSCS_thread_local &&
-          DC->isFunctionOrMethod())
-        NewVD->setTSCSpec(TSCS);
-      else
-        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
-             diag::err_thread_non_global)
-          << DeclSpec::getSpecifierName(TSCS);
-    } else if (!Context.getTargetInfo().isTLSSupported())
+    // C++11 [dcl.stc]p4:
+    //   When thread_local is applied to a variable of block scope the
+    //   storage-class-specifier static is implied if it does not appear
+    //   explicitly.
+    // Core issue: 'static' is not implied if the variable is declared
+    //   'extern'.
+    if (NewVD->hasLocalStorage() &&
+        (SCSpec != DeclSpec::SCS_unspecified ||
+         TSCS != DeclSpec::TSCS_thread_local ||
+         !DC->isFunctionOrMethod()))
+      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
+           diag::err_thread_non_global)
+        << DeclSpec::getSpecifierName(TSCS);
+    else if (!Context.getTargetInfo().isTLSSupported())
       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
            diag::err_thread_unsupported);
     else
@@ -6609,9 +6676,6 @@
     if (D.isInvalidType())
       NewFD->setInvalidDecl();
 
-    // Set the lexical context.
-    NewFD->setLexicalDeclContext(SemaRef.CurContext);
-
     return NewFD;
   }
 
@@ -6711,6 +6775,11 @@
     IsVirtualOkay = !Ret->isStatic();
     return Ret;
   } else {
+    bool isFriend =
+        SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
+    if (!isFriend && SemaRef.CurContext->isRecord())
+      return nullptr;
+
     // Determine whether the function was written with a
     // prototype. This true when:
     //   - we're in C++ (where every function has a prototype),
@@ -6883,8 +6952,10 @@
 
       // We have an error, now let's go back up through history and show where
       // the offending field came from
-      for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
-             E = HistoryStack.end(); I != E; ++I) {
+      for (ArrayRef<const FieldDecl *>::const_iterator
+               I = HistoryStack.begin() + 1,
+               E = HistoryStack.end();
+           I != E; ++I) {
         const FieldDecl *OuterField = *I;
         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
           << OuterField->getType();
@@ -6995,12 +7066,12 @@
 
         // Check that we can declare a template here.
         if (CheckTemplateDeclScope(S, TemplateParams))
-          return nullptr;
+          NewFD->setInvalidDecl();
 
         // A destructor cannot be a template.
         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
           Diag(NewFD->getLocation(), diag::err_destructor_template);
-          return nullptr;
+          NewFD->setInvalidDecl();
         }
         
         // If we're adding a template to a dependent context, we may need to 
@@ -7387,7 +7458,7 @@
       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
                                                   isExplicitSpecialization));
     else if (!Previous.empty())
-      // Make graceful recovery from an invalid redeclaration.
+      // Recover gracefully from an invalid redeclaration.
       D.setRedeclaration(true);
     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
@@ -7528,6 +7599,9 @@
       if (!NewFD->isInvalidDecl())
         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
                                                     isExplicitSpecialization));
+      else if (!Previous.empty())
+        // Recover gracefully from an invalid redeclaration.
+        D.setRedeclaration(true);
     }
 
     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
@@ -7879,7 +7953,7 @@
       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
     CXXMethodDecl *OldMD = nullptr;
     if (OldDecl)
-      OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
+      OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
     if (!OldMD || !OldMD->isStatic()) {
       const FunctionProtoType *FPT =
         MD->getType()->castAs<FunctionProtoType>();
@@ -8044,7 +8118,7 @@
     // the function returns a UDT (class, struct, or union type) that is not C
     // compatible, and if it does, warn the user.
     // But, issue any diagnostic on the first declaration only.
-    if (NewFD->isExternC() && Previous.empty()) {
+    if (Previous.empty() && NewFD->isExternC()) {
       QualType R = NewFD->getReturnType();
       if (R->isIncompleteType() && !R->isVoidType())
         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
@@ -8491,7 +8565,8 @@
       // Treat std::move as a use.
       if (E->getNumArgs() == 1) {
         if (FunctionDecl *FD = E->getDirectCallee()) {
-          if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
+          if (FD->isInStdNamespace() && FD->getIdentifier() &&
+              FD->getIdentifier()->isStr("move")) {
             HandleValue(E->getArg(0));
             return;
           }
@@ -8569,8 +8644,10 @@
                                 bool DirectInit, bool TypeMayContainAuto) {
   // If there is no declaration, there was an error parsing it.  Just ignore
   // the initializer.
-  if (!RealDecl || RealDecl->isInvalidDecl())
+  if (!RealDecl || RealDecl->isInvalidDecl()) {
+    CorrectDelayedTyposInExpr(Init);
     return;
+  }
 
   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
     // With declarators parsed the way they are, the parser cannot
@@ -8684,6 +8761,14 @@
     CheckVariableDeclarationType(VDecl);
     if (VDecl->isInvalidDecl())
       return;
+
+    // If all looks well, warn if this is a case that will change meaning when
+    // we implement N3922.
+    if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
+      Diag(Init->getLocStart(),
+           diag::warn_auto_var_direct_list_init)
+        << FixItHint::CreateInsertion(Init->getLocStart(), "=");
+    }
   }
 
   // dllimport cannot be used on variable definitions.
@@ -8801,6 +8886,22 @@
       Args = MultiExprArg(CXXDirectInit->getExprs(),
                           CXXDirectInit->getNumExprs());
 
+    // Try to correct any TypoExprs in the initialization arguments.
+    for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
+      ExprResult Res =
+          CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
+            InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
+            return Init.Failed() ? ExprError() : E;
+          });
+      if (Res.isInvalid()) {
+        VDecl->setInvalidDecl();
+      } else if (Res.get() != Args[Idx]) {
+        Args[Idx] = Res.get();
+      }
+    }
+    if (VDecl->isInvalidDecl())
+      return;
+
     InitializationSequence InitSeq(*this, Entity, Kind, Args);
     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
     if (Result.isInvalid()) {
@@ -9211,6 +9312,8 @@
         Var->setInvalidDecl();
         return;
       }
+    } else {
+      return;
     }
 
     // The variable can not have an abstract class type.
@@ -9308,8 +9411,6 @@
   case SC_OpenCLWorkGroupLocal:
     llvm_unreachable("Unexpected storage class");
   }
-  if (VD->isConstexpr())
-    Error = 5;
   if (Error != -1) {
     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
       << VD->getDeclName() << Error;
@@ -9583,18 +9684,6 @@
     }
   }
 
-  if (!VD->isInvalidDecl() &&
-      VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
-    if (const VarDecl *Def = VD->getDefinition()) {
-      if (Def->hasAttr<AliasAttr>()) {
-        Diag(VD->getLocation(), diag::err_tentative_after_alias)
-            << VD->getDeclName();
-        Diag(Def->getLocation(), diag::note_previous_definition);
-        VD->setInvalidDecl();
-      }
-    }
-  }
-
   const DeclContext *DC = VD->getDeclContext();
   // If there's a #pragma GCC visibility in scope, and this isn't a class
   // member, set the visibility of this variable.
@@ -10159,7 +10248,7 @@
       QualType CaptureType = VD->getType();
       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
       LSI->addCapture(VD, /*IsBlock*/false, ByRef, 
-          /*RefersToEnclosingLocal*/true, C.getLocation(),
+          /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
           /*EllipsisLoc*/C.isPackExpansion() 
                          ? C.getEllipsisLoc() : SourceLocation(),
           CaptureType, /*Expr*/ nullptr);
@@ -10457,9 +10546,11 @@
       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
                                              FD->getReturnType(), FD);
 
-      // If this is a constructor, we need a vtable.
+      // If this is a structor, we need a vtable.
       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
+      else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
+        MarkVTableUsed(FD->getLocation(), Destructor->getParent());
       
       // Try to apply the named return value optimization. We have to check
       // if we can do this here because lambdas keep return statements around
@@ -11579,9 +11670,8 @@
             } else {
               // If the type is currently being defined, complain
               // about a nested redefinition.
-              const TagType *Tag
-                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
-              if (Tag->isBeingDefined()) {
+              auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
+              if (TD->isBeingDefined()) {
                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
                 Diag(PrevTagDecl->getLocation(),
                      diag::note_previous_definition);
@@ -11771,7 +11861,7 @@
       // CheckMemberSpecialization, below.
       if (!isExplicitSpecialization &&
           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
-          diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
+          diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
         Invalid = true;
 
       New->setQualifierInfo(SS.getWithLocInContext(Context));
@@ -12311,7 +12401,8 @@
   if (!InvalidDecl && Mutable) {
     unsigned DiagID = 0;
     if (T->isReferenceType())
-      DiagID = diag::err_mutable_reference;
+      DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
+                                        : diag::err_mutable_reference;
     else if (T.isConstQualified())
       DiagID = diag::err_mutable_const;
 
@@ -12320,8 +12411,10 @@
       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
       Diag(ErrLoc, DiagID);
-      Mutable = false;
-      InvalidDecl = true;
+      if (DiagID != diag::ext_mutable_reference) {
+        Mutable = false;
+        InvalidDecl = true;
+      }
     }
   }
 
@@ -13485,6 +13578,49 @@
   }
 }
 
+bool
+Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
+                        bool AllowMask) const {
+  FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
+  assert(FEAttr && "looking for value in non-flag enum");
+
+  llvm::APInt FlagMask = ~FEAttr->getFlagBits();
+  unsigned Width = FlagMask.getBitWidth();
+
+  // We will try a zero-extended value for the regular check first.
+  llvm::APInt ExtVal = Val.zextOrSelf(Width);
+
+  // A value is in a flag enum if either its bits are a subset of the enum's
+  // flag bits (the first condition) or we are allowing masks and the same is
+  // true of its complement (the second condition). When masks are allowed, we
+  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
+  //
+  // While it's true that any value could be used as a mask, the assumption is
+  // that a mask will have all of the insignificant bits set. Anything else is
+  // likely a logic error.
+  if (!(FlagMask & ExtVal))
+    return true;
+
+  if (AllowMask) {
+    // Try a one-extended value instead. This can happen if the enum is wider
+    // than the constant used, in C with extensions to allow for wider enums.
+    // The mask will still have the correct behaviour, so we give the user the
+    // benefit of the doubt.
+    //
+    // FIXME: This heuristic can cause weird results if the enum was extended
+    // to a larger type and is signed, because then bit-masks of smaller types
+    // that get extended will fall out of range (e.g. ~0x1u). We currently don't
+    // detect that case and will get a false positive for it. In most cases,
+    // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
+    // be fine just to accept this as a warning.
+    ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
+    if (!(FlagMask & ~ExtVal))
+      return true;
+  }
+
+  return false;
+}
+
 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
                          SourceLocation RBraceLoc, Decl *EnumDeclX,
                          ArrayRef<Decl *> Elements,
@@ -13570,10 +13706,8 @@
       BestPromotionType = Context.getPromotedIntegerType(BestType);
     else
       BestPromotionType = BestType;
-    // We don't need to set BestWidth, because BestType is going to be the type
-    // of the enumerators, but we do anyway because otherwise some compilers
-    // warn that it might be used uninitialized.
-    BestWidth = CharWidth;
+
+    BestWidth = Context.getIntWidth(BestType);
   }
   else if (NumNegativeBits) {
     // If there is a negative value, figure out the smallest integer type (of
@@ -13638,10 +13772,15 @@
     }
   }
 
+  FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
+  if (FEAttr)
+    FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
+
   // Loop over all of the enumerator constants, changing their types to match
-  // the type of the enum if needed.
-  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
-    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
+  // the type of the enum if needed. If we have a flag type, we also prepare the
+  // FlagBits cache.
+  for (auto *D : Elements) {
+    auto *ECD = cast_or_null<EnumConstantDecl>(D);
     if (!ECD) continue;  // Already issued a diagnostic.
 
     // Standard C says the enumerators have int type, but we allow, as an
@@ -13671,7 +13810,7 @@
         // enum-specifier, each enumerator has the type of its
         // enumeration.
         ECD->setType(EnumType);
-      continue;
+      goto flagbits;
     } else {
       NewTy = BestType;
       NewWidth = BestWidth;
@@ -13698,8 +13837,32 @@
       ECD->setType(EnumType);
     else
       ECD->setType(NewTy);
+
+flagbits:
+    // Check to see if we have a constant with exactly one bit set. Note that x
+    // & (x - 1) will be nonzero if and only if x has more than one bit set.
+    if (FEAttr) {
+      llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
+      if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
+        FEAttr->getFlagBits() |= ExtVal;
+      }
+    }
   }
 
+  if (FEAttr) {
+    for (Decl *D : Elements) {
+      EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
+      if (!ECD) continue;  // Already issued a diagnostic.
+
+      llvm::APSInt InitVal = ECD->getInitVal();
+      if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
+        Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
+          << ECD << Enum;
+    }
+  }
+
+
+
   Enum->completeDefinition(BestType, BestPromotionType,
                            NumPositiveBits, NumNegativeBits);
 
@@ -13874,7 +14037,10 @@
 }
 
 AvailabilityResult Sema::getCurContextAvailability() const {
-  const Decl *D = cast<Decl>(getCurObjCLexicalContext());
+  const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
+  if (!D)
+    return AR_Available;
+
   // If we are within an Objective-C method, we should consult
   // both the availability of the method as well as the
   // enclosing class.  If the class is (say) deprecated,
diff --git a/lib/Sema/SemaDeclAttr.cpp b/lib/Sema/SemaDeclAttr.cpp
index 48daba3..5ca074b 100644
--- a/lib/Sema/SemaDeclAttr.cpp
+++ b/lib/Sema/SemaDeclAttr.cpp
@@ -351,13 +351,13 @@
 // Check to see if the type is a smart pointer of some kind.  We assume
 // it's a smart pointer if it defines both operator-> and operator*.
 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
-  DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
-    S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
+  DeclContextLookupResult Res1 = RT->getDecl()->lookup(
+      S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
   if (Res1.empty())
     return false;
 
-  DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
-    S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
+  DeclContextLookupResult Res2 = RT->getDecl()->lookup(
+      S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
   if (Res2.empty())
     return false;
 
@@ -741,11 +741,9 @@
   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
     return;
 
-  D->addAttr(::new (S.Context)
-             ExclusiveTrylockFunctionAttr(Attr.getRange(), S.Context,
-                                          Attr.getArgAsExpr(0),
-                                          Args.data(), Args.size(),
-                                          Attr.getAttributeSpellingListIndex()));
+  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
+      Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
+      Args.size(), Attr.getAttributeSpellingListIndex()));
 }
 
 static void handleLockReturnedAttr(Sema &S, Decl *D,
@@ -863,8 +861,14 @@
     
     StringRef StateString;
     SourceLocation Loc;
-    if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
-      return;
+    if (Attr.isArgIdent(ArgIndex)) {
+      IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
+      StateString = Ident->Ident->getName();
+      Loc = Ident->Loc;
+    } else {
+      if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
+        return;
+    }
 
     if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
                                                      CallableState)) {
@@ -1488,6 +1492,20 @@
     return;
   }
 
+  // Aliases should be on declarations, not definitions.
+  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
+    if (FD->isThisDeclarationADefinition()) {
+      S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
+      return;
+    }
+  } else {
+    const auto *VD = cast<VarDecl>(D);
+    if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
+      S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
+      return;
+    }
+  }
+
   // FIXME: check if target symbol exists in current file
 
   D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
@@ -1540,18 +1558,16 @@
   }
 }
 
-static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
-  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
-    QualType RetTy = FD->getReturnType();
-    if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
-      D->addAttr(::new (S.Context)
-                 MallocAttr(Attr.getRange(), S.Context,
-                            Attr.getAttributeSpellingListIndex()));
-      return;
-    }
+static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
+  QualType ResultType = getFunctionOrMethodResultType(D);
+  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
+    D->addAttr(::new (S.Context) RestrictAttr(
+        Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
+    return;
   }
 
-  S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
+  S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
+      << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
 }
 
 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
@@ -2487,6 +2503,8 @@
     .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
     .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
     .Case("kprintf", SupportedFormat) // OpenBSD.
+    .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
+    .Case("os_trace", SupportedFormat)
 
     .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
     .Default(InvalidFormat);
@@ -2945,12 +2963,15 @@
 void Sema::CheckAlignasUnderalignment(Decl *D) {
   assert(D->hasAttrs() && "no attributes on decl");
 
-  QualType Ty;
-  if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
-    Ty = VD->getType();
-  else
-    Ty = Context.getTagDeclType(cast<TagDecl>(D));
-  if (Ty->isDependentType() || Ty->isIncompleteType())
+  QualType UnderlyingTy, DiagTy;
+  if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
+    UnderlyingTy = DiagTy = VD->getType();
+  } else {
+    UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
+    if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
+      UnderlyingTy = ED->getIntegerType();
+  }
+  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
     return;
 
   // C++11 [dcl.align]p5, C11 6.7.5/4:
@@ -2969,10 +2990,10 @@
 
   if (AlignasAttr && Align) {
     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
-    CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
+    CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
     if (NaturalAlign > RequestedAlign)
       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
-        << Ty << (unsigned)NaturalAlign.getQuantity();
+        << DiagTy << (unsigned)NaturalAlign.getQuantity();
   }
 }
 
@@ -3146,24 +3167,75 @@
                          Attr.getAttributeSpellingListIndex()));
 }
 
+AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
+                                              IdentifierInfo *Ident,
+                                              unsigned AttrSpellingListIndex) {
+  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
+    Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
+    Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
+    return nullptr;
+  }
+
+  if (D->hasAttr<AlwaysInlineAttr>())
+    return nullptr;
+
+  return ::new (Context) AlwaysInlineAttr(Range, Context,
+                                          AttrSpellingListIndex);
+}
+
+MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
+                                    unsigned AttrSpellingListIndex) {
+  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
+    Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
+    Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
+    return nullptr;
+  }
+
+  if (D->hasAttr<MinSizeAttr>())
+    return nullptr;
+
+  return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
+}
+
+OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
+                                              unsigned AttrSpellingListIndex) {
+  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
+    Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
+    Diag(Range.getBegin(), diag::note_conflicting_attribute);
+    D->dropAttr<AlwaysInlineAttr>();
+  }
+  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
+    Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
+    Diag(Range.getBegin(), diag::note_conflicting_attribute);
+    D->dropAttr<MinSizeAttr>();
+  }
+
+  if (D->hasAttr<OptimizeNoneAttr>())
+    return nullptr;
+
+  return ::new (Context) OptimizeNoneAttr(Range, Context,
+                                          AttrSpellingListIndex);
+}
+
 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
                                    const AttributeList &Attr) {
-  if (checkAttrMutualExclusion<OptimizeNoneAttr>(S, D, Attr))
-    return;
+  if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
+          D, Attr.getRange(), Attr.getName(),
+          Attr.getAttributeSpellingListIndex()))
+    D->addAttr(Inline);
+}
 
-  D->addAttr(::new (S.Context)
-             AlwaysInlineAttr(Attr.getRange(), S.Context,
-                              Attr.getAttributeSpellingListIndex()));
+static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
+  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
+          D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
+    D->addAttr(MinSize);
 }
 
 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
                                    const AttributeList &Attr) {
-  if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr))
-    return;
-
-  D->addAttr(::new (S.Context)
-             OptimizeNoneAttr(Attr.getRange(), S.Context,
-                              Attr.getAttributeSpellingListIndex()));
+  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
+          D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
+    D->addAttr(Optnone);
 }
 
 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
@@ -3269,11 +3341,6 @@
                        Attr.getAttributeSpellingListIndex()));
     return;
   }
-  case AttributeList::AT_PnaclCall:
-    D->addAttr(::new (S.Context)
-               PnaclCallAttr(Attr.getRange(), S.Context,
-                             Attr.getAttributeSpellingListIndex()));
-    return;
   case AttributeList::AT_IntelOclBicc:
     D->addAttr(::new (S.Context)
                IntelOclBiccAttr(Attr.getRange(), S.Context,
@@ -3330,16 +3397,18 @@
     Diag(attr.getLoc(), diag::err_invalid_pcs);
     return true;
   }
-  case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
   case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
   default: llvm_unreachable("unexpected attribute kind");
   }
 
   const TargetInfo &TI = Context.getTargetInfo();
   TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
-  if (A == TargetInfo::CCCR_Warning) {
-    Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
+  if (A != TargetInfo::CCCR_OK) {
+    if (A == TargetInfo::CCCR_Warning)
+      Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
 
+    // This convention is not valid for the target. Use the default function or
+    // method calling convention.
     TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
     if (FD)
       MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member : 
@@ -3578,29 +3647,24 @@
     default:
       llvm_unreachable("invalid ownership attribute");
     case AttributeList::AT_NSReturnsAutoreleased:
-      D->addAttr(::new (S.Context)
-                 NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context,
-                                           Attr.getAttributeSpellingListIndex()));
+      D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
+          Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
       return;
     case AttributeList::AT_CFReturnsNotRetained:
-      D->addAttr(::new (S.Context)
-                 CFReturnsNotRetainedAttr(Attr.getRange(), S.Context,
-                                          Attr.getAttributeSpellingListIndex()));
+      D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
+          Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
       return;
     case AttributeList::AT_NSReturnsNotRetained:
-      D->addAttr(::new (S.Context)
-                 NSReturnsNotRetainedAttr(Attr.getRange(), S.Context,
-                                          Attr.getAttributeSpellingListIndex()));
+      D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
+          Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
       return;
     case AttributeList::AT_CFReturnsRetained:
-      D->addAttr(::new (S.Context)
-                 CFReturnsRetainedAttr(Attr.getRange(), S.Context,
-                                       Attr.getAttributeSpellingListIndex()));
+      D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
+          Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
       return;
     case AttributeList::AT_NSReturnsRetained:
-      D->addAttr(::new (S.Context)
-                 NSReturnsRetainedAttr(Attr.getRange(), S.Context,
-                                       Attr.getAttributeSpellingListIndex()));
+      D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
+          Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
       return;
   };
 }
@@ -3629,9 +3693,8 @@
     return;
   }
 
-  D->addAttr(::new (S.Context)
-                  ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context,
-                                              attr.getAttributeSpellingListIndex()));
+  D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
+      attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
 }
 
 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
@@ -3684,6 +3747,22 @@
     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
     return;
   }
+
+  // Typedefs only allow objc_bridge(id) and have some additional checking.
+  if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
+    if (!Parm->Ident->isStr("id")) {
+      S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
+        << Attr.getName();
+      return;
+    }
+
+    // Only allow 'cv void *'.
+    QualType T = TD->getUnderlyingType();
+    if (!T->isVoidPointerType()) {
+      S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
+      return;
+    }
+  }
   
   D->addAttr(::new (S.Context)
              ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
@@ -3725,10 +3804,15 @@
 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
                                             const AttributeList &Attr) {
   ObjCInterfaceDecl *IFace;
-  if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
+  if (ObjCCategoryDecl *CatDecl =
+          dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
     IFace = CatDecl->getClassInterface();
   else
     IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
+
+  if (!IFace)
+    return;
+
   IFace->setHasDesignatedInitializers();
   D->addAttr(::new (S.Context)
                   ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
@@ -3950,6 +4034,32 @@
     handleARMInterruptAttr(S, D, Attr);
 }
 
+static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
+                                    const AttributeList &Attr) {
+  uint32_t NumRegs;
+  Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
+  if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
+    return;
+
+  D->addAttr(::new (S.Context)
+             AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
+                               NumRegs,
+                               Attr.getAttributeSpellingListIndex()));
+}
+
+static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
+                                    const AttributeList &Attr) {
+  uint32_t NumRegs;
+  Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
+  if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
+    return;
+
+  D->addAttr(::new (S.Context)
+             AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
+                               NumRegs,
+                               Attr.getAttributeSpellingListIndex()));
+}
+
 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
                                               const AttributeList& Attr) {
   // If we try to apply it to a function pointer, don't warn, but don't
@@ -4159,6 +4269,12 @@
       return;
     }
   }
+
+  if (!S.getLangOpts().CPlusPlus14)
+    if (Attr.isCXX11Attribute() &&
+        !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
+      S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
+
   handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
 }
 
@@ -4257,6 +4373,12 @@
   case AttributeList::AT_NoMips16:
     handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
     break;
+  case AttributeList::AT_AMDGPUNumVGPR:
+    handleAMDGPUNumVGPRAttr(S, D, Attr);
+    break;
+  case AttributeList::AT_AMDGPUNumSGPR:
+    handleAMDGPUNumSGPRAttr(S, D, Attr);
+    break;
   case AttributeList::AT_IBAction:
     handleSimpleAttribute<IBActionAttr>(S, D, Attr);
     break;
@@ -4318,11 +4440,14 @@
     handleExtVectorTypeAttr(S, scope, D, Attr);
     break;
   case AttributeList::AT_MinSize:
-    handleSimpleAttribute<MinSizeAttr>(S, D, Attr);
+    handleMinSizeAttr(S, D, Attr);
     break;
   case AttributeList::AT_OptimizeNone:
     handleOptimizeNoneAttr(S, D, Attr);
     break;
+  case AttributeList::AT_FlagEnum:
+    handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
+    break;
   case AttributeList::AT_Flatten:
     handleSimpleAttribute<FlattenAttr>(S, D, Attr);
     break;
@@ -4350,8 +4475,8 @@
   case AttributeList::AT_Kernel:
     handleKernelAttr(S, D, Attr);
     break;
-  case AttributeList::AT_Malloc:
-    handleMallocAttr(S, D, Attr);
+  case AttributeList::AT_Restrict:
+    handleRestrictAttr(S, D, Attr);
     break;
   case AttributeList::AT_MayAlias:
     handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
@@ -4575,7 +4700,6 @@
   case AttributeList::AT_MSABI:
   case AttributeList::AT_SysVABI:
   case AttributeList::AT_Pcs:
-  case AttributeList::AT_PnaclCall:
   case AttributeList::AT_IntelOclBicc:
     handleCallConvAttr(S, D, Attr);
     break;
@@ -4587,8 +4711,11 @@
     break;
 
   // Microsoft attributes:
-  case AttributeList::AT_MsStruct:
-    handleSimpleAttribute<MsStructAttr>(S, D, Attr);
+  case AttributeList::AT_MSNoVTable:
+    handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
+    break;
+  case AttributeList::AT_MSStruct:
+    handleSimpleAttribute<MSStructAttr>(S, D, Attr);
     break;
   case AttributeList::AT_Uuid:
     handleUuidAttr(S, D, Attr);
@@ -4733,19 +4860,31 @@
     return;
   }
 
+  // FIXME: We should be able to handle this in TableGen as well. It would be
+  // good to have a way to specify "these attributes must appear as a group",
+  // for these. Additionally, it would be good to have a way to specify "these
+  // attribute must never appear as a group" for attributes like cold and hot.
   if (!D->hasAttr<OpenCLKernelAttr>()) {
     // These attributes cannot be applied to a non-kernel function.
     if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
+      // FIXME: This emits a different error message than
+      // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
       D->setInvalidDecl();
-    }
-    if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
+    } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
       D->setInvalidDecl();
-    }
-    if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
+    } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
       Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
       D->setInvalidDecl();
+    } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
+      Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
+        << A << ExpectedKernelFunction;
+      D->setInvalidDecl();
+    } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
+      Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
+        << A << ExpectedKernelFunction;
+      D->setInvalidDecl();
     }
   }
 }
@@ -4756,7 +4895,7 @@
                                           const AttributeList *AttrList) {
   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
     if (l->getKind() == AttributeList::AT_Annotate) {
-      handleAnnotateAttr(*this, ASDecl, *l);
+      ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
     } else {
       Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
       return true;
@@ -4961,7 +5100,8 @@
       return true;
     // A category implicitly has the availability of the interface.
     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
-      return CatD->getClassInterface()->isDeprecated();
+      if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
+        return Interface->isDeprecated();
   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
   return false;
 }
@@ -4972,7 +5112,8 @@
       return true;
     // A category implicitly has the availability of the interface.
     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
-      return CatD->getClassInterface()->isUnavailable();
+      if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
+        return Interface->isUnavailable();
   } while ((D = cast_or_null<Decl>(D->getDeclContext())));
   return false;
 }
@@ -5112,11 +5253,9 @@
                                    bool ObjCPropertyAccess) {
   // Delay if we're currently parsing a declaration.
   if (DelayedDiagnostics.shouldDelayDiagnostics()) {
-    DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(AD, Loc, D,
-                                                               UnknownObjCClass,
-                                                               ObjCProperty,
-                                                               Message,
-                                                               ObjCPropertyAccess));
+    DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
+        AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
+        ObjCPropertyAccess));
     return;
   }
 
diff --git a/lib/Sema/SemaDeclCXX.cpp b/lib/Sema/SemaDeclCXX.cpp
index f23d1a0..c41dc33 100644
--- a/lib/Sema/SemaDeclCXX.cpp
+++ b/lib/Sema/SemaDeclCXX.cpp
@@ -388,9 +388,14 @@
         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
         if (Param->hasUnparsedDefaultArg()) {
           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
+          SourceRange SR;
+          if (Toks->size() > 1)
+            SR = SourceRange((*Toks)[1].getLocation(),
+                             Toks->back().getLocation());
+          else
+            SR = UnparsedDefaultArgLocs[Param];
           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
-            << SourceRange((*Toks)[1].getLocation(),
-                           Toks->back().getLocation());
+            << SR;
           delete Toks;
           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
         } else if (Param->getDefaultArg()) {
@@ -504,14 +509,11 @@
       
       // Look for the function declaration where the default argument was
       // actually written, which may be a declaration prior to Old.
-      for (FunctionDecl *Older = Old->getPreviousDecl();
-           Older; Older = Older->getPreviousDecl()) {
-        if (!Older->getParamDecl(p)->hasDefaultArg())
-          break;
-        
+      for (auto Older = Old; OldParam->hasInheritedDefaultArg();) {
+        Older = Older->getPreviousDecl();
         OldParam = Older->getParamDecl(p);
-      }        
-      
+      }
+
       Diag(OldParam->getLocation(), diag::note_previous_definition)
         << OldParam->getDefaultArgRange();
     } else if (OldParamHasDfl) {
@@ -519,7 +521,9 @@
       // It's important to use getInit() here;  getDefaultArg()
       // strips off any top-level ExprWithCleanups.
       NewParam->setHasInheritedDefaultArg();
-      if (OldParam->hasUninstantiatedDefaultArg())
+      if (OldParam->hasUnparsedDefaultArg())
+        NewParam->setUnparsedDefaultArg();
+      else if (OldParam->hasUninstantiatedDefaultArg())
         NewParam->setUninstantiatedDefaultArg(
                                       OldParam->getUninstantiatedDefaultArg());
       else
@@ -1540,6 +1544,31 @@
   return true;
 }
 
+/// Use small set to collect indirect bases.  As this is only used
+/// locally, there's no need to abstract the small size parameter.
+typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
+
+/// \brief Recursively add the bases of Type.  Don't add Type itself.
+static void
+NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
+                  const QualType &Type)
+{
+  // Even though the incoming type is a base, it might not be
+  // a class -- it could be a template parm, for instance.
+  if (auto Rec = Type->getAs<RecordType>()) {
+    auto Decl = Rec->getAsCXXRecordDecl();
+
+    // Iterate over its bases.
+    for (const auto &BaseSpec : Decl->bases()) {
+      QualType Base = Context.getCanonicalType(BaseSpec.getType())
+        .getUnqualifiedType();
+      if (Set.insert(Base).second)
+        // If we've not already seen it, recurse.
+        NoteIndirectBases(Context, Set, Base);
+    }
+  }
+}
+
 /// \brief Performs the actual work of attaching the given base class
 /// specifiers to a C++ class.
 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
@@ -1553,6 +1582,10 @@
   // class.
   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
 
+  // Used to track indirect bases so we can see if a direct base is
+  // ambiguous.
+  IndirectBaseSet IndirectBaseTypes;
+
   // Copy non-redundant base specifiers into permanent storage.
   unsigned NumGoodBases = 0;
   bool Invalid = false;
@@ -1580,6 +1613,11 @@
       // Okay, add this new base class.
       KnownBase = Bases[idx];
       Bases[NumGoodBases++] = Bases[idx];
+
+      // Note this base's direct & indirect bases, if there could be ambiguity.
+      if (NumBases > 1)
+        NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
+      
       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
         if (Class->isInterface() &&
@@ -1600,11 +1638,33 @@
 
   // Attach the remaining base class specifiers to the derived class.
   Class->setBases(Bases, NumGoodBases);
+  
+  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
+    // Check whether this direct base is inaccessible due to ambiguity.
+    QualType BaseType = Bases[idx]->getType();
+    CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
+      .getUnqualifiedType();
 
-  // Delete the remaining (good) base class specifiers, since their
-  // data has been copied into the CXXRecordDecl.
-  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
+    if (IndirectBaseTypes.count(CanonicalBase)) {
+      CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
+                         /*DetectVirtual=*/true);
+      bool found
+        = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
+      assert(found);
+      (void)found;
+
+      if (Paths.isAmbiguous(CanonicalBase))
+        Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
+          << BaseType << getAmbiguousPathsDisplayString(Paths)
+          << Bases[idx]->getSourceRange();
+      else
+        assert(Bases[idx]->isVirtual());
+    }
+
+    // Delete the base class specifier, since its data has been copied
+    // into the CXXRecordDecl.
     Context.Deallocate(Bases[idx]);
+  }
 
   return Invalid;
 }
@@ -1684,18 +1744,6 @@
     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
 }
 
-/// \brief Determine whether the given base path includes a virtual
-/// base class.
-bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
-  for (CXXCastPath::const_iterator B = BasePath.begin(), 
-                                BEnd = BasePath.end();
-       B != BEnd; ++B)
-    if ((*B)->isVirtual())
-      return true;
-
-  return false;
-}
-
 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
 /// conversion (where Derived and Base are class types) is
 /// well-formed, meaning that the conversion is unambiguous (and
@@ -2154,7 +2202,8 @@
       assert(Member && "HandleField never returns null");
     }
   } else {
-    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
+    assert(InitStyle == ICIS_NoInit ||
+           D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
 
     Member = HandleDeclarator(S, D, TemplateParameterLists);
     if (!Member)
@@ -2164,7 +2213,7 @@
     if (BitWidth) {
       if (Member->isInvalidDecl()) {
         // don't emit another diagnostic.
-      } else if (isa<VarDecl>(Member)) {
+      } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
         // C++ 9.6p3: A bit-field shall not be a static member.
         // "static member 'A' cannot be a bit-field"
         Diag(Loc, diag::err_static_not_bitfield)
@@ -2237,6 +2286,9 @@
     // List of Decls to generate a warning on.  Also remove Decls that become
     // initialized.
     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
+    // List of base classes of the record.  Classes are removed after their
+    // initializers.
+    llvm::SmallPtrSetImpl<QualType> &BaseClasses;
     // Vector of decls to be removed from the Decl set prior to visiting the
     // nodes.  These Decls may have been initialized in the prior initializer.
     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
@@ -2252,9 +2304,10 @@
   public:
     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
     UninitializedFieldVisitor(Sema &S,
-                              llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
-      : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr),
-        InitList(false), InitListFieldDecl(nullptr) {}
+                              llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
+                              llvm::SmallPtrSetImpl<QualType> &BaseClasses)
+      : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
+        Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
 
     // Returns true if the use of ME is not an uninitialized use.
     bool IsInitListMemberExprInitialized(MemberExpr *ME,
@@ -2309,7 +2362,8 @@
       bool AllPODFields = FieldME->getType().isPODType(S.Context);
 
       Expr *Base = ME;
-      while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) {
+      while (MemberExpr *SubME =
+                 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
 
         if (isa<VarDecl>(SubME->getMemberDecl()))
           return;
@@ -2321,10 +2375,10 @@
         if (!FieldME->getType().isPODType(S.Context))
           AllPODFields = false;
 
-        Base = SubME->getBase()->IgnoreParenImpCasts();
+        Base = SubME->getBase();
       }
 
-      if (!isa<CXXThisExpr>(Base))
+      if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
         return;
 
       if (AddressOf && AllPODFields)
@@ -2332,6 +2386,21 @@
 
       ValueDecl* FoundVD = FieldME->getMemberDecl();
 
+      if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
+        while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
+          BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
+        }
+
+        if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
+          QualType T = BaseCast->getType();
+          if (T->isPointerType() &&
+              BaseClasses.count(T->getPointeeType())) {
+            S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
+                << T->getPointeeType() << FoundVD;
+          }
+        }
+      }
+
       if (!Decls.count(FoundVD))
         return;
 
@@ -2420,7 +2489,7 @@
     }
 
     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
-                          FieldDecl *Field) {
+                          FieldDecl *Field, const Type *BaseClass) {
       // Remove Decls that may have been initialized in the previous
       // initializer.
       for (ValueDecl* VD : DeclsToRemove)
@@ -2442,6 +2511,8 @@
 
       if (Field)
         Decls.erase(Field);
+      if (BaseClass)
+        BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
     }
 
     void VisitMemberExpr(MemberExpr *ME) {
@@ -2489,7 +2560,8 @@
       // Treat std::move as a use.
       if (E->getNumArgs() == 1) {
         if (FunctionDecl *FD = E->getDirectCallee()) {
-          if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
+          if (FD->isInStdNamespace() && FD->getIdentifier() &&
+              FD->getIdentifier()->isStr("move")) {
             HandleValue(E->getArg(0), false /*AddressOf*/);
             return;
           }
@@ -2578,14 +2650,19 @@
       }
     }
 
-    if (UninitializedFields.empty())
+    llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
+    for (auto I : RD->bases())
+      UninitializedBaseClasses.insert(I.getType().getCanonicalType());
+
+    if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
       return;
 
     UninitializedFieldVisitor UninitializedChecker(SemaRef,
-                                                   UninitializedFields);
+                                                   UninitializedFields,
+                                                   UninitializedBaseClasses);
 
     for (const auto *FieldInit : Constructor->inits()) {
-      if (UninitializedFields.empty())
+      if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
         break;
 
       Expr *InitExpr = FieldInit->getInit();
@@ -2599,10 +2676,12 @@
           continue;
         // In class initializers will point to the constructor.
         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
-                                              FieldInit->getAnyMember());
+                                              FieldInit->getAnyMember(),
+                                              FieldInit->getBaseClass());
       } else {
         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
-                                              FieldInit->getAnyMember());
+                                              FieldInit->getAnyMember(),
+                                              FieldInit->getBaseClass());
       }
     }
   }
@@ -2626,13 +2705,14 @@
   // Pop the notional constructor scope we created earlier.
   PopFunctionScopeInfo(nullptr, D);
 
-  FieldDecl *FD = cast<FieldDecl>(D);
-  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
+  FieldDecl *FD = dyn_cast<FieldDecl>(D);
+  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
          "must set init style when field is created");
 
   if (!InitExpr) {
-    FD->setInvalidDecl();
-    FD->removeInClassInitializer();
+    D->setInvalidDecl();
+    if (FD)
+      FD->removeInClassInitializer();
     return;
   }
 
@@ -2783,6 +2863,11 @@
                           SourceLocation IdLoc,
                           Expr *Init,
                           SourceLocation EllipsisLoc) {
+  ExprResult Res = CorrectDelayedTyposInExpr(Init);
+  if (!Res.isUsable())
+    return true;
+  Init = Res.get();
+
   if (!ConstructorD)
     return true;
 
@@ -4668,15 +4753,20 @@
   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
   const bool ClassImported = !ClassExported;
 
+  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
+
+  // Don't dllexport explicit class template instantiation declarations.
+  if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
+    Class->dropAttr<DLLExportAttr>();
+    return;
+  }
+
   // Force declaration of implicit members so they can inherit the attribute.
   S.ForceDeclarationOfImplicitMembers(Class);
 
   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
   // seem to be true in practice?
 
-  TemplateSpecializationKind TSK =
-    Class->getTemplateSpecializationKind();
-
   for (Decl *Member : Class->decls()) {
     VarDecl *VD = dyn_cast<VarDecl>(Member);
     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
@@ -4696,9 +4786,9 @@
         continue;
       }
 
-      if (MD->isInlined() && ClassImported &&
+      if (MD->isInlined() &&
           !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
-        // MinGW does not import inline functions.
+        // MinGW does not import or export inline methods.
         continue;
       }
     }
@@ -4712,7 +4802,7 @@
 
     if (MD && ClassExported) {
       if (MD->isUserProvided()) {
-        // Instantiate non-default methods..
+        // Instantiate non-default class member functions ...
 
         // .. except for certain kinds of template specializations.
         if (TSK == TSK_ExplicitInstantiationDeclaration)
@@ -4721,16 +4811,27 @@
           continue;
 
         S.MarkFunctionReferenced(Class->getLocation(), MD);
+
+        // The function will be passed to the consumer when its definition is
+        // encountered.
       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
                  MD->isCopyAssignmentOperator() ||
                  MD->isMoveAssignmentOperator()) {
-        // Instantiate non-trivial or explicitly defaulted methods, and the
-        // copy assignment / move assignment operators.
+        // Synthesize and instantiate non-trivial implicit methods, explicitly
+        // defaulted methods, and the copy and move assignment operators. The
+        // latter are exported even if they are trivial, because the address of
+        // an operator can be taken and should compare equal accross libraries.
+        DiagnosticErrorTrap Trap(S.Diags);
         S.MarkFunctionReferenced(Class->getLocation(), MD);
-        // Resolve its exception specification; CodeGen needs it.
-        auto *FPT = MD->getType()->getAs<FunctionProtoType>();
-        S.ResolveExceptionSpec(Class->getLocation(), FPT);
-        S.ActOnFinishInlineMethodDef(MD);
+        if (Trap.hasErrorOccurred()) {
+          S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
+              << Class->getName() << !S.getLangOpts().CPlusPlus11;
+          break;
+        }
+
+        // There is no later point when we will see the definition of this
+        // function, so pass it to the consumer now.
+        S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
       }
     }
   }
@@ -4853,42 +4954,6 @@
     for (auto *M : Record->methods())
       DiagnoseAbsenceOfOverrideControl(M);
   }
-  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
-  // function that is not a constructor declares that member function to be
-  // const. [...] The class of which that function is a member shall be
-  // a literal type.
-  //
-  // If the class has virtual bases, any constexpr members will already have
-  // been diagnosed by the checks performed on the member declaration, so
-  // suppress this (less useful) diagnostic.
-  //
-  // We delay this until we know whether an explicitly-defaulted (or deleted)
-  // destructor for the class is trivial.
-  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
-      !Record->isLiteral() && !Record->getNumVBases()) {
-    for (const auto *M : Record->methods()) {
-      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
-        switch (Record->getTemplateSpecializationKind()) {
-        case TSK_ImplicitInstantiation:
-        case TSK_ExplicitInstantiationDeclaration:
-        case TSK_ExplicitInstantiationDefinition:
-          // If a template instantiates to a non-literal type, but its members
-          // instantiate to constexpr functions, the template is technically
-          // ill-formed, but we allow it for sanity.
-          continue;
-
-        case TSK_Undeclared:
-        case TSK_ExplicitSpecialization:
-          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
-                             diag::err_constexpr_method_non_literal);
-          break;
-        }
-
-        // Only produce one error per class.
-        break;
-      }
-    }
-  }
 
   // ms_struct is a request to use the same ABI rules as MSVC.  Check
   // whether this class uses any C++ features that are implemented
@@ -5311,27 +5376,21 @@
 }
 
 void Sema::CheckDelayedMemberExceptionSpecs() {
-  SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
-              2> Checks;
-  SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
+  decltype(DelayedExceptionSpecChecks) Checks;
+  decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
 
-  std::swap(Checks, DelayedDestructorExceptionSpecChecks);
+  std::swap(Checks, DelayedExceptionSpecChecks);
   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
 
   // Perform any deferred checking of exception specifications for virtual
   // destructors.
-  for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
-    const CXXDestructorDecl *Dtor = Checks[i].first;
-    assert(!Dtor->getParent()->isDependentType() &&
-           "Should not ever add destructors of templates into the list.");
-    CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
-  }
+  for (auto &Check : Checks)
+    CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
 
   // Check that any explicitly-defaulted methods have exception specifications
   // compatible with their implicit exception specifications.
-  for (unsigned I = 0, N = Specs.size(); I != N; ++I)
-    CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
-                                                Specs[I].second);
+  for (auto &Spec : Specs)
+    CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
 }
 
 namespace {
@@ -6797,6 +6856,22 @@
   return Context.getFunctionType(Context.VoidTy, None, EPI);
 }
 
+static void extendLeft(SourceRange &R, const SourceRange &Before) {
+  if (Before.isInvalid())
+    return;
+  R.setBegin(Before.getBegin());
+  if (R.getEnd().isInvalid())
+    R.setEnd(Before.getEnd());
+}
+
+static void extendRight(SourceRange &R, const SourceRange &After) {
+  if (After.isInvalid())
+    return;
+  if (R.getBegin().isInvalid())
+    R.setBegin(After.getBegin());
+  R.setEnd(After.getEnd());
+}
+
 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
 /// well-formednes of the conversion function declarator @p D with
 /// type @p R. If there are any errors in the declarator, this routine
@@ -6818,7 +6893,9 @@
     SC = SC_None;
   }
 
-  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
+  TypeSourceInfo *ConvTSI = nullptr;
+  QualType ConvType =
+      GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
 
   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
     // Conversion functions don't have return types, but the parser will
@@ -6852,9 +6929,75 @@
   // Diagnose "&operator bool()" and other such nonsense.  This
   // is actually a gcc extension which we don't support.
   if (Proto->getReturnType() != ConvType) {
-    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
-        << Proto->getReturnType();
-    D.setInvalidType();
+    bool NeedsTypedef = false;
+    SourceRange Before, After;
+
+    // Walk the chunks and extract information on them for our diagnostic.
+    bool PastFunctionChunk = false;
+    for (auto &Chunk : D.type_objects()) {
+      switch (Chunk.Kind) {
+      case DeclaratorChunk::Function:
+        if (!PastFunctionChunk) {
+          if (Chunk.Fun.HasTrailingReturnType) {
+            TypeSourceInfo *TRT = nullptr;
+            GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
+            if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
+          }
+          PastFunctionChunk = true;
+          break;
+        }
+        // Fall through.
+      case DeclaratorChunk::Array:
+        NeedsTypedef = true;
+        extendRight(After, Chunk.getSourceRange());
+        break;
+
+      case DeclaratorChunk::Pointer:
+      case DeclaratorChunk::BlockPointer:
+      case DeclaratorChunk::Reference:
+      case DeclaratorChunk::MemberPointer:
+        extendLeft(Before, Chunk.getSourceRange());
+        break;
+
+      case DeclaratorChunk::Paren:
+        extendLeft(Before, Chunk.Loc);
+        extendRight(After, Chunk.EndLoc);
+        break;
+      }
+    }
+
+    SourceLocation Loc = Before.isValid() ? Before.getBegin() :
+                         After.isValid()  ? After.getBegin() :
+                                            D.getIdentifierLoc();
+    auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
+    DB << Before << After;
+
+    if (!NeedsTypedef) {
+      DB << /*don't need a typedef*/0;
+
+      // If we can provide a correct fix-it hint, do so.
+      if (After.isInvalid() && ConvTSI) {
+        SourceLocation InsertLoc =
+            PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
+        DB << FixItHint::CreateInsertion(InsertLoc, " ")
+           << FixItHint::CreateInsertionFromRange(
+                  InsertLoc, CharSourceRange::getTokenRange(Before))
+           << FixItHint::CreateRemoval(Before);
+      }
+    } else if (!Proto->getReturnType()->isDependentType()) {
+      DB << /*typedef*/1 << Proto->getReturnType();
+    } else if (getLangOpts().CPlusPlus11) {
+      DB << /*alias template*/2 << Proto->getReturnType();
+    } else {
+      DB << /*might not be fixable*/3;
+    }
+
+    // Recover by incorporating the other type chunks into the result type.
+    // Note, this does *not* change the name of the function. This is compatible
+    // with the GCC extension:
+    //   struct S { &operator int(); } s;
+    //   int &r = s.operator int(); // ok in GCC
+    //   S::operator int&() {} // error in GCC, function name is 'operator int'.
     ConvType = Proto->getReturnType();
   }
 
@@ -7230,7 +7373,7 @@
     StdInitializerList = Template;
   }
 
-  if (Template != StdInitializerList)
+  if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
     return false;
 
   // This is an instance of std::initializer_list. Find the argument type.
@@ -7406,8 +7549,8 @@
     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
         && "expected namespace decl");
 
-    // The use of a nested name specifier may trigger deprecation warnings.

-    DiagnoseUseOfDecl(Named, IdentLoc);

+    // The use of a nested name specifier may trigger deprecation warnings.
+    DiagnoseUseOfDecl(Named, IdentLoc);
 
     // C++ [namespace.udir]p1:
     //   A using-directive specifies that the names in the nominated
@@ -8160,7 +8303,7 @@
     // If we weren't able to compute a valid scope, it must be a
     // dependent class scope.
     if (!NamedContext || NamedContext->isRecord()) {
-      auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
+      auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
         RD = nullptr;
 
@@ -8522,7 +8665,7 @@
     }
   }
 
-  // The use of a nested name specifier may trigger deprecation warnings.

+  // The use of a nested name specifier may trigger deprecation warnings.
   DiagnoseUseOfDecl(ND, IdentLoc);
 
   NamespaceAliasDecl *AliasDecl =
@@ -8926,7 +9069,7 @@
     ASTContext &Context = SemaRef.Context;
     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
         Context.getCanonicalType(Context.getRecordType(Base)));
-    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
+    DeclContext::lookup_result Decls = Derived->lookup(Name);
     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
   }
 
@@ -9269,7 +9412,7 @@
   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
     if (Record->isInvalidDecl()) {
       DelayedDefaultedMemberExceptionSpecs.clear();
-      DelayedDestructorExceptionSpecChecks.clear();
+      DelayedExceptionSpecChecks.clear();
       return;
     }
   }
@@ -9309,8 +9452,8 @@
 //  copy/move operators. These classes serve as factory functions and help us
 //  avoid using the same Expr* in the AST twice.
 class ExprBuilder {
-  ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
-  ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
+  ExprBuilder(const ExprBuilder&) = delete;
+  ExprBuilder &operator=(const ExprBuilder&) = delete;
 
 protected:
   static Expr *assertNotNull(Expr *E) {
@@ -12932,7 +13075,7 @@
     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
   if (!Pos.second) {
     // If we already had an entry, check to see if we are promoting this vtable
-    // to required a definition. If so, we need to reappend to the VTableUses
+    // to require a definition. If so, we need to reappend to the VTableUses
     // list, since we may have already processed the first entry.
     if (DefinitionRequired && !Pos.first->second) {
       Pos.first->second = true;
@@ -13034,7 +13177,8 @@
     DefinedAnything = true;
     MarkVirtualMembersReferenced(Loc, Class);
     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
-    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
+    if (VTablesUsed[Canonical])
+      Consumer.HandleVTable(Class);
 
     // Optionally warn if we're emitting a weak vtable.
     if (Class->isExternallyVisible() &&
diff --git a/lib/Sema/SemaDeclObjC.cpp b/lib/Sema/SemaDeclObjC.cpp
index eccf2e1..33d9e95 100644
--- a/lib/Sema/SemaDeclObjC.cpp
+++ b/lib/Sema/SemaDeclObjC.cpp
@@ -617,8 +617,7 @@
     QualType T = TDecl->getUnderlyingType();
     if (T->isObjCObjectType())
       if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
-        for (auto *I : OPT->quals())
-          ProtocolRefs.push_back(I);
+        ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
   }
 }
 
@@ -2004,13 +2003,12 @@
                                 IncompleteImpl, InsMap, ClsMap, CDecl,
                                 ExplicitImplProtocols);
       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
-                                      /* SynthesizeProperties */ false);
+                                      /*SynthesizeProperties=*/false);
     } 
   } else
     llvm_unreachable("invalid ObjCContainerDecl type.");
 }
 
-/// ActOnForwardClassDeclaration -
 Sema::DeclGroupPtrTy
 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
                                    IdentifierInfo **IdentList,
@@ -2037,10 +2035,11 @@
       } else {
         // a forward class declaration matching a typedef name of a class refers
         // to the underlying class. Just ignore the forward class with a warning
-        // as this will force the intended behavior which is to lookup the typedef
-        // name.
+        // as this will force the intended behavior which is to lookup the
+        // typedef name.
         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
-          Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
+          Diag(AtClassLoc, diag::warn_forward_class_redefinition)
+              << IdentList[i];
           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
           continue;
         }
@@ -2217,22 +2216,22 @@
   return true;
 }
 
-void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
+void Sema::addMethodToGlobalList(ObjCMethodList *List,
+                                 ObjCMethodDecl *Method) {
   // Record at the head of the list whether there were 0, 1, or >= 2 methods
   // inside categories.
-  if (ObjCCategoryDecl *
-        CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
+  if (ObjCCategoryDecl *CD =
+          dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
     if (!CD->IsClassExtension() && List->getBits() < 2)
-        List->setBits(List->getBits()+1);
+      List->setBits(List->getBits() + 1);
 
   // If the list is empty, make it a singleton list.
-  if (List->Method == nullptr) {
-    List->Method = Method;
+  if (List->getMethod() == nullptr) {
+    List->setMethod(Method);
     List->setNext(nullptr);
-      List->Count = Method->isDefined() ? 0 : 1;
     return;
   }
-  
+
   // We've seen a method with this name, see if we have already seen this type
   // signature.
   ObjCMethodList *Previous = List;
@@ -2241,37 +2240,42 @@
     if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
       continue;
 
-    if (!MatchTwoMethodDeclarations(Method, List->Method))
+    if (!MatchTwoMethodDeclarations(Method, List->getMethod()))
       continue;
-      
-    ObjCMethodDecl *PrevObjCMethod = List->Method;
+
+    ObjCMethodDecl *PrevObjCMethod = List->getMethod();
 
     // Propagate the 'defined' bit.
     if (Method->isDefined())
       PrevObjCMethod->setDefined(true);
-    else
-      ++List->Count;
-    
+    else {
+      // Objective-C doesn't allow an @interface for a class after its
+      // @implementation. So if Method is not defined and there already is
+      // an entry for this type signature, Method has to be for a different
+      // class than PrevObjCMethod.
+      List->setHasMoreThanOneDecl(true);
+    }
+
     // If a method is deprecated, push it in the global pool.
     // This is used for better diagnostics.
     if (Method->isDeprecated()) {
       if (!PrevObjCMethod->isDeprecated())
-        List->Method = Method;
+        List->setMethod(Method);
     }
-    // If new method is unavailable, push it into global pool
+    // If the new method is unavailable, push it into global pool
     // unless previous one is deprecated.
     if (Method->isUnavailable()) {
       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
-        List->Method = Method;
+        List->setMethod(Method);
     }
-    
+
     return;
   }
-  
+
   // We have a new signature for an existing method - add it.
   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
-  Previous->setNext(new (Mem) ObjCMethodList(Method, 0, nullptr));
+  Previous->setNext(new (Mem) ObjCMethodList(Method));
 }
 
 /// \brief Read the contents of the method pool for a given selector from
@@ -2294,7 +2298,7 @@
   if (Pos == MethodPool.end())
     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
                                            GlobalMethods())).first;
-  
+
   Method->setDefined(impl);
   
   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
@@ -2320,9 +2324,8 @@
   return (chosen->getReturnType()->isIntegerType());
 }
 
-bool Sema::CollectMultipleMethodsInGlobalPool(Selector Sel,
-                                              SmallVectorImpl<ObjCMethodDecl*>& Methods,
-                                              bool instance) {
+bool Sema::CollectMultipleMethodsInGlobalPool(
+    Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
   if (ExternalSource)
     ReadMethodPool(Sel);
 
@@ -2332,19 +2335,19 @@
   // Gather the non-hidden methods.
   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
   for (ObjCMethodList *M = &MethList; M; M = M->getNext())
-    if (M->Method && !M->Method->isHidden())
-      Methods.push_back(M->Method);
-  return (Methods.size() > 1);
+    if (M->getMethod() && !M->getMethod()->isHidden())
+      Methods.push_back(M->getMethod());
+  return Methods.size() > 1;
 }
 
-bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel,
-                                          bool instance) {
+bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, bool instance) {
   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
-  // Test for no method in the pool which should not trigger any warning by caller.
+  // Test for no method in the pool which should not trigger any warning by
+  // caller.
   if (Pos == MethodPool.end())
     return true;
   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
-  return MethList.Count > 1;
+  return MethList.hasMoreThanOneDecl();
 }
 
 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
@@ -2361,12 +2364,12 @@
   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
   SmallVector<ObjCMethodDecl *, 4> Methods;
   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
-    if (M->Method && !M->Method->isHidden()) {
+    if (M->getMethod() && !M->getMethod()->isHidden()) {
       // If we're not supposed to warn about mismatches, we're done.
       if (!warn)
-        return M->Method;
+        return M->getMethod();
 
-      Methods.push_back(M->Method);
+      Methods.push_back(M->getMethod());
     }
   }
 
@@ -2438,13 +2441,17 @@
   GlobalMethods &Methods = Pos->second;
   for (const ObjCMethodList *Method = &Methods.first; Method;
        Method = Method->getNext())
-    if (Method->Method && Method->Method->isDefined())
-      return Method->Method;
+    if (Method->getMethod() &&
+        (Method->getMethod()->isDefined() ||
+         Method->getMethod()->isPropertyAccessor()))
+      return Method->getMethod();
   
   for (const ObjCMethodList *Method = &Methods.second; Method;
        Method = Method->getNext())
-    if (Method->Method && Method->Method->isDefined())
-      return Method->Method;
+    if (Method->getMethod() &&
+        (Method->getMethod()->isDefined() ||
+         Method->getMethod()->isPropertyAccessor()))
+      return Method->getMethod();
   return nullptr;
 }
 
@@ -2507,25 +2514,27 @@
        e = MethodPool.end(); b != e; b++) {
     // instance methods
     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
-      if (M->Method &&
-          (M->Method->getSelector().getNumArgs() == NumArgs) &&
-          (M->Method->getSelector() != Sel)) {
+      if (M->getMethod() &&
+          (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
+          (M->getMethod()->getSelector() != Sel)) {
         if (ObjectIsId)
-          Methods.push_back(M->Method);
+          Methods.push_back(M->getMethod());
         else if (!ObjectIsClass &&
-                 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
-          Methods.push_back(M->Method);
+                 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
+                                          ObjectType))
+          Methods.push_back(M->getMethod());
       }
     // class methods
     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
-      if (M->Method &&
-          (M->Method->getSelector().getNumArgs() == NumArgs) &&
-          (M->Method->getSelector() != Sel)) {
+      if (M->getMethod() &&
+          (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
+          (M->getMethod()->getSelector() != Sel)) {
         if (ObjectIsClass)
-          Methods.push_back(M->Method);
+          Methods.push_back(M->getMethod());
         else if (!ObjectIsId &&
-                 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
-          Methods.push_back(M->Method);
+                 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
+                                          ObjectType))
+          Methods.push_back(M->getMethod());
       }
   }
   
@@ -2855,7 +2864,7 @@
     }
     ObjCMethodList &list =
       method->isInstanceMethod() ? it->second.first : it->second.second;
-    if (!list.Method) return;
+    if (!list.getMethod()) return;
 
     ObjCContainerDecl *container
       = cast<ObjCContainerDecl>(method->getDeclContext());
diff --git a/lib/Sema/SemaExceptionSpec.cpp b/lib/Sema/SemaExceptionSpec.cpp
index 7175c01..41abd49 100644
--- a/lib/Sema/SemaExceptionSpec.cpp
+++ b/lib/Sema/SemaExceptionSpec.cpp
@@ -437,7 +437,7 @@
       OldNR != FunctionProtoType::NR_NoNoexcept &&
       NewNR != FunctionProtoType::NR_NoNoexcept) {
     Diag(NewLoc, DiagID);
-    if (NoteID.getDiagID() != 0)
+    if (NoteID.getDiagID() != 0 && OldLoc.isValid())
       Diag(OldLoc, NoteID);
     return true;
   }
@@ -518,7 +518,7 @@
     }
 
     Diag(NewLoc, DiagID);
-    if (NoteID.getDiagID() != 0)
+    if (NoteID.getDiagID() != 0 && OldLoc.isValid())
       Diag(OldLoc, NoteID);
     return true;
   }
@@ -547,7 +547,7 @@
     return false;
   }
   Diag(NewLoc, DiagID);
-  if (NoteID.getDiagID() != 0)
+  if (NoteID.getDiagID() != 0 && OldLoc.isValid())
     Diag(OldLoc, NoteID);
   return true;
 }
@@ -801,6 +801,11 @@
 
 bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
                                                 const CXXMethodDecl *Old) {
+  // If the new exception specification hasn't been parsed yet, skip the check.
+  // We'll get called again once it's been parsed.
+  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
+      EST_Unparsed)
+    return false;
   if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
     // Don't check uninstantiated template destructors at all. We can only
     // synthesize correct specs after the template is instantiated.
@@ -809,16 +814,18 @@
     if (New->getParent()->isBeingDefined()) {
       // The destructor might be updated once the definition is finished. So
       // remember it and check later.
-      DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
-        cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
+      DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
       return false;
     }
   }
-  // If the exception specification hasn't been parsed yet, skip the check.
-  // We'll get called again once it's been parsed.
-  if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
-      EST_Unparsed)
+  // If the old exception specification hasn't been parsed yet, remember that
+  // we need to perform this check when we get to the end of the outermost
+  // lexically-surrounding class.
+  if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
+      EST_Unparsed) {
+    DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
     return false;
+  }
   unsigned DiagID = diag::err_override_exception_spec;
   if (getLangOpts().MicrosoftExt)
     DiagID = diag::ext_override_exception_spec;
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index dc02f4e..3725b2d 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -76,8 +76,8 @@
 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
   // Warn if this is used but marked unused.
   if (D->hasAttr<UnusedAttr>()) {
-    const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
-    if (!DC->hasAttr<UnusedAttr>())
+    const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
+    if (DC && !DC->hasAttr<UnusedAttr>())
       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
   }
 }
@@ -1290,6 +1290,13 @@
     ControllingExpr = result.get();
   }
 
+  // The controlling expression is an unevaluated operand, so side effects are
+  // likely unintended.
+  if (ActiveTemplateInstantiations.empty() &&
+      ControllingExpr->HasSideEffects(Context, false))
+    Diag(ControllingExpr->getExprLoc(),
+         diag::warn_side_effects_unevaluated_context);
+
   bool TypeErrorFound = false,
        IsResultDependent = ControllingExpr->isTypeDependent(),
        ContainsUnexpandedParameterPack
@@ -1590,40 +1597,37 @@
   if (getLangOpts().CUDA)
     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
-        CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
-                           CalleeTarget = IdentifyCUDATarget(Callee);
-        if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
+        if (CheckCUDATarget(Caller, Callee)) {
           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
-            << CalleeTarget << D->getIdentifier() << CallerTarget;
+            << IdentifyCUDATarget(Callee) << D->getIdentifier()
+            << IdentifyCUDATarget(Caller);
           Diag(D->getLocation(), diag::note_previous_decl)
             << D->getIdentifier();
           return ExprError();
         }
       }
 
-  bool refersToEnclosingScope =
-    (CurContext != D->getDeclContext() &&
-     D->getDeclContext()->isFunctionOrMethod()) ||
-    (isa<VarDecl>(D) &&
-     cast<VarDecl>(D)->isInitCapture());
+  bool RefersToCapturedVariable =
+      isa<VarDecl>(D) &&
+      NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
 
   DeclRefExpr *E;
   if (isa<VarTemplateSpecializationDecl>(D)) {
     VarTemplateSpecializationDecl *VarSpec =
         cast<VarTemplateSpecializationDecl>(D);
 
-    E = DeclRefExpr::Create(
-        Context,
-        SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
-        VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
-        NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
+    E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
+                                        : NestedNameSpecifierLoc(),
+                            VarSpec->getTemplateKeywordLoc(), D,
+                            RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
+                            FoundD, TemplateArgs);
   } else {
     assert(!TemplateArgs && "No template arguments for non-variable"
                             " template specialization references");
-    E = DeclRefExpr::Create(
-        Context,
-        SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
-        SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
+    E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
+                                        : NestedNameSpecifierLoc(),
+                            SourceLocation(), D, RefersToCapturedVariable,
+                            NameInfo, Ty, VK, FoundD);
   }
 
   MarkDeclRefReferenced(E);
@@ -2122,9 +2126,9 @@
       if (SS.isValid())
         CCC->setTypoNNS(SS.getScopeRep());
     }
-    if (DiagnoseEmptyLookup(
-            S, SS, R, CCC ? std::move(CCC) : std::move(DefaultValidator),
-            nullptr, None, getLangOpts().CPlusPlus ? &TE : nullptr)) {
+    if (DiagnoseEmptyLookup(S, SS, R,
+                            CCC ? std::move(CCC) : std::move(DefaultValidator),
+                            nullptr, None, &TE)) {
       if (TE && KeywordReplacement) {
         auto &State = getTypoExprState(TE);
         auto BestTC = State.Consumer->getNextCorrection();
@@ -3262,7 +3266,9 @@
     if (Ty == Context.DoubleTy) {
       if (getLangOpts().SinglePrecisionConstants) {
         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
-      } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
+      } else if (getLangOpts().OpenCL &&
+                 !((getLangOpts().OpenCLVersion >= 120) ||
+                   getOpenCLOptions().cl_khr_fp64)) {
         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
       }
@@ -3528,6 +3534,12 @@
     return true;
   }
 
+  // The operand for sizeof and alignof is in an unevaluated expression context,
+  // so side effects could result in unintended consequences.
+  if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
+      ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
+    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
+
   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
                                        E->getSourceRange(), ExprKind))
     return true;
@@ -4541,6 +4553,8 @@
       ExprResult result = S.CheckPlaceholderExpr(args[i]);
       if (result.isInvalid()) hasInvalid = true;
       else args[i] = result.get();
+    } else if (hasInvalid) {
+      (void)S.CorrectDelayedTyposInExpr(args[i]);
     }
   }
   return hasInvalid;
@@ -5297,6 +5311,12 @@
   if (getLangOpts().CPlusPlus) {
     // Check that there are no default arguments (C++ only).
     CheckExtraCXXDefaultArguments(D);
+  } else {
+    // Make sure any TypoExprs have been dealt with.
+    ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
+    if (!Res.isUsable())
+      return ExprError();
+    CastExpr = Res.get();
   }
 
   checkUnusedDeclAttributes(D);
@@ -5498,47 +5518,24 @@
 }
 
 /// \brief Return false if the condition expression is valid, true otherwise.
-static bool checkCondition(Sema &S, Expr *Cond) {
+static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
   QualType CondTy = Cond->getType();
 
+  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
+  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
+    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
+      << CondTy << Cond->getSourceRange();
+    return true;
+  }
+
   // C99 6.5.15p2
   if (CondTy->isScalarType()) return false;
 
-  // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
-  if (S.getLangOpts().OpenCL && CondTy->isVectorType())
-    return false;
-
-  // Emit the proper error message.
-  S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
-                              diag::err_typecheck_cond_expect_scalar :
-                              diag::err_typecheck_cond_expect_scalar_or_vector)
-    << CondTy;
+  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
+    << CondTy << Cond->getSourceRange();
   return true;
 }
 
-/// \brief Return false if the two expressions can be converted to a vector,
-/// true otherwise
-static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
-                                                    ExprResult &RHS,
-                                                    QualType CondTy) {
-  // Both operands should be of scalar type.
-  if (!LHS.get()->getType()->isScalarType()) {
-    S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
-      << CondTy;
-    return true;
-  }
-  if (!RHS.get()->getType()->isScalarType()) {
-    S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
-      << CondTy;
-    return true;
-  }
-
-  // Implicity convert these scalars to the type of the condition.
-  LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
-  RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
-  return false;
-}
-
 /// \brief Handle when one or both operands are void type.
 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
                                          ExprResult &RHS) {
@@ -5755,6 +5752,184 @@
   return true;
 }
 
+/// \brief Simple conversion between integer and floating point types.
+///
+/// Used when handling the OpenCL conditional operator where the
+/// condition is a vector while the other operands are scalar.
+///
+/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
+/// types are either integer or floating type. Between the two
+/// operands, the type with the higher rank is defined as the "result
+/// type". The other operand needs to be promoted to the same type. No
+/// other type promotion is allowed. We cannot use
+/// UsualArithmeticConversions() for this purpose, since it always
+/// promotes promotable types.
+static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
+                                            ExprResult &RHS,
+                                            SourceLocation QuestionLoc) {
+  LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
+  if (LHS.isInvalid())
+    return QualType();
+  RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
+  if (RHS.isInvalid())
+    return QualType();
+
+  // For conversion purposes, we ignore any qualifiers.
+  // For example, "const float" and "float" are equivalent.
+  QualType LHSType =
+    S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
+  QualType RHSType =
+    S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
+
+  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
+    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
+      << LHSType << LHS.get()->getSourceRange();
+    return QualType();
+  }
+
+  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
+    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
+      << RHSType << RHS.get()->getSourceRange();
+    return QualType();
+  }
+
+  // If both types are identical, no conversion is needed.
+  if (LHSType == RHSType)
+    return LHSType;
+
+  // Now handle "real" floating types (i.e. float, double, long double).
+  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
+    return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
+                                 /*IsCompAssign = */ false);
+
+  // Finally, we have two differing integer types.
+  return handleIntegerConversion<doIntegralCast, doIntegralCast>
+  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
+}
+
+/// \brief Convert scalar operands to a vector that matches the
+///        condition in length.
+///
+/// Used when handling the OpenCL conditional operator where the
+/// condition is a vector while the other operands are scalar.
+///
+/// We first compute the "result type" for the scalar operands
+/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
+/// into a vector of that type where the length matches the condition
+/// vector type. s6.11.6 requires that the element types of the result
+/// and the condition must have the same number of bits.
+static QualType
+OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
+                              QualType CondTy, SourceLocation QuestionLoc) {
+  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
+  if (ResTy.isNull()) return QualType();
+
+  const VectorType *CV = CondTy->getAs<VectorType>();
+  assert(CV);
+
+  // Determine the vector result type
+  unsigned NumElements = CV->getNumElements();
+  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
+
+  // Ensure that all types have the same number of bits
+  if (S.Context.getTypeSize(CV->getElementType())
+      != S.Context.getTypeSize(ResTy)) {
+    // Since VectorTy is created internally, it does not pretty print
+    // with an OpenCL name. Instead, we just print a description.
+    std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
+    SmallString<64> Str;
+    llvm::raw_svector_ostream OS(Str);
+    OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
+    S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
+      << CondTy << OS.str();
+    return QualType();
+  }
+
+  // Convert operands to the vector result type
+  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
+  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
+
+  return VectorTy;
+}
+
+/// \brief Return false if this is a valid OpenCL condition vector
+static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
+                                       SourceLocation QuestionLoc) {
+  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
+  // integral type.
+  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
+  assert(CondTy);
+  QualType EleTy = CondTy->getElementType();
+  if (EleTy->isIntegerType()) return false;
+
+  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
+    << Cond->getType() << Cond->getSourceRange();
+  return true;
+}
+
+/// \brief Return false if the vector condition type and the vector
+///        result type are compatible.
+///
+/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
+/// number of elements, and their element types have the same number
+/// of bits.
+static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
+                              SourceLocation QuestionLoc) {
+  const VectorType *CV = CondTy->getAs<VectorType>();
+  const VectorType *RV = VecResTy->getAs<VectorType>();
+  assert(CV && RV);
+
+  if (CV->getNumElements() != RV->getNumElements()) {
+    S.Diag(QuestionLoc, diag::err_conditional_vector_size)
+      << CondTy << VecResTy;
+    return true;
+  }
+
+  QualType CVE = CV->getElementType();
+  QualType RVE = RV->getElementType();
+
+  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
+    S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
+      << CondTy << VecResTy;
+    return true;
+  }
+
+  return false;
+}
+
+/// \brief Return the resulting type for the conditional operator in
+///        OpenCL (aka "ternary selection operator", OpenCL v1.1
+///        s6.3.i) when the condition is a vector type.
+static QualType
+OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
+                             ExprResult &LHS, ExprResult &RHS,
+                             SourceLocation QuestionLoc) {
+  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
+  if (Cond.isInvalid())
+    return QualType();
+  QualType CondTy = Cond.get()->getType();
+
+  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
+    return QualType();
+
+  // If either operand is a vector then find the vector type of the
+  // result as specified in OpenCL v1.1 s6.3.i.
+  if (LHS.get()->getType()->isVectorType() ||
+      RHS.get()->getType()->isVectorType()) {
+    QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
+                                              /*isCompAssign*/false);
+    if (VecResTy.isNull()) return QualType();
+    // The result type must match the condition type as specified in
+    // OpenCL v1.1 s6.11.6.
+    if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
+      return QualType();
+    return VecResTy;
+  }
+
+  // Both operands are scalar.
+  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
+}
+
 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
 /// In that case, LHS = cond.
 /// C99 6.5.15
@@ -5778,11 +5953,16 @@
   VK = VK_RValue;
   OK = OK_Ordinary;
 
+  // The OpenCL operator with a vector condition is sufficiently
+  // different to merit its own checker.
+  if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
+    return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
+
   // First, check the condition.
   Cond = UsualUnaryConversions(Cond.get());
   if (Cond.isInvalid())
     return QualType();
-  if (checkCondition(*this, Cond.get()))
+  if (checkCondition(*this, Cond.get(), QuestionLoc))
     return QualType();
 
   // Now check the two expressions.
@@ -5794,17 +5974,9 @@
   if (LHS.isInvalid() || RHS.isInvalid())
     return QualType();
 
-  QualType CondTy = Cond.get()->getType();
   QualType LHSTy = LHS.get()->getType();
   QualType RHSTy = RHS.get()->getType();
 
-  // If the condition is a vector, and both operands are scalar,
-  // attempt to implicity convert them to the vector type to act like the
-  // built in select. (OpenCL v1.1 s6.3.i)
-  if (getLangOpts().OpenCL && CondTy->isVectorType())
-    if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
-      return QualType();
-  
   // If both operands have arithmetic type, do the usual arithmetic conversions
   // to find a common type: C99 6.5.15p3,5.
   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
@@ -6098,6 +6270,8 @@
     return IsLogicOp(OP->getOpcode());
   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
     return OP->getOpcode() == UO_LNot;
+  if (E->getType()->isPointerType())
+    return true;
 
   return false;
 }
@@ -6142,6 +6316,15 @@
                                     SourceLocation ColonLoc,
                                     Expr *CondExpr, Expr *LHSExpr,
                                     Expr *RHSExpr) {
+  if (!getLangOpts().CPlusPlus) {
+    // C cannot handle TypoExpr nodes in the condition because it
+    // doesn't handle dependent types properly, so make sure any TypoExprs have
+    // been dealt with before checking the operands.
+    ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
+    if (!CondResult.isUsable()) return ExprError();
+    CondExpr = CondResult.get();
+  }
+
   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
   // was the condition.
   OpaqueValueExpr *opaqueValue = nullptr;
@@ -6235,7 +6418,7 @@
 
   if (!lhq.compatiblyIncludes(rhq)) {
     // Treat address-space mismatches as fatal.  TODO: address subspaces
-    if (lhq.getAddressSpace() != rhq.getAddressSpace())
+    if (!lhq.isAddressSpaceSupersetOf(rhq))
       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
 
     // It's okay to add or remove GC or lifetime qualifiers when converting to
@@ -6520,7 +6703,9 @@
   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
     // U* -> T*
     if (isa<PointerType>(RHSType)) {
-      Kind = CK_BitCast;
+      unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
+      unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
+      Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
     }
 
@@ -7149,9 +7334,12 @@
 /// \returns True if pointer has incomplete type
 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
                                                  Expr *Operand) {
-  assert(Operand->getType()->isAnyPointerType() &&
-         !Operand->getType()->isDependentType());
-  QualType PointeeTy = Operand->getType()->getPointeeType();
+  QualType ResType = Operand->getType();
+  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
+    ResType = ResAtomicType->getValueType();
+
+  assert(ResType->isAnyPointerType() && !ResType->isDependentType());
+  QualType PointeeTy = ResType->getPointeeType();
   return S.RequireCompleteType(Loc, PointeeTy,
                                diag::err_typecheck_arithmetic_incomplete_type,
                                PointeeTy, Operand->getSourceRange());
@@ -7167,9 +7355,13 @@
 /// \returns True when the operand is valid to use (even if as an extension).
 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
                                             Expr *Operand) {
-  if (!Operand->getType()->isAnyPointerType()) return true;
+  QualType ResType = Operand->getType();
+  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
+    ResType = ResAtomicType->getValueType();
 
-  QualType PointeeTy = Operand->getType()->getPointeeType();
+  if (!ResType->isAnyPointerType()) return true;
+
+  QualType PointeeTy = ResType->getPointeeType();
   if (PointeeTy->isVoidType()) {
     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
     return !S.getLangOpts().CPlusPlus;
@@ -7203,6 +7395,19 @@
   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
 
+  // if both are pointers check if operation is valid wrt address spaces
+  if (isLHSPointer && isRHSPointer) {
+    const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
+    const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
+    if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
+      S.Diag(Loc,
+             diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
+          << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
+          << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
+      return false;
+    }
+  }
+
   // Check for arithmetic on pointers to incomplete types.
   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
@@ -7246,7 +7451,7 @@
 
   bool IsStringPlusInt = StrExpr &&
       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
-  if (!IsStringPlusInt)
+  if (!IsStringPlusInt || IndexExpr->isValueDependent())
     return;
 
   llvm::APSInt index;
@@ -7276,13 +7481,13 @@
 /// \brief Emit a warning when adding a char literal to a string.
 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
                                    Expr *LHSExpr, Expr *RHSExpr) {
-  const DeclRefExpr *StringRefExpr =
-      dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
+  const Expr *StringRefExpr = LHSExpr;
   const CharacterLiteral *CharExpr =
       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
-  if (!StringRefExpr) {
-    StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
+
+  if (!CharExpr) {
     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
+    StringRefExpr = RHSExpr;
   }
 
   if (!CharExpr || !StringRefExpr)
@@ -7500,7 +7705,7 @@
 }
 
 static bool isScopedEnumerationType(QualType T) {
-  if (const EnumType *ET = dyn_cast<EnumType>(T))
+  if (const EnumType *ET = T->getAs<EnumType>())
     return ET->getDecl()->isScoped();
   return false;
 }
@@ -7574,6 +7779,69 @@
     << RHS.get()->getSourceRange();
 }
 
+/// \brief Return the resulting type when an OpenCL vector is shifted
+///        by a scalar or vector shift amount.
+static QualType checkOpenCLVectorShift(Sema &S,
+                                       ExprResult &LHS, ExprResult &RHS,
+                                       SourceLocation Loc, bool IsCompAssign) {
+  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
+  if (!LHS.get()->getType()->isVectorType()) {
+    S.Diag(Loc, diag::err_shift_rhs_only_vector)
+      << RHS.get()->getType() << LHS.get()->getType()
+      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
+    return QualType();
+  }
+
+  if (!IsCompAssign) {
+    LHS = S.UsualUnaryConversions(LHS.get());
+    if (LHS.isInvalid()) return QualType();
+  }
+
+  RHS = S.UsualUnaryConversions(RHS.get());
+  if (RHS.isInvalid()) return QualType();
+
+  QualType LHSType = LHS.get()->getType();
+  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
+  QualType LHSEleType = LHSVecTy->getElementType();
+
+  // Note that RHS might not be a vector.
+  QualType RHSType = RHS.get()->getType();
+  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
+  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
+
+  // OpenCL v1.1 s6.3.j says that the operands need to be integers.
+  if (!LHSEleType->isIntegerType()) {
+    S.Diag(Loc, diag::err_typecheck_expect_int)
+      << LHS.get()->getType() << LHS.get()->getSourceRange();
+    return QualType();
+  }
+
+  if (!RHSEleType->isIntegerType()) {
+    S.Diag(Loc, diag::err_typecheck_expect_int)
+      << RHS.get()->getType() << RHS.get()->getSourceRange();
+    return QualType();
+  }
+
+  if (RHSVecTy) {
+    // OpenCL v1.1 s6.3.j says that for vector types, the operators
+    // are applied component-wise. So if RHS is a vector, then ensure
+    // that the number of elements is the same as LHS...
+    if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
+      S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
+        << LHS.get()->getType() << RHS.get()->getType()
+        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
+      return QualType();
+    }
+  } else {
+    // ...else expand RHS to match the number of elements in LHS.
+    QualType VecTy =
+      S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
+    RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
+  }
+
+  return LHSType;
+}
+
 // C99 6.5.7
 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
                                   SourceLocation Loc, unsigned Opc,
@@ -7582,8 +7850,11 @@
 
   // Vector shifts promote their scalar inputs to vector type.
   if (LHS.get()->getType()->isVectorType() ||
-      RHS.get()->getType()->isVectorType())
+      RHS.get()->getType()->isVectorType()) {
+    if (LangOpts.OpenCL)
+      return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
+  }
 
   // Shifts don't perform usual arithmetic conversions, they just do integer
   // promotions on each operand. C99 6.5.7p3
@@ -8131,6 +8402,13 @@
       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
     }
     if (LCanPointeeTy != RCanPointeeTy) {
+      const PointerType *lhsPtr = LHSType->getAs<PointerType>();
+      if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
+        Diag(Loc,
+             diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
+            << LHSType << RHSType << 0 /* comparison */
+            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
+      }
       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
@@ -8545,7 +8823,7 @@
   // Must be a reference to a declaration from an enclosing scope.
   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
   if (!DRE) return NCCK_None;
-  if (!DRE->refersToEnclosingLocal()) return NCCK_None;
+  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
 
   // The declaration must be a variable which is not declared 'const'.
   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
@@ -8577,19 +8855,19 @@
   if (IsLV == Expr::MLV_Valid)
     return false;
 
-  unsigned Diag = 0;
+  unsigned DiagID = 0;
   bool NeedType = false;
   switch (IsLV) { // C99 6.5.16p2
   case Expr::MLV_ConstQualified:
-    Diag = diag::err_typecheck_assign_const;
+    DiagID = diag::err_typecheck_assign_const;
 
     // Use a specialized diagnostic when we're assigning to an object
     // from an enclosing function or block.
     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
       if (NCCK == NCCK_Block)
-        Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
+        DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
       else
-        Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
+        DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
       break;
     }
 
@@ -8609,18 +8887,18 @@
           //  - self
           ObjCMethodDecl *method = S.getCurMethodDecl();
           if (method && var == method->getSelfDecl())
-            Diag = method->isClassMethod()
+            DiagID = method->isClassMethod()
               ? diag::err_typecheck_arc_assign_self_class_method
               : diag::err_typecheck_arc_assign_self;
 
           //  - fast enumeration variables
           else
-            Diag = diag::err_typecheck_arr_assign_enumeration;
+            DiagID = diag::err_typecheck_arr_assign_enumeration;
 
           SourceRange Assign;
           if (Loc != OrigLoc)
             Assign = SourceRange(OrigLoc, OrigLoc);
-          S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
+          S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
           // We need to preserve the AST regardless, so migration tool 
           // can do its job.
           return false;
@@ -8631,37 +8909,37 @@
     break;
   case Expr::MLV_ArrayType:
   case Expr::MLV_ArrayTemporary:
-    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
+    DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
     NeedType = true;
     break;
   case Expr::MLV_NotObjectType:
-    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
+    DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
     NeedType = true;
     break;
   case Expr::MLV_LValueCast:
-    Diag = diag::err_typecheck_lvalue_casts_not_supported;
+    DiagID = diag::err_typecheck_lvalue_casts_not_supported;
     break;
   case Expr::MLV_Valid:
     llvm_unreachable("did not take early return for MLV_Valid");
   case Expr::MLV_InvalidExpression:
   case Expr::MLV_MemberFunction:
   case Expr::MLV_ClassTemporary:
-    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
+    DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
     break;
   case Expr::MLV_IncompleteType:
   case Expr::MLV_IncompleteVoidType:
     return S.RequireCompleteType(Loc, E->getType(),
              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
   case Expr::MLV_DuplicateVectorComponents:
-    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
+    DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
     break;
   case Expr::MLV_NoSetterProperty:
     llvm_unreachable("readonly properties should be processed differently");
   case Expr::MLV_InvalidMessageExpression:
-    Diag = diag::error_readonly_message_assignment;
+    DiagID = diag::error_readonly_message_assignment;
     break;
   case Expr::MLV_SubObjCPropertySetting:
-    Diag = diag::error_no_subobject_property_setting;
+    DiagID = diag::error_no_subobject_property_setting;
     break;
   }
 
@@ -8669,9 +8947,9 @@
   if (Loc != OrigLoc)
     Assign = SourceRange(OrigLoc, OrigLoc);
   if (NeedType)
-    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
+    S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
   else
-    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
+    S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
   return true;
 }
 
@@ -8703,17 +8981,6 @@
                                        QualType CompoundType) {
   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
 
-  if (!getLangOpts().CPlusPlus) {
-    // C cannot handle TypoExpr nodes on either side of n assignment because it
-    // doesn't handle dependent types properly, so make sure any TypoExprs have
-    // been dealt with before checking the operands.
-    ExprResult Res = CorrectDelayedTyposInExpr(LHSExpr);
-    Expr *NewLHS = Res.isInvalid() ? LHSExpr : Res.get();
-    Res = CorrectDelayedTyposInExpr(RHS);
-    if (!Res.isInvalid() && (Res.get() != RHS.get() || NewLHS != LHSExpr))
-      return CheckAssignmentOperands(NewLHS, Res, Loc, CompoundType);
-  }
-
   // Verify that LHS is a modifiable lvalue, and emit error if not.
   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
     return QualType();
@@ -9151,6 +9418,8 @@
           !getLangOpts().CPlusPlus) {
         AddressOfError = AO_Register_Variable;
       }
+    } else if (isa<MSPropertyDecl>(dcl)) {
+      AddressOfError = AO_Property_Expansion;
     } else if (isa<FunctionTemplateDecl>(dcl)) {
       return Context.OverloadTy;
     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
@@ -9211,7 +9480,7 @@
   if (!Param)
     return;
   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
-    if (!FD->hasAttr<NonNullAttr>())
+    if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
       return;
   if (FunctionScopeInfo *FD = S.getCurFunction())
     if (!FD->ModifiedNonNullParams.count(Param))
@@ -9415,6 +9684,18 @@
   }
 }
 
+static NamedDecl *getDeclFromExpr(Expr *E) {
+  if (!E)
+    return nullptr;
+  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
+    return DRE->getDecl();
+  if (auto *ME = dyn_cast<MemberExpr>(E))
+    return ME->getMemberDecl();
+  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
+    return IRE->getDecl();
+  return nullptr;
+}
+
 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
 /// operator @p Opc at location @c TokLoc. This routine only supports
 /// built-in operations; ActOnBinOp handles overloaded operators.
@@ -9447,6 +9728,22 @@
   ExprValueKind VK = VK_RValue;
   ExprObjectKind OK = OK_Ordinary;
 
+  if (!getLangOpts().CPlusPlus) {
+    // C cannot handle TypoExpr nodes on either side of a binop because it
+    // doesn't handle dependent types properly, so make sure any TypoExprs have
+    // been dealt with before checking the operands.
+    LHS = CorrectDelayedTyposInExpr(LHSExpr);
+    RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
+      if (Opc != BO_Assign)
+        return ExprResult(E);
+      // Avoid correcting the RHS to the same Expr as the LHS.
+      Decl *D = getDeclFromExpr(E);
+      return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
+    });
+    if (!LHS.isUsable() || !RHS.isUsable())
+      return ExprError();
+  }
+
   switch (Opc) {
   case BO_Assign:
     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
@@ -9455,8 +9752,10 @@
       VK = LHS.get()->getValueKind();
       OK = LHS.get()->getObjectKind();
     }
-    if (!ResultTy.isNull())
+    if (!ResultTy.isNull()) {
       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
+      DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
+    }
     RecordModifiableNonNullParam(*this, LHS.get());
     break;
   case BO_PtrMemD:
@@ -10223,11 +10522,6 @@
   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
   PopExpressionEvaluationContext();
 
-  bool isFileScope
-    = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
-  if (isFileScope)
-    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
-
   // FIXME: there are a variety of strange constraints to enforce here, for
   // example, it is not possible to goto into a stmt expression apparently.
   // More semantic analysis is needed.
@@ -11380,12 +11674,9 @@
 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
                                       Decl *LambdaContextDecl,
                                       bool IsDecltype) {
-  ExprEvalContexts.push_back(
-             ExpressionEvaluationContextRecord(NewContext,
-                                               ExprCleanupObjects.size(),
-                                               ExprNeedsCleanups,
-                                               LambdaContextDecl,
-                                               IsDecltype));
+  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
+                                ExprNeedsCleanups, LambdaContextDecl,
+                                IsDecltype);
   ExprNeedsCleanups = false;
   if (!MaybeODRUseExprs.empty())
     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
@@ -11517,7 +11808,8 @@
   // We (incorrectly) mark overload resolution as an unevaluated context, so we
   // can just check that here. Skip the rest of this function if we've already
   // marked the function as used.
-  if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
+  if (Func->isUsed(/*CheckUsedAttr=*/false) ||
+      !IsPotentiallyEvaluatedContext(*this)) {
     // C++11 [temp.inst]p3:
     //   Unless a function template specialization has been explicitly
     //   instantiated or explicitly specialized, the function template
@@ -11569,7 +11861,7 @@
     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
     if (Destructor->isDefaulted() && !Destructor->isDeleted())
       DefineImplicitDestructor(Loc, Destructor);
-    if (Destructor->isVirtual())
+    if (Destructor->isVirtual() && getLangOpts().AppleKext)
       MarkVTableUsed(Loc, Destructor->getParent());
   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
     if (MethodDecl->isOverloadedOperator() &&
@@ -11589,7 +11881,7 @@
         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
       else
         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
-    } else if (MethodDecl->isVirtual())
+    } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
       MarkVTableUsed(Loc, MethodDecl->getParent());
   }
 
@@ -11757,7 +12049,7 @@
                                  const bool Diagnose, Sema &S) {
   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
     return getLambdaAwareParentOfDeclContext(DC);
-  else {
+  else if (Var->hasLocalStorage()) {
     if (Diagnose)
        diagnoseUncapturableValueReference(S, Loc, Var, DC);
   }
@@ -11925,7 +12217,7 @@
                                     const bool BuildAndDiagnose, 
                                     QualType &CaptureType,
                                     QualType &DeclRefType, 
-                                    const bool RefersToEnclosingLocal,
+                                    const bool RefersToCapturedVariable,
                                     Sema &S) {
   
   // By default, capture variables by reference.
@@ -11947,7 +12239,7 @@
     Field->setAccess(AS_private);
     RD->addDecl(Field);
  
-    CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
+    CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
                                             DeclRefType, VK_LValue, Loc);
     Var->setReferenced(true);
     Var->markUsed(S.Context);
@@ -11955,7 +12247,7 @@
 
   // Actually capture the variable.
   if (BuildAndDiagnose)
-    RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
+    RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
                     SourceLocation(), CaptureType, CopyExpr);
   
   
@@ -11969,7 +12261,7 @@
                                   VarDecl *Var, QualType FieldType, 
                                   QualType DeclRefType,
                                   SourceLocation Loc,
-                                  bool RefersToEnclosingLocal) {
+                                  bool RefersToCapturedVariable) {
   CXXRecordDecl *Lambda = LSI->Lambda;
 
   // Build the non-static data member.
@@ -11998,7 +12290,7 @@
   // C++ [expr.prim.labda]p12:
   //   An entity captured by a lambda-expression is odr-used (3.2) in
   //   the scope containing the lambda-expression.
-  Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 
+  Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 
                                           DeclRefType, VK_LValue, Loc);
   Var->setReferenced(true);
   Var->markUsed(S.Context);
@@ -12092,7 +12384,7 @@
                             const bool BuildAndDiagnose, 
                             QualType &CaptureType,
                             QualType &DeclRefType, 
-                            const bool RefersToEnclosingLocal,
+                            const bool RefersToCapturedVariable,
                             const Sema::TryCaptureKind Kind, 
                             SourceLocation EllipsisLoc,
                             const bool IsTopScope,
@@ -12166,7 +12458,7 @@
   if (BuildAndDiagnose) {
     ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 
                                         CaptureType, DeclRefType, Loc,
-                                        RefersToEnclosingLocal);
+                                        RefersToCapturedVariable);
     if (!Result.isInvalid())
       CopyExpr = Result.get();
   }
@@ -12187,7 +12479,7 @@
     
   // Add the capture.
   if (BuildAndDiagnose)
-    LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 
+    LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
                     Loc, EllipsisLoc, CaptureType, CopyExpr);
       
   return true;
@@ -12199,7 +12491,7 @@
                               QualType &CaptureType,
                               QualType &DeclRefType,
 						                const unsigned *const FunctionScopeIndexToStopAt) {
-  bool Nested = false;
+  bool Nested = Var->isInitCapture();
   
   DeclContext *DC = CurContext;
   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
@@ -12217,8 +12509,13 @@
   
   // If the variable is declared in the current context (and is not an 
   // init-capture), there is no need to capture it.
-  if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
-  if (!Var->hasLocalStorage()) return true;
+  if (!Nested && Var->getDeclContext() == DC) return true;
+
+  // Capture global variables if it is required to use private copy of this
+  // variable.
+  bool IsGlobal = !Var->hasLocalStorage();
+  if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
+    return true;
 
   // Walk up the stack to determine whether we can capture the variable,
   // performing the "simple" checks that don't depend on type. We stop when
@@ -12239,8 +12536,17 @@
                                                               ExprLoc, 
                                                               BuildAndDiagnose,
                                                               *this);
-    if (!ParentDC) return true;
-    
+    // We need to check for the parent *first* because, if we *have*
+    // private-captured a global variable, we need to recursively capture it in
+    // intermediate blocks, lambdas, etc.
+    if (!ParentDC) {
+      if (IsGlobal) {
+        FunctionScopesIndex = MaxFunctionScopesIndex - 1;
+        break;
+      }
+      return true;
+    }
+
     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
 
@@ -12466,6 +12772,14 @@
                             DeclRefType, nullptr);
 }
 
+bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
+  QualType CaptureType;
+  QualType DeclRefType;
+  return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
+                             /*BuildAndDiagnose=*/false, CaptureType,
+                             DeclRefType, nullptr);
+}
+
 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
   QualType CaptureType;
   QualType DeclRefType;
@@ -13619,6 +13933,15 @@
 /// Check for operands with placeholder types and complain if found.
 /// Returns true if there was an error and no recovery was possible.
 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
+  if (!getLangOpts().CPlusPlus) {
+    // C cannot handle TypoExpr nodes on either side of a binop because it
+    // doesn't handle dependent types properly, so make sure any TypoExprs have
+    // been dealt with before checking the operands.
+    ExprResult Result = CorrectDelayedTyposInExpr(E);
+    if (!Result.isUsable()) return ExprError();
+    E = Result.get();
+  }
+
   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
   if (!placeholderType) return E;
 
@@ -13643,7 +13966,17 @@
   // Bound member functions.
   case BuiltinType::BoundMember: {
     ExprResult result = E;
-    tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
+    const Expr *BME = E->IgnoreParens();
+    PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
+    // Try to give a nicer diagnostic if it is a bound member that we recognize.
+    if (isa<CXXPseudoDestructorExpr>(BME)) {
+      PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
+    } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
+      if (ME->getMemberNameInfo().getName().getNameKind() ==
+          DeclarationName::CXXDestructorName)
+        PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
+    }
+    tryToRecoverWithCall(result, PD,
                          /*complain*/ true);
     return result;
   }
diff --git a/lib/Sema/SemaExprCXX.cpp b/lib/Sema/SemaExprCXX.cpp
index 35211a2..695c3db 100644
--- a/lib/Sema/SemaExprCXX.cpp
+++ b/lib/Sema/SemaExprCXX.cpp
@@ -113,6 +113,9 @@
   bool isDependent = false;
   bool LookInScope = false;
 
+  if (SS.isInvalid())
+    return ParsedType();
+
   // If we have an object type, it's because we are in a
   // pseudo-destructor-expression or a member access expression, and
   // we know what type we're looking for.
@@ -384,6 +387,9 @@
       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
     return ExprError();
 
+  if (T->isVariablyModifiedType())
+    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
+
   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
                                      SourceRange(TypeidLoc, RParenLoc));
 }
@@ -393,6 +399,7 @@
                                 SourceLocation TypeidLoc,
                                 Expr *E,
                                 SourceLocation RParenLoc) {
+  bool WasEvaluated = false;
   if (E && !E->isTypeDependent()) {
     if (E->getType()->isPlaceholderType()) {
       ExprResult result = CheckPlaceholderExpr(E);
@@ -422,6 +429,7 @@
 
         // We require a vtable to query the type at run time.
         MarkVTableUsed(TypeidLoc, RecordD);
+        WasEvaluated = true;
       }
     }
 
@@ -438,6 +446,18 @@
     }
   }
 
+  if (E->getType()->isVariablyModifiedType())
+    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
+                     << E->getType());
+  else if (ActiveTemplateInstantiations.empty() &&
+           E->HasSideEffects(Context, WasEvaluated)) {
+    // The expression operand for typeid is in an unevaluated expression
+    // context, so side effects could result in unintended consequences.
+    Diag(E->getExprLoc(), WasEvaluated
+                              ? diag::warn_side_effects_typeid
+                              : diag::warn_side_effects_unevaluated_context);
+  }
+
   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
                                      SourceRange(TypeidLoc, RParenLoc));
 }
@@ -965,18 +985,21 @@
   Expr *Inner = Result.get();
   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
     Inner = BTE->getSubExpr();
-  if (isa<InitListExpr>(Inner)) {
-    // If the list-initialization doesn't involve a constructor call, we'll get
-    // the initializer-list (with corrected type) back, but that's not what we
-    // want, since it will be treated as an initializer list in further
-    // processing. Explicitly insert a cast here.
+  if (!isa<CXXTemporaryObjectExpr>(Inner)) {
+    // If we created a CXXTemporaryObjectExpr, that node also represents the
+    // functional cast. Otherwise, create an explicit cast to represent
+    // the syntactic form of a functional-style cast that was used here.
+    //
+    // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
+    // would give a more consistent AST representation than using a
+    // CXXTemporaryObjectExpr. It's also weird that the functional cast
+    // is sometimes handled by initialization and sometimes not.
     QualType ResultType = Result.get()->getType();
     Result = CXXFunctionalCastExpr::Create(
         Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
         CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
   }
 
-  // FIXME: Improve AST representation?
   return Result;
 }
 
@@ -2031,7 +2054,7 @@
 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
                                            QualType Return,
                                            QualType Param1, QualType Param2,
-                                           bool AddMallocAttr) {
+                                           bool AddRestrictAttr) {
   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
   unsigned NumParams = Param2.isNull() ? 1 : 2;
 
@@ -2054,8 +2077,9 @@
         // FIXME: Do we need to check for default arguments here?
         if (InitialParam1Type == Param1 &&
             (NumParams == 1 || InitialParam2Type == Param2)) {
-          if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
-            Func->addAttr(MallocAttr::CreateImplicit(Context));
+          if (AddRestrictAttr && !Func->hasAttr<RestrictAttr>())
+            Func->addAttr(RestrictAttr::CreateImplicit(
+                Context, RestrictAttr::GNU_malloc));
           // Make the function visible to name lookup, even if we found it in
           // an unimported module. It either is an implicitly-declared global
           // allocation function, or is suppressing that function.
@@ -2065,7 +2089,7 @@
       }
     }
   }
-
+  
   FunctionProtoType::ExtProtoInfo EPI;
 
   QualType BadAllocType;
@@ -2093,9 +2117,24 @@
                          SourceLocation(), Name,
                          FnType, /*TInfo=*/nullptr, SC_None, false, true);
   Alloc->setImplicit();
+  
+  // Implicit sized deallocation functions always have default visibility.
+  Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
+                                                VisibilityAttr::Default));
 
-  if (AddMallocAttr)
-    Alloc->addAttr(MallocAttr::CreateImplicit(Context));
+  if (NumParams == 2 && !getLangOpts().DefineSizedDeallocation) {
+    assert(getLangOpts().SizedDeallocation &&
+           "Only sized deallocation can have two parameters");
+
+    // This declaration should be emited as extern_weak.
+    assert(Alloc->getLinkageAndVisibility().getLinkage() ==
+           clang::ExternalLinkage);
+    Alloc->addAttr(WeakAttr::CreateImplicit(Context));
+  }
+
+  if (AddRestrictAttr)
+    Alloc->addAttr(
+        RestrictAttr::CreateImplicit(Context, RestrictAttr::GNU_malloc));
 
   ParmVarDecl *ParamDecls[2];
   for (unsigned I = 0; I != NumParams; ++I) {
@@ -2553,6 +2592,8 @@
     S.CheckConstructorAccess(CastLoc, Constructor,
                              InitializedEntity::InitializeTemporary(Ty),
                              Constructor->getAccess());
+    if (S.DiagnoseUseOfDecl(Method, CastLoc))
+      return ExprError();
 
     ExprResult Result = S.BuildCXXConstructExpr(
         CastLoc, Ty, cast<CXXConstructorDecl>(Method),
@@ -2568,6 +2609,10 @@
   case CK_UserDefinedConversion: {
     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
 
+    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
+    if (S.DiagnoseUseOfDecl(Method, CastLoc))
+      return ExprError();
+
     // Create an implicit call expr that calls it.
     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
@@ -2579,8 +2624,6 @@
                                       CK_UserDefinedConversion, Result.get(),
                                       nullptr, Result.get()->getValueKind());
 
-    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
-
     return S.MaybeBindToTemporary(Result.get());
   }
   }
@@ -2611,7 +2654,7 @@
       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
       CastKind CastKind;
       QualType BeforeToType;
-      assert(FD && "FIXME: aggregate initialization from init list");
+      assert(FD && "no conversion function for user-defined conversion seq");
       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
         CastKind = CK_UserDefinedConversion;
 
@@ -2742,15 +2785,19 @@
   // Perform the first implicit conversion.
   switch (SCS.First) {
   case ICK_Identity:
-    // Nothing to do.
+    if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
+      FromType = FromAtomic->getValueType().getUnqualifiedType();
+      From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
+                                      From, /*BasePath=*/nullptr, VK_RValue);
+    }
     break;
 
   case ICK_Lvalue_To_Rvalue: {
     assert(From->getObjectKind() != OK_ObjCProperty);
-    FromType = FromType.getUnqualifiedType();
     ExprResult FromRes = DefaultLvalueConversion(From);
     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
     From = FromRes.get();
+    FromType = From->getType();
     break;
   }
 
@@ -2773,10 +2820,29 @@
   // Perform the second implicit conversion
   switch (SCS.Second) {
   case ICK_Identity:
-    // If both sides are functions (or pointers/references to them), there could
-    // be incompatible exception declarations.
-    if (CheckExceptionSpecCompatibility(From, ToType))
-      return ExprError();
+    // C++ [except.spec]p5:
+    //   [For] assignment to and initialization of pointers to functions,
+    //   pointers to member functions, and references to functions: the
+    //   target entity shall allow at least the exceptions allowed by the
+    //   source value in the assignment or initialization.
+    switch (Action) {
+    case AA_Assigning:
+    case AA_Initializing:
+      // Note, function argument passing and returning are initialization.
+    case AA_Passing:
+    case AA_Returning:
+    case AA_Sending:
+    case AA_Passing_CFAudited:
+      if (CheckExceptionSpecCompatibility(From, ToType))
+        return ExprError();
+      break;
+
+    case AA_Casting:
+    case AA_Converting:
+      // Casts and implicit conversions are not initialization, so are not
+      // checked for exception specification mismatches.
+      break;
+    }
     // Nothing else to do.
     break;
 
@@ -3489,8 +3555,8 @@
 
       bool FoundConstructor = false;
       unsigned FoundTQs;
-      DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
-      for (DeclContext::lookup_const_iterator Con = R.begin(),
+      DeclContext::lookup_result R = Self.LookupConstructors(RD);
+      for (DeclContext::lookup_iterator Con = R.begin(),
            ConEnd = R.end(); Con != ConEnd; ++Con) {
         // A template constructor is never a copy constructor.
         // FIXME: However, it may actually be selected at the actual overload
@@ -3529,8 +3595,8 @@
         return true;
 
       bool FoundConstructor = false;
-      DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
-      for (DeclContext::lookup_const_iterator Con = R.begin(),
+      DeclContext::lookup_result R = Self.LookupConstructors(RD);
+      for (DeclContext::lookup_iterator Con = R.begin(),
            ConEnd = R.end(); Con != ConEnd; ++Con) {
         // FIXME: In C++0x, a constructor template can be a default constructor.
         if (isa<FunctionTemplateDecl>(*Con))
@@ -5099,7 +5165,7 @@
     if (Call == TopCall)
       continue;
 
-    if (CheckCallReturnType(Call->getCallReturnType(),
+    if (CheckCallReturnType(Call->getCallReturnType(Context),
                             Call->getLocStart(),
                             Call, Call->getDirectCallee()))
       return ExprError();
@@ -5162,10 +5228,11 @@
   }
 }
 
-ExprResult
-Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
-                                   tok::TokenKind OpKind, ParsedType &ObjectType,
-                                   bool &MayBePseudoDestructor) {
+ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
+                                              SourceLocation OpLoc,
+                                              tok::TokenKind OpKind,
+                                              ParsedType &ObjectType,
+                                              bool &MayBePseudoDestructor) {
   // Since this might be a postfix expression, get rid of ParenListExprs.
   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
   if (Result.isInvalid()) return ExprError();
@@ -5299,20 +5366,6 @@
   return Base;
 }
 
-ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
-                                                   Expr *MemExpr) {
-  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
-  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
-    << isa<CXXPseudoDestructorExpr>(MemExpr)
-    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
-
-  return ActOnCallExpr(/*Scope*/ nullptr,
-                       MemExpr,
-                       /*LPLoc*/ ExpectedLParenLoc,
-                       None,
-                       /*RPLoc*/ ExpectedLParenLoc);
-}
-
 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 
                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
   if (Base->hasPlaceholderType()) {
@@ -5353,8 +5406,7 @@
                                            TypeSourceInfo *ScopeTypeInfo,
                                            SourceLocation CCLoc,
                                            SourceLocation TildeLoc,
-                                         PseudoDestructorTypeStorage Destructed,
-                                           bool HasTrailingLParen) {
+                                         PseudoDestructorTypeStorage Destructed) {
   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
 
   QualType ObjectType;
@@ -5442,10 +5494,7 @@
                                             TildeLoc,
                                             Destructed);
 
-  if (HasTrailingLParen)
-    return Result;
-
-  return DiagnoseDtorReference(Destructed.getLocation(), Result);
+  return Result;
 }
 
 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
@@ -5455,8 +5504,7 @@
                                            UnqualifiedId &FirstTypeName,
                                            SourceLocation CCLoc,
                                            SourceLocation TildeLoc,
-                                           UnqualifiedId &SecondTypeName,
-                                           bool HasTrailingLParen) {
+                                           UnqualifiedId &SecondTypeName) {
   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
          "Invalid first type name in pseudo-destructor");
@@ -5583,20 +5631,20 @@
 
   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
                                    ScopeTypeInfo, CCLoc, TildeLoc,
-                                   Destructed, HasTrailingLParen);
+                                   Destructed);
 }
 
 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
                                            SourceLocation OpLoc,
                                            tok::TokenKind OpKind,
                                            SourceLocation TildeLoc, 
-                                           const DeclSpec& DS,
-                                           bool HasTrailingLParen) {
+                                           const DeclSpec& DS) {
   QualType ObjectType;
   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
     return ExprError();
 
-  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
+  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
+                                 false);
 
   TypeLocBuilder TLB;
   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
@@ -5606,7 +5654,7 @@
 
   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
                                    nullptr, SourceLocation(), TildeLoc,
-                                   Destructed, HasTrailingLParen);
+                                   Destructed);
 }
 
 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
@@ -5664,6 +5712,13 @@
 
 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
                                       SourceLocation RParen) {
+  if (ActiveTemplateInstantiations.empty() &&
+      Operand->HasSideEffects(Context, false)) {
+    // The expression operand for noexcept is in an unevaluated expression
+    // context, so side effects could result in unintended consequences.
+    Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
+  }
+
   CanThrowResult CanThrow = canThrow(Operand);
   return new (Context)
       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
@@ -5935,15 +5990,18 @@
     NewSS = *SS;
 
   if (auto *ND = TC.getCorrectionDecl()) {
+    R.setLookupName(ND->getDeclName());
     R.addDecl(ND);
     if (ND->isCXXClassMember()) {
-      // Figure out the correct naming class to ad to the LookupResult.
+      // Figure out the correct naming class to add to the LookupResult.
       CXXRecordDecl *Record = nullptr;
       if (auto *NNS = TC.getCorrectionSpecifier())
         Record = NNS->getAsType()->getAsCXXRecordDecl();
       if (!Record)
-        Record = cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
-      R.setNamingClass(Record);
+        Record =
+            dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
+      if (Record)
+        R.setNamingClass(Record);
 
       // Detect and handle the case where the decl might be an implicit
       // member.
@@ -5992,7 +6050,7 @@
   typedef TreeTransform<TransformTypos> BaseTransform;
 
   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
-  llvm::SmallSetVector<TypoExpr *, 2> TypoExprs;
+  llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
 
@@ -6055,10 +6113,19 @@
       return ME->getMemberDecl();
     // FIXME: Add any other expr types that could be be seen by the delayed typo
     // correction TreeTransform for which the corresponding TypoCorrection could
-    // contain multple decls.
+    // contain multiple decls.
     return nullptr;
   }
 
+  ExprResult TryTransform(Expr *E) {
+    Sema::SFINAETrap Trap(SemaRef);
+    ExprResult Res = TransformExpr(E);
+    if (Trap.hasErrorOccurred() || Res.isInvalid())
+      return ExprError();
+
+    return ExprFilter(Res.get());
+  }
+
 public:
   TransformTypos(Sema &SemaRef, llvm::function_ref<ExprResult(Expr *)> Filter)
       : BaseTransform(SemaRef), ExprFilter(Filter) {}
@@ -6070,8 +6137,13 @@
     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
                                                  RParenLoc, ExecConfig);
     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
-      if (!Result.isInvalid() && Result.get())
-        OverloadResolution[OE] = cast<CallExpr>(Result.get())->getCallee();
+      if (Result.isUsable()) {
+        Expr *ResultCall = Result.get();
+        if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
+          ResultCall = BE->getSubExpr();
+        if (auto *CE = dyn_cast<CallExpr>(ResultCall))
+          OverloadResolution[OE] = CE->getCallee();
+      }
     }
     return Result;
   }
@@ -6079,30 +6151,45 @@
   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
 
   ExprResult Transform(Expr *E) {
-    ExprResult res;
-    bool error = false;
+    ExprResult Res;
     while (true) {
-      Sema::SFINAETrap Trap(SemaRef);
-      res = TransformExpr(E);
-      error = Trap.hasErrorOccurred();
-
-      if (!(error || res.isInvalid()))
-        res = ExprFilter(res.get());
+      Res = TryTransform(E);
 
       // Exit if either the transform was valid or if there were no TypoExprs
       // to transform that still have any untried correction candidates..
-      if (!(error || res.isInvalid()) ||
+      if (!Res.isInvalid() ||
           !CheckAndAdvanceTypoExprCorrectionStreams())
         break;
     }
 
+    // Ensure none of the TypoExprs have multiple typo correction candidates
+    // with the same edit length that pass all the checks and filters.
+    // TODO: Properly handle various permutations of possible corrections when
+    // there is more than one potentially ambiguous typo correction.
+    while (!AmbiguousTypoExprs.empty()) {
+      auto TE  = AmbiguousTypoExprs.back();
+      auto Cached = TransformCache[TE];
+      auto &State = SemaRef.getTypoExprState(TE);
+      State.Consumer->saveCurrentPosition();
+      TransformCache.erase(TE);
+      if (!TryTransform(E).isInvalid()) {
+        State.Consumer->resetCorrectionStream();
+        TransformCache.erase(TE);
+        Res = ExprError();
+        break;
+      }
+      AmbiguousTypoExprs.remove(TE);
+      State.Consumer->restoreSavedPosition();
+      TransformCache[TE] = Cached;
+    }
+
     // Ensure that all of the TypoExprs within the current Expr have been found.
-    if (!res.isUsable())
+    if (!Res.isUsable())
       FindTypoExprs(TypoExprs).TraverseStmt(E);
 
     EmitAllDiagnostics();
 
-    return res;
+    return Res;
   }
 
   ExprResult TransformTypoExpr(TypoExpr *E) {
@@ -6124,21 +6211,15 @@
           State.RecoveryHandler(SemaRef, E, TC) :
           attemptRecovery(SemaRef, *State.Consumer, TC);
       if (!NE.isInvalid()) {
-        // Check whether there is a second viable correction with the same edit
-        // distance--in which case do not suggest anything since both are
-        // equally good candidates for correcting the typo.
-        Sema::SFINAETrap LocalTrap(SemaRef);
+        // Check whether there may be a second viable correction with the same
+        // edit distance; if so, remember this TypoExpr may have an ambiguous
+        // correction so it can be more thoroughly vetted later.
         TypoCorrection Next;
-        while ((Next = State.Consumer->peekNextCorrection()) &&
-               Next.getEditDistance(false) == TC.getEditDistance(false)) {
-          ExprResult Res =
-              State.RecoveryHandler
-                  ? State.RecoveryHandler(SemaRef, E, Next)
-                  : attemptRecovery(SemaRef, *State.Consumer, Next);
-          if (!Res.isInvalid()) {
-            NE = ExprError();
-            State.Consumer->getNextCorrection();
-          }
+        if ((Next = State.Consumer->peekNextCorrection()) &&
+            Next.getEditDistance(false) == TC.getEditDistance(false)) {
+          AmbiguousTypoExprs.insert(E);
+        } else {
+          AmbiguousTypoExprs.remove(E);
         }
         assert(!NE.isUnset() &&
                "Typo was transformed into a valid-but-null ExprResult");
@@ -6155,16 +6236,21 @@
   // If the current evaluation context indicates there are uncorrected typos
   // and the current expression isn't guaranteed to not have typos, try to
   // resolve any TypoExpr nodes that might be in the expression.
-  if (!ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
+  if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
       (E->isTypeDependent() || E->isValueDependent() ||
        E->isInstantiationDependent())) {
+    auto TyposInContext = ExprEvalContexts.back().NumTypos;
+    assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
+    ExprEvalContexts.back().NumTypos = ~0U;
     auto TyposResolved = DelayedTypos.size();
     auto Result = TransformTypos(*this, Filter).Transform(E);
+    ExprEvalContexts.back().NumTypos = TyposInContext;
     TyposResolved -= DelayedTypos.size();
-    if (TyposResolved) {
+    if (Result.isInvalid() || Result.get() != E) {
       ExprEvalContexts.back().NumTypos -= TyposResolved;
       return Result;
     }
+    assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
   }
   return E;
 }
diff --git a/lib/Sema/SemaExprMember.cpp b/lib/Sema/SemaExprMember.cpp
index 3a57da7..b27bd39 100644
--- a/lib/Sema/SemaExprMember.cpp
+++ b/lib/Sema/SemaExprMember.cpp
@@ -11,7 +11,6 @@
 //
 //===----------------------------------------------------------------------===//
 #include "clang/Sema/Overload.h"
-#include "clang/Sema/SemaInternal.h"
 #include "clang/AST/ASTLambda.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
@@ -22,6 +21,7 @@
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
+#include "clang/Sema/SemaInternal.h"
 
 using namespace clang;
 using namespace sema;
@@ -90,7 +90,6 @@
 /// conservatively answer "yes", in which case some errors will simply
 /// not be caught until template-instantiation.
 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
-                                            Scope *CurScope,
                                             const LookupResult &R) {
   assert(!R.empty() && (*R.begin())->isCXXClassMember());
 
@@ -205,6 +204,9 @@
   SourceRange Range(Loc);
   if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
 
+  // Look through using shadow decls and aliases.
+  Rep = Rep->getUnderlyingDecl();
+
   DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
   CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
@@ -237,7 +239,7 @@
                                       SourceLocation TemplateKWLoc,
                                       LookupResult &R,
                                 const TemplateArgumentListInfo *TemplateArgs) {
-  switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
+  switch (ClassifyImplicitMemberAccess(*this, R)) {
   case IMA_Instance:
     return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
 
@@ -642,7 +644,7 @@
   }
 
   // The record definition is complete, now look up the member.
-  SemaRef.LookupQualifiedName(R, DC);
+  SemaRef.LookupQualifiedName(R, DC, SS);
 
   if (!R.empty())
     return false;
@@ -984,8 +986,7 @@
           CXXScopeSpec TempSS(SS);
           RetryExpr = ActOnMemberAccessExpr(
               ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
-              TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
-              ExtraArgs->HasTrailingLParen);
+              TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
         }
         if (Trap.hasErrorOccurred())
           RetryExpr = ExprError();
@@ -1606,9 +1607,6 @@
 /// possibilities, including destructor and operator references.
 ///
 /// \param OpKind either tok::arrow or tok::period
-/// \param HasTrailingLParen whether the next token is '(', which
-///   is used to diagnose mis-uses of special members that can
-///   only be called
 /// \param ObjCImpDecl the current Objective-C \@implementation
 ///   decl; this is an ugly hack around the fact that Objective-C
 ///   \@implementations aren't properly put in the context chain
@@ -1618,24 +1616,10 @@
                                        CXXScopeSpec &SS,
                                        SourceLocation TemplateKWLoc,
                                        UnqualifiedId &Id,
-                                       Decl *ObjCImpDecl,
-                                       bool HasTrailingLParen) {
+                                       Decl *ObjCImpDecl) {
   if (SS.isSet() && SS.isInvalid())
     return ExprError();
 
-  // The only way a reference to a destructor can be used is to
-  // immediately call it. If the next token is not a '(', produce
-  // a diagnostic and build the call now.
-  if (!HasTrailingLParen &&
-      Id.getKind() == UnqualifiedId::IK_DestructorName) {
-    ExprResult DtorAccess =
-        ActOnMemberAccessExpr(S, Base, OpLoc, OpKind, SS, TemplateKWLoc, Id,
-                              ObjCImpDecl, /*HasTrailingLParen*/true);
-    if (DtorAccess.isInvalid())
-      return DtorAccess;
-    return DiagnoseDtorReference(Id.getLocStart(), DtorAccess.get());
-  }
-
   // Warn about the explicit constructor calls Microsoft extension.
   if (getLangOpts().MicrosoftExt &&
       Id.getKind() == UnqualifiedId::IK_ConstructorName)
@@ -1668,8 +1652,7 @@
                                     NameInfo, TemplateArgs);
   }
 
-  ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl,
-                                          HasTrailingLParen};
+  ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
   return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
                                   TemplateKWLoc, FirstQualifierInScope,
                                   NameInfo, TemplateArgs, &ExtraArgs);
diff --git a/lib/Sema/SemaExprObjC.cpp b/lib/Sema/SemaExprObjC.cpp
index eeee352..ebe6cbb 100644
--- a/lib/Sema/SemaExprObjC.cpp
+++ b/lib/Sema/SemaExprObjC.cpp
@@ -218,7 +218,9 @@
       S.Diag(Loc, diag::err_undeclared_nsnumber);
       return nullptr;
     }
-    
+  }
+
+  if (S.NSNumberPointer.isNull()) {
     // generate the pointer to NSNumber type.
     QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
     S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
@@ -987,7 +989,7 @@
   ObjCMethodList *M = &MethList;
   bool Warned = false;
   for (M = M->getNext(); M; M=M->getNext()) {
-    ObjCMethodDecl *MatchingMethodDecl = M->Method;
+    ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
     if (MatchingMethodDecl == Method ||
         isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
         MatchingMethodDecl->getSelector() != Method->getSelector())
@@ -1751,29 +1753,30 @@
       IsSuper = true;
 
       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
-        if (CurMethod->isInstanceMethod()) {
-          ObjCInterfaceDecl *Super =
-            CurMethod->getClassInterface()->getSuperClass();
-          if (!Super) {
-            // The current class does not have a superclass.
-            Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
-            << CurMethod->getClassInterface()->getIdentifier();
-            return ExprError();
+        if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
+          if (CurMethod->isInstanceMethod()) {
+            ObjCInterfaceDecl *Super = Class->getSuperClass();
+            if (!Super) {
+              // The current class does not have a superclass.
+              Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
+              << Class->getIdentifier();
+              return ExprError();
+            }
+            QualType T = Context.getObjCInterfaceType(Super);
+            T = Context.getObjCObjectPointerType(T);
+
+            return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
+                                             /*BaseExpr*/nullptr,
+                                             SourceLocation()/*OpLoc*/,
+                                             &propertyName,
+                                             propertyNameLoc,
+                                             receiverNameLoc, T, true);
           }
-          QualType T = Context.getObjCInterfaceType(Super);
-          T = Context.getObjCObjectPointerType(T);
 
-          return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
-                                           /*BaseExpr*/nullptr,
-                                           SourceLocation()/*OpLoc*/, 
-                                           &propertyName,
-                                           propertyNameLoc,
-                                           receiverNameLoc, T, true);
+          // Otherwise, if this is a class method, try dispatching to our
+          // superclass.
+          IFace = Class->getSuperClass();
         }
-
-        // Otherwise, if this is a class method, try dispatching to our
-        // superclass.
-        IFace = CurMethod->getClassInterface()->getSuperClass();
       }
     }
 
@@ -2458,8 +2461,9 @@
     } else if (ReceiverType->isObjCClassType() ||
                ReceiverType->isObjCQualifiedClassType()) {
       // Handle messages to Class.
-      // We allow sending a message to a qualified Class ("Class<foo>"), which 
-      // is ok as long as one of the protocols implements the selector (if not, warn).
+      // We allow sending a message to a qualified Class ("Class<foo>"), which
+      // is ok as long as one of the protocols implements the selector (if not,
+      // warn).
       if (const ObjCObjectPointerType *QClassTy 
             = ReceiverType->getAsObjCQualifiedClassType()) {
         // Search protocols for class methods.
@@ -3027,17 +3031,20 @@
 
     /// Some declaration references are okay.
     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
-      // References to global constants from system headers are okay.
-      // These are things like 'kCFStringTransformToLatin'.  They are
-      // can also be assumed to be immune to retains.
       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
+      // References to global constants are okay.
       if (isAnyRetainable(TargetClass) &&
           isAnyRetainable(SourceClass) &&
           var &&
           var->getStorageClass() == SC_Extern &&
-          var->getType().isConstQualified() &&
-          Context.getSourceManager().isInSystemHeader(var->getLocation())) {
-        return ACC_bottom;
+          var->getType().isConstQualified()) {
+
+        // In system headers, they can also be assumed to be immune to retains.
+        // These are things like 'kCFStringTransformToLatin'.
+        if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
+          return ACC_bottom;
+
+        return ACC_plusZero;
       }
 
       // Nothing else.
@@ -3404,6 +3411,9 @@
     if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
       if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
         HadTheAttribute = true;
+        if (Parm->isStr("id"))
+          return true;
+        
         NamedDecl *Target = nullptr;
         // Check for an existing type with this name.
         LookupResult R(S, DeclarationName(Parm), SourceLocation(),
diff --git a/lib/Sema/SemaInit.cpp b/lib/Sema/SemaInit.cpp
index b57e029..4a6531e 100644
--- a/lib/Sema/SemaInit.cpp
+++ b/lib/Sema/SemaInit.cpp
@@ -149,9 +149,9 @@
 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
                             Sema &S) {
   // Get the length of the string as parsed.
-  uint64_t StrLength =
-    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
-
+  auto *ConstantArrayTy =
+      cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
+  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
 
   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
     // C99 6.7.8p14. We have an array of character type with unknown size
@@ -640,6 +640,9 @@
                                  InitListExpr *IL, QualType &T,
                                  bool VerifyOnly)
   : SemaRef(S), VerifyOnly(VerifyOnly) {
+  // FIXME: Check that IL isn't already the semantic form of some other
+  // InitListExpr. If it is, we'd create a broken AST.
+
   hadError = false;
 
   FullyStructuredList =
@@ -751,6 +754,68 @@
   }
 }
 
+/// Warn that \p Entity was of scalar type and was initialized by a
+/// single-element braced initializer list.
+static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
+                                 SourceRange Braces) {
+  // Don't warn during template instantiation. If the initialization was
+  // non-dependent, we warned during the initial parse; otherwise, the
+  // type might not be scalar in some uses of the template.
+  if (!S.ActiveTemplateInstantiations.empty())
+    return;
+
+  unsigned DiagID = 0;
+
+  switch (Entity.getKind()) {
+  case InitializedEntity::EK_VectorElement:
+  case InitializedEntity::EK_ComplexElement:
+  case InitializedEntity::EK_ArrayElement:
+  case InitializedEntity::EK_Parameter:
+  case InitializedEntity::EK_Parameter_CF_Audited:
+  case InitializedEntity::EK_Result:
+    // Extra braces here are suspicious.
+    DiagID = diag::warn_braces_around_scalar_init;
+    break;
+
+  case InitializedEntity::EK_Member:
+    // Warn on aggregate initialization but not on ctor init list or
+    // default member initializer.
+    if (Entity.getParent())
+      DiagID = diag::warn_braces_around_scalar_init;
+    break;
+
+  case InitializedEntity::EK_Variable:
+  case InitializedEntity::EK_LambdaCapture:
+    // No warning, might be direct-list-initialization.
+    // FIXME: Should we warn for copy-list-initialization in these cases?
+    break;
+
+  case InitializedEntity::EK_New:
+  case InitializedEntity::EK_Temporary:
+  case InitializedEntity::EK_CompoundLiteralInit:
+    // No warning, braces are part of the syntax of the underlying construct.
+    break;
+
+  case InitializedEntity::EK_RelatedResult:
+    // No warning, we already warned when initializing the result.
+    break;
+
+  case InitializedEntity::EK_Exception:
+  case InitializedEntity::EK_Base:
+  case InitializedEntity::EK_Delegating:
+  case InitializedEntity::EK_BlockElement:
+    llvm_unreachable("unexpected braced scalar init");
+  }
+
+  if (DiagID) {
+    S.Diag(Braces.getBegin(), DiagID)
+      << Braces
+      << FixItHint::CreateRemoval(Braces.getBegin())
+      << FixItHint::CreateRemoval(Braces.getEnd());
+  }
+}
+
+
 /// Check whether the initializer \p IList (that was written with explicit
 /// braces) can be used to initialize an object of type \p T.
 ///
@@ -826,12 +891,9 @@
     }
   }
 
-  if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
-      !TopLevelObject)
-    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
-      << IList->getSourceRange()
-      << FixItHint::CreateRemoval(IList->getLocStart())
-      << FixItHint::CreateRemoval(IList->getLocEnd());
+  if (!VerifyOnly && T->isScalarType() &&
+      IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
+    warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
 }
 
 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
@@ -904,7 +966,7 @@
                               StructuredList, StructuredIndex);
 
   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
-    if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
+    if (!SemaRef.getLangOpts().CPlusPlus) {
       InitListExpr *InnerStructuredList
         = getStructuredSubobjectInit(IList, Index, ElemType,
                                      StructuredList, StructuredIndex,
@@ -915,8 +977,6 @@
       ++Index;
       return;
     }
-    assert(SemaRef.getLangOpts().CPlusPlus &&
-           "non-aggregate records are only possible in C++");
     // C++ initialization is handled later.
   } else if (isa<ImplicitValueInitExpr>(expr)) {
     // This happens during template instantiation when we see an InitListExpr
@@ -929,15 +989,45 @@
     return;
   }
 
-  // FIXME: Need to handle atomic aggregate types with implicit init lists.
-  if (ElemType->isScalarType() || ElemType->isAtomicType())
+  if (SemaRef.getLangOpts().CPlusPlus) {
+    // C++ [dcl.init.aggr]p2:
+    //   Each member is copy-initialized from the corresponding
+    //   initializer-clause.
+
+    // FIXME: Better EqualLoc?
+    InitializationKind Kind =
+      InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
+    InitializationSequence Seq(SemaRef, Entity, Kind, expr,
+                               /*TopLevelOfInitList*/ true);
+
+    // C++14 [dcl.init.aggr]p13:
+    //   If the assignment-expression can initialize a member, the member is
+    //   initialized. Otherwise [...] brace elision is assumed
+    //
+    // Brace elision is never performed if the element is not an
+    // assignment-expression.
+    if (Seq || isa<InitListExpr>(expr)) {
+      if (!VerifyOnly) {
+        ExprResult Result =
+          Seq.Perform(SemaRef, Entity, Kind, expr);
+        if (Result.isInvalid())
+          hadError = true;
+
+        UpdateStructuredListElement(StructuredList, StructuredIndex,
+                                    Result.getAs<Expr>());
+      } else if (!Seq)
+        hadError = true;
+      ++Index;
+      return;
+    }
+
+    // Fall through for subaggregate initialization
+  } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
+    // FIXME: Need to handle atomic aggregate types with implicit init lists.
     return CheckScalarType(Entity, IList, ElemType, Index,
                            StructuredList, StructuredIndex);
-
-  assert((ElemType->isRecordType() || ElemType->isVectorType() ||
-          ElemType->isArrayType()) && "Unexpected type");
-
-  if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
+  } else if (const ArrayType *arrayType =
+                 SemaRef.Context.getAsArrayType(ElemType)) {
     // arrayType can be incomplete if we're initializing a flexible
     // array member.  There's nothing we can do with the completed
     // type here, though.
@@ -953,34 +1043,10 @@
 
     // Fall through for subaggregate initialization.
 
-  } else if (SemaRef.getLangOpts().CPlusPlus) {
-    // C++ [dcl.init.aggr]p12:
-    //   All implicit type conversions (clause 4) are considered when
-    //   initializing the aggregate member with an initializer from
-    //   an initializer-list. If the initializer can initialize a
-    //   member, the member is initialized. [...]
-
-    // FIXME: Better EqualLoc?
-    InitializationKind Kind =
-      InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
-    InitializationSequence Seq(SemaRef, Entity, Kind, expr);
-
-    if (Seq) {
-      if (!VerifyOnly) {
-        ExprResult Result =
-          Seq.Perform(SemaRef, Entity, Kind, expr);
-        if (Result.isInvalid())
-          hadError = true;
-
-        UpdateStructuredListElement(StructuredList, StructuredIndex,
-                                    Result.getAs<Expr>());
-      }
-      ++Index;
-      return;
-    }
-
-    // Fall through for subaggregate initialization
   } else {
+    assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
+           "Unexpected type");
+
     // C99 6.7.8p13:
     //
     //   The initializer for a structure or union object that has
@@ -990,10 +1056,8 @@
     //   initial value of the object, including unnamed members, is
     //   that of the expression.
     ExprResult ExprRes = expr;
-    if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
-        SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
-                                                 !VerifyOnly)
-          != Sema::Incompatible) {
+    if (SemaRef.CheckSingleAssignmentConstraints(
+            ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
       if (ExprRes.isInvalid())
         hadError = true;
       else {
@@ -3107,15 +3171,13 @@
 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
                            MultiExprArg Args,
                            OverloadCandidateSet &CandidateSet,
-                           ArrayRef<NamedDecl *> Ctors,
+                           DeclContext::lookup_result Ctors,
                            OverloadCandidateSet::iterator &Best,
                            bool CopyInitializing, bool AllowExplicit,
-                           bool OnlyListConstructors, bool InitListSyntax) {
+                           bool OnlyListConstructors, bool IsListInit) {
   CandidateSet.clear();
 
-  for (ArrayRef<NamedDecl *>::iterator
-         Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
-    NamedDecl *D = *Con;
+  for (NamedDecl *D : Ctors) {
     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
     bool SuppressUserConversions = false;
 
@@ -3129,19 +3191,21 @@
       Constructor = cast<CXXConstructorDecl>(D);
 
       // C++11 [over.best.ics]p4:
-      //   However, when considering the argument of a constructor or
-      //   user-defined conversion function that is a candidate:
-      //    -- by 13.3.1.3 when invoked for the copying/moving of a temporary
-      //       in the second step of a class copy-initialization,
-      //    -- by 13.3.1.7 when passing the initializer list as a single
-      //       argument or when the initializer list has exactly one elementand
-      //       a conversion to some class X or reference to (possibly
-      //       cv-qualified) X is considered for the first parameter of a
-      //       constructor of X, or
-      //    -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
-      //   only standard conversion sequences and ellipsis conversion sequences
-      //   are considered.
-      if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
+      //   ... and the constructor or user-defined conversion function is a
+      //   candidate by
+      //   - 13.3.1.3, when the argument is the temporary in the second step
+      //     of a class copy-initialization, or
+      //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
+      //   user-defined conversion sequences are not considered.
+      // FIXME: This breaks backward compatibility, e.g. PR12117. As a
+      //        temporary fix, let's re-instate the third bullet above until
+      //        there is a resolution in the standard, i.e.,
+      //   - 13.3.1.7 when the initializer list has exactly one element that is
+      //     itself an initializer list and a conversion to some class X or
+      //     reference to (possibly cv-qualified) X is considered for the first
+      //     parameter of a constructor of X.
+      if ((CopyInitializing ||
+           (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
           Constructor->isCopyOrMoveConstructor())
         SuppressUserConversions = true;
     }
@@ -3178,16 +3242,19 @@
 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
 /// enumerates the constructors of the initialized entity and performs overload
 /// resolution to select the best.
-/// If InitListSyntax is true, this is list-initialization of a non-aggregate
-/// class type.
+/// \param IsListInit     Is this list-initialization?
+/// \param IsInitListCopy Is this non-list-initialization resulting from a
+///                       list-initialization from {x} where x is the same
+///                       type as the entity?
 static void TryConstructorInitialization(Sema &S,
                                          const InitializedEntity &Entity,
                                          const InitializationKind &Kind,
                                          MultiExprArg Args, QualType DestType,
                                          InitializationSequence &Sequence,
-                                         bool InitListSyntax = false) {
-  assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
-         "InitListSyntax must come with a single initializer list argument.");
+                                         bool IsListInit = false,
+                                         bool IsInitListCopy = false) {
+  assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
+         "IsListInit must come with a single initializer list argument.");
 
   // The type we're constructing needs to be complete.
   if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
@@ -3206,29 +3273,28 @@
 
   // Determine whether we are allowed to call explicit constructors or
   // explicit conversion operators.
-  bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
+  bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
 
   //   - Otherwise, if T is a class type, constructors are considered. The
   //     applicable constructors are enumerated, and the best one is chosen
   //     through overload resolution.
-  DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
-  // The container holding the constructors can under certain conditions
-  // be changed while iterating (e.g. because of deserialization).
-  // To be safe we copy the lookup results to a new container.
-  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
+  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
 
   OverloadingResult Result = OR_No_Viable_Function;
   OverloadCandidateSet::iterator Best;
   bool AsInitializerList = false;
 
-  // C++11 [over.match.list]p1:
-  //   When objects of non-aggregate type T are list-initialized, overload
-  //   resolution selects the constructor in two phases:
+  // C++11 [over.match.list]p1, per DR1467:
+  //   When objects of non-aggregate type T are list-initialized, such that
+  //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
+  //   according to the rules in this section, overload resolution selects
+  //   the constructor in two phases:
+  //
   //   - Initially, the candidate functions are the initializer-list
   //     constructors of the class T and the argument list consists of the
   //     initializer list as a single argument.
-  if (InitListSyntax) {
+  if (IsListInit) {
     InitListExpr *ILE = cast<InitListExpr>(Args[0]);
     AsInitializerList = true;
 
@@ -3239,7 +3305,7 @@
                                           CandidateSet, Ctors, Best,
                                           CopyInitialization, AllowExplicit,
                                           /*OnlyListConstructor=*/true,
-                                          InitListSyntax);
+                                          IsListInit);
 
     // Time to unwrap the init list.
     Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
@@ -3256,10 +3322,10 @@
                                         CandidateSet, Ctors, Best,
                                         CopyInitialization, AllowExplicit,
                                         /*OnlyListConstructors=*/false,
-                                        InitListSyntax);
+                                        IsListInit);
   }
   if (Result) {
-    Sequence.SetOverloadFailure(InitListSyntax ?
+    Sequence.SetOverloadFailure(IsListInit ?
                       InitializationSequence::FK_ListConstructorOverloadFailed :
                       InitializationSequence::FK_ConstructorOverloadFailed,
                                 Result);
@@ -3281,7 +3347,7 @@
   //   In copy-list-initialization, if an explicit constructor is chosen, the
   //   initializer is ill-formed.
   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
-  if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
+  if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
     Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
     return;
   }
@@ -3289,10 +3355,9 @@
   // Add the constructor initialization step. Any cv-qualification conversion is
   // subsumed by the initialization.
   bool HadMultipleCandidates = (CandidateSet.size() > 1);
-  Sequence.AddConstructorInitializationStep(CtorDecl,
-                                            Best->FoundDecl.getAccess(),
-                                            DestType, HadMultipleCandidates,
-                                            InitListSyntax, AsInitializerList);
+  Sequence.AddConstructorInitializationStep(
+      CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
+      IsListInit | IsInitListCopy, AsInitializerList);
 }
 
 static bool
@@ -3425,48 +3490,97 @@
     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
     return;
   }
-  if (DestType->isRecordType()) {
-    if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
-      Sequence.setIncompleteTypeFailure(DestType);
-      return;
+
+  if (DestType->isRecordType() &&
+      S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
+    Sequence.setIncompleteTypeFailure(DestType);
+    return;
+  }
+
+  // C++11 [dcl.init.list]p3, per DR1467:
+  // - If T is a class type and the initializer list has a single element of
+  //   type cv U, where U is T or a class derived from T, the object is
+  //   initialized from that element (by copy-initialization for
+  //   copy-list-initialization, or by direct-initialization for
+  //   direct-list-initialization).
+  // - Otherwise, if T is a character array and the initializer list has a
+  //   single element that is an appropriately-typed string literal
+  //   (8.5.2 [dcl.init.string]), initialization is performed as described
+  //   in that section.
+  // - Otherwise, if T is an aggregate, [...] (continue below).
+  if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
+    if (DestType->isRecordType()) {
+      QualType InitType = InitList->getInit(0)->getType();
+      if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
+          S.IsDerivedFrom(InitType, DestType)) {
+        Expr *InitAsExpr = InitList->getInit(0);
+        TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
+                                     Sequence, /*InitListSyntax*/ false,
+                                     /*IsInitListCopy*/ true);
+        return;
+      }
     }
+    if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
+      Expr *SubInit[1] = {InitList->getInit(0)};
+      if (!isa<VariableArrayType>(DestAT) &&
+          IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
+        InitializationKind SubKind =
+            Kind.getKind() == InitializationKind::IK_DirectList
+                ? InitializationKind::CreateDirect(Kind.getLocation(),
+                                                   InitList->getLBraceLoc(),
+                                                   InitList->getRBraceLoc())
+                : Kind;
+        Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
+                                /*TopLevelOfInitList*/ true);
 
-    // C++11 [dcl.init.list]p3:
-    //   - If T is an aggregate, aggregate initialization is performed.
-    if (!DestType->isAggregateType()) {
-      if (S.getLangOpts().CPlusPlus11) {
-        //   - Otherwise, if the initializer list has no elements and T is a
-        //     class type with a default constructor, the object is
-        //     value-initialized.
-        if (InitList->getNumInits() == 0) {
-          CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
-          if (RD->hasDefaultConstructor()) {
-            TryValueInitialization(S, Entity, Kind, Sequence, InitList);
-            return;
-          }
-        }
-
-        //   - Otherwise, if T is a specialization of std::initializer_list<E>,
-        //     an initializer_list object constructed [...]
-        if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
+        // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
+        // the element is not an appropriately-typed string literal, in which
+        // case we should proceed as in C++11 (below).
+        if (Sequence) {
+          Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
           return;
-
-        //   - Otherwise, if T is a class type, constructors are considered.
-        Expr *InitListAsExpr = InitList;
-        TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
-                                     Sequence, /*InitListSyntax*/true);
-      } else
-        Sequence.SetFailed(
-            InitializationSequence::FK_InitListBadDestinationType);
-      return;
+        }
+      }
     }
   }
+
+  // C++11 [dcl.init.list]p3:
+  //   - If T is an aggregate, aggregate initialization is performed.
+  if (DestType->isRecordType() && !DestType->isAggregateType()) {
+    if (S.getLangOpts().CPlusPlus11) {
+      //   - Otherwise, if the initializer list has no elements and T is a
+      //     class type with a default constructor, the object is
+      //     value-initialized.
+      if (InitList->getNumInits() == 0) {
+        CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
+        if (RD->hasDefaultConstructor()) {
+          TryValueInitialization(S, Entity, Kind, Sequence, InitList);
+          return;
+        }
+      }
+
+      //   - Otherwise, if T is a specialization of std::initializer_list<E>,
+      //     an initializer_list object constructed [...]
+      if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
+        return;
+
+      //   - Otherwise, if T is a class type, constructors are considered.
+      Expr *InitListAsExpr = InitList;
+      TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
+                                   Sequence, /*InitListSyntax*/ true);
+    } else
+      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
+    return;
+  }
+
   if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
       InitList->getNumInits() == 1 &&
       InitList->getInit(0)->getType()->isRecordType()) {
     //   - Otherwise, if the initializer list has a single element of type E
     //     [...references are handled above...], the object or reference is
-    //     initialized from that element; if a narrowing conversion is required
+    //     initialized from that element (by copy-initialization for
+    //     copy-list-initialization, or by direct-initialization for
+    //     direct-list-initialization); if a narrowing conversion is required
     //     to convert the element to T, the program is ill-formed.
     //
     // Per core-24034, this is direct-initialization if we were performing
@@ -3543,14 +3657,7 @@
     // to see if there is a suitable conversion.
     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
 
-    DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
-    // The container holding the constructors can under certain conditions
-    // be changed while iterating (e.g. because of deserialization).
-    // To be safe we copy the lookup results to a new container.
-    SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
-    for (SmallVectorImpl<NamedDecl *>::iterator
-           CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
-      NamedDecl *D = *CI;
+    for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
       DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
 
       // Find the constructor (which may be a template).
@@ -3586,11 +3693,8 @@
     // functions.
     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
 
-    std::pair<CXXRecordDecl::conversion_iterator,
-              CXXRecordDecl::conversion_iterator>
-      Conversions = T2RecordDecl->getVisibleConversionFunctions();
-    for (CXXRecordDecl::conversion_iterator
-           I = Conversions.first, E = Conversions.second; I != E; ++I) {
+    const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
+    for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
       NamedDecl *D = *I;
       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
       if (isa<UsingShadowDecl>(D))
@@ -4218,11 +4322,9 @@
       CXXRecordDecl *SourceRecordDecl
         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
 
-      std::pair<CXXRecordDecl::conversion_iterator,
-                CXXRecordDecl::conversion_iterator>
-        Conversions = SourceRecordDecl->getVisibleConversionFunctions();
-      for (CXXRecordDecl::conversion_iterator
-             I = Conversions.first, E = Conversions.second; I != E; ++I) {
+      const auto &Conversions =
+          SourceRecordDecl->getVisibleConversionFunctions();
+      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
         NamedDecl *D = *I;
         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
         if (isa<UsingShadowDecl>(D))
@@ -4408,8 +4510,7 @@
 
 /// \brief Determine whether we have compatible array types for the
 /// purposes of GNU by-copy array initialization.
-static bool hasCompatibleArrayTypes(ASTContext &Context,
-                                    const ArrayType *Dest, 
+static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
                                     const ArrayType *Source) {
   // If the source and destination array types are equivalent, we're
   // done.
@@ -4668,7 +4769,7 @@
     return;
   }
 
-  // Determine whether we should consider writeback conversions for 
+  // Determine whether we should consider writeback conversions for
   // Objective-C ARC.
   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
          Entity.isParameterKind();
@@ -5022,6 +5123,8 @@
                              const InitializedEntity &Entity,
                              ExprResult CurInit,
                              bool IsExtraneousCopy) {
+  if (CurInit.isInvalid())
+    return CurInit;
   // Determine which class type we're copying to.
   Expr *CurInitExpr = (Expr *)CurInit.get();
   CXXRecordDecl *Class = nullptr;
@@ -5497,18 +5600,18 @@
 static bool
 performReferenceExtension(Expr *Init,
                           const InitializedEntity *ExtendingEntity) {
-  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
-    if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
-      // This is just redundant braces around an initializer. Step over it.
-      Init = ILE->getInit(0);
-    }
-  }
-
   // Walk past any constructs which we can lifetime-extend across.
   Expr *Old;
   do {
     Old = Init;
 
+    if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
+      if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
+        // This is just redundant braces around an initializer. Step over it.
+        Init = ILE->getInit(0);
+      }
+    }
+
     // Step over any subobject adjustments; we may have a materialized
     // temporary inside them.
     SmallVector<const Expr *, 2> CommaLHSs;
@@ -5820,15 +5923,6 @@
                                          &BasePath, IgnoreBaseAccess))
         return ExprError();
 
-      if (S.BasePathInvolvesVirtualBase(BasePath)) {
-        QualType T = SourceType;
-        if (const PointerType *Pointer = T->getAs<PointerType>())
-          T = Pointer->getPointeeType();
-        if (const RecordType *RecordTy = T->getAs<RecordType>())
-          S.MarkVTableUsed(CurInit.get()->getLocStart(),
-                           cast<CXXRecordDecl>(RecordTy->getDecl()));
-      }
-
       ExprValueKind VK =
           Step->Kind == SK_CastDerivedToBaseLValue ?
               VK_LValue :
diff --git a/lib/Sema/SemaLambda.cpp b/lib/Sema/SemaLambda.cpp
index a64a0fb..90a81f4 100644
--- a/lib/Sema/SemaLambda.cpp
+++ b/lib/Sema/SemaLambda.cpp
@@ -617,7 +617,7 @@
   // If it was ever a placeholder, it had to been deduced to DependentTy.
   assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); 
 
-  // C++ Core Issue #975, proposed resolution:
+  // C++ core issue 975:
   //   If a lambda-expression does not include a trailing-return-type,
   //   it is as if the trailing-return-type denotes the following type:
   //     - if there are no return statements in the compound-statement,
@@ -631,6 +631,10 @@
   //       same, that common type;
   //     - otherwise, the program is ill-formed.
   //
+  // C++ core issue 1048 additionally removes top-level cv-qualifiers
+  // from the types of returned expressions to match the C++14 auto
+  // deduction rules.
+  //
   // In addition, in blocks in non-C++ modes, if all of the return
   // statements are enumerator-like expressions of some type T, where
   // T has a name for linkage, then we infer the return type of the
@@ -679,7 +683,8 @@
     const ReturnStmt *RS = *I;
     const Expr *RetE = RS->getRetValue();
 
-    QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
+    QualType ReturnType =
+        (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
     if (Context.hasSameType(ReturnType, CSI.ReturnType))
       continue;
 
diff --git a/lib/Sema/SemaLookup.cpp b/lib/Sema/SemaLookup.cpp
index 8b0ea32..06d2223 100644
--- a/lib/Sema/SemaLookup.cpp
+++ b/lib/Sema/SemaLookup.cpp
@@ -194,10 +194,11 @@
     const_iterator begin() const { return list.begin(); }
     const_iterator end() const { return list.end(); }
 
-    std::pair<const_iterator,const_iterator>
+    llvm::iterator_range<const_iterator>
     getNamespacesFor(DeclContext *DC) const {
-      return std::equal_range(begin(), end(), DC->getPrimaryContext(),
-                              UnqualUsingEntry::Comparator());
+      return llvm::make_range(std::equal_range(begin(), end(),
+                                               DC->getPrimaryContext(),
+                                               UnqualUsingEntry::Comparator()));
     }
   };
 }
@@ -413,6 +414,8 @@
     if (!Unique.insert(D).second) {
       // If it's not unique, pull something off the back (and
       // continue at this index).
+      // FIXME: This is wrong. We need to take the more recent declaration in
+      // order to get the right type, default arguments, etc.
       Decls[I] = Decls[--N];
       continue;
     }
@@ -670,8 +673,8 @@
     DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
 
   // Perform lookup into this declaration context.
-  DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
-  for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
+  DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
+  for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
        ++I) {
     NamedDecl *D = *I;
     if ((D = R.getAcceptableDecl(D))) {
@@ -765,11 +768,8 @@
 
   // Perform direct name lookup into the namespaces nominated by the
   // using directives whose common ancestor is this namespace.
-  UnqualUsingDirectiveSet::const_iterator UI, UEnd;
-  std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
-
-  for (; UI != UEnd; ++UI)
-    if (LookupDirect(S, R, UI->getNominatedNamespace()))
+  for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
+    if (LookupDirect(S, R, UUE.getNominatedNamespace()))
       Found = true;
 
   R.resolveKind();
@@ -1256,6 +1256,9 @@
 
   for (auto RD : D->redecls()) {
     if (auto ND = dyn_cast<NamedDecl>(RD)) {
+      // FIXME: This is wrong in the case where the previous declaration is not
+      // visible in the same scope as D. This needs to be done much more
+      // carefully.
       if (LookupResult::isVisible(SemaRef, ND))
         return ND;
     }
@@ -1762,6 +1765,31 @@
   return true;
 }
 
+/// \brief Performs qualified name lookup or special type of lookup for
+/// "__super::" scope specifier.
+///
+/// This routine is a convenience overload meant to be called from contexts
+/// that need to perform a qualified name lookup with an optional C++ scope
+/// specifier that might require special kind of lookup.
+///
+/// \param R captures both the lookup criteria and any lookup results found.
+///
+/// \param LookupCtx The context in which qualified name lookup will
+/// search.
+///
+/// \param SS An optional C++ scope-specifier.
+///
+/// \returns true if lookup succeeded, false if it failed.
+bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
+                               CXXScopeSpec &SS) {
+  auto *NNS = SS.getScopeRep();
+  if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
+    return LookupInSuper(R, NNS->getAsRecordDecl());
+  else
+
+    return LookupQualifiedName(R, LookupCtx);
+}
+
 /// @brief Performs name lookup for a name that was parsed in the
 /// source code, and may contain a C++ scope specifier.
 ///
@@ -2475,8 +2503,18 @@
   // will always be a (possibly implicit) declaration to shadow any others.
   OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
   DeclContext::lookup_result R = RD->lookup(Name);
-  assert(!R.empty() &&
-         "lookup for a constructor or assignment operator was empty");
+
+  if (R.empty()) {
+    // We might have no default constructor because we have a lambda's closure
+    // type, rather than because there's some other declared constructor.
+    // Every class has a copy/move constructor, copy/move assignment, and
+    // destructor.
+    assert(SM == CXXDefaultConstructor &&
+           "lookup for a constructor or assignment operator was empty");
+    Result->setMethod(nullptr);
+    Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
+    return Result;
+  }
 
   // Copy the candidates as our processing of them may load new declarations
   // from an external source and invalidate lookup_result.
@@ -3174,10 +3212,8 @@
   if (Entity) {
     // Lookup visible declarations in any namespaces found by using
     // directives.
-    UnqualUsingDirectiveSet::const_iterator UI, UEnd;
-    std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
-    for (; UI != UEnd; ++UI)
-      LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
+    for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
+      LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
                          Result, /*QualifiedNameLookup=*/false,
                          /*InBaseClass=*/false, Consumer, Visited);
   }
@@ -3562,7 +3598,7 @@
         QualifiedResults.push_back(Candidate);
       break;
     }
-    Candidate.setCorrectionRange(TempSS, Result.getLookupNameInfo());
+    Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
     return true;
   }
   return false;
@@ -3998,8 +4034,7 @@
     Scope *S, CXXScopeSpec *SS,
     std::unique_ptr<CorrectionCandidateCallback> CCC,
     DeclContext *MemberContext, bool EnteringContext,
-    const ObjCObjectPointerType *OPT, bool ErrorRecovery,
-    bool &IsUnqualifiedLookup) {
+    const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
 
   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
       DisableTypoCorrection)
@@ -4043,6 +4078,14 @@
   if (getLangOpts().AltiVec && Typo->isStr("vector"))
     return nullptr;
 
+  // Provide a stop gap for files that are just seriously broken.  Trying
+  // to correct all typos can turn into a HUGE performance penalty, causing
+  // some files to take minutes to get rejected by the parser.
+  unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
+  if (Limit && TyposCorrected >= Limit)
+    return nullptr;
+  ++TyposCorrected;
+
   // If we're handling a missing symbol error, using modules, and the
   // special search all modules option is used, look for a missing import.
   if (ErrorRecovery && getLangOpts().Modules &&
@@ -4057,13 +4100,8 @@
       *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
       EnteringContext);
 
-  // If a callback object considers an empty typo correction candidate to be
-  // viable, assume it does not do any actual validation of the candidates.
-  TypoCorrection EmptyCorrection;
-  bool ValidatingCallback = !isCandidateViable(CCCRef, EmptyCorrection);
-
   // Perform name lookup to find visible, similarly-named entities.
-  IsUnqualifiedLookup = false;
+  bool IsUnqualifiedLookup = false;
   DeclContext *QualifiedDC = MemberContext;
   if (MemberContext) {
     LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
@@ -4078,46 +4116,9 @@
     if (!QualifiedDC)
       return nullptr;
 
-    // Provide a stop gap for files that are just seriously broken.  Trying
-    // to correct all typos can turn into a HUGE performance penalty, causing
-    // some files to take minutes to get rejected by the parser.
-    if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
-      return nullptr;
-    ++TyposCorrected;
-
     LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
   } else {
     IsUnqualifiedLookup = true;
-    UnqualifiedTyposCorrectedMap::iterator Cached
-      = UnqualifiedTyposCorrected.find(Typo);
-    if (Cached != UnqualifiedTyposCorrected.end()) {
-      // Add the cached value, unless it's a keyword or fails validation. In the
-      // keyword case, we'll end up adding the keyword below.
-      if (Cached->second) {
-        if (!Cached->second.isKeyword() &&
-            isCandidateViable(CCCRef, Cached->second)) {
-          // Do not use correction that is unaccessible in the given scope.
-          NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
-          DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
-                                       CorrectionDecl->getLocation());
-          LookupResult R(*this, NameInfo, LookupOrdinaryName);
-          if (LookupName(R, S))
-            Consumer->addCorrection(Cached->second);
-        }
-      } else {
-        // Only honor no-correction cache hits when a callback that will validate
-        // correction candidates is not being used.
-        if (!ValidatingCallback)
-          return nullptr;
-      }
-    }
-    if (Cached == UnqualifiedTyposCorrected.end()) {
-      // Provide a stop gap for files that are just seriously broken.  Trying
-      // to correct all typos can turn into a HUGE performance penalty, causing
-      // some files to take minutes to get rejected by the parser.
-      if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
-        return nullptr;
-    }
   }
 
   // Determine whether we are going to search in the various namespaces for
@@ -4224,30 +4225,24 @@
   // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
   bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
 
-  TypoCorrection EmptyCorrection;
-  bool ValidatingCallback = !isCandidateViable(*CCC, EmptyCorrection);
-
   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
-  bool IsUnqualifiedLookup = false;
   auto Consumer = makeTypoCorrectionConsumer(
       TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
-      EnteringContext, OPT, Mode == CTK_ErrorRecovery, IsUnqualifiedLookup);
+      EnteringContext, OPT, Mode == CTK_ErrorRecovery);
 
   if (!Consumer)
     return TypoCorrection();
 
   // If we haven't found anything, we're done.
   if (Consumer->empty())
-    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
-                            IsUnqualifiedLookup);
+    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
 
   // Make sure the best edit distance (prior to adding any namespace qualifiers)
   // is not more that about a third of the length of the typo's identifier.
   unsigned ED = Consumer->getBestEditDistance(true);
   unsigned TypoLen = Typo->getName().size();
   if (ED > 0 && TypoLen / ED < 3)
-    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
-                            IsUnqualifiedLookup);
+    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
 
   TypoCorrection BestTC = Consumer->getNextCorrection();
   TypoCorrection SecondBestTC = Consumer->getNextCorrection();
@@ -4260,8 +4255,7 @@
     // If this was an unqualified lookup and we believe the callback
     // object wouldn't have filtered out possible corrections, note
     // that no correction was found.
-    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
-                            IsUnqualifiedLookup && !ValidatingCallback);
+    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
   }
 
   // If only a single name remains, return that result.
@@ -4274,10 +4268,6 @@
     if (ED == 0 && Result.isKeyword())
       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
 
-    // Record the correction for unqualified lookup.
-    if (IsUnqualifiedLookup)
-      UnqualifiedTyposCorrected[Typo] = Result;
-
     TypoCorrection TC = Result;
     TC.setCorrectionRange(SS, TypoName);
     checkCorrectionVisibility(*this, TC);
@@ -4298,10 +4288,6 @@
         BestTC.getCorrection().getAsString() != "super")
       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
 
-    // Record the correction for unqualified lookup.
-    if (IsUnqualifiedLookup)
-      UnqualifiedTyposCorrected[Typo] = BestTC;
-
     BestTC.setCorrectionRange(SS, TypoName);
     return BestTC;
   }
@@ -4309,8 +4295,7 @@
   // Record the failure's location if needed and return an empty correction. If
   // this was an unqualified lookup and we believe the callback object did not
   // filter out possible corrections, also cache the failure for the typo.
-  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
-                          IsUnqualifiedLookup && !ValidatingCallback);
+  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
 }
 
 /// \brief Try to "correct" a typo in the source code by finding
@@ -4361,13 +4346,9 @@
   assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
 
   TypoCorrection Empty;
-  bool IsUnqualifiedLookup = false;
   auto Consumer = makeTypoCorrectionConsumer(
       TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
-      EnteringContext, OPT,
-      /*SearchModules=*/(Mode == CTK_ErrorRecovery) && getLangOpts().Modules &&
-          getLangOpts().ModulesSearchAll,
-      IsUnqualifiedLookup);
+      EnteringContext, OPT, Mode == CTK_ErrorRecovery);
 
   if (!Consumer || Consumer->empty())
     return nullptr;
diff --git a/lib/Sema/SemaObjCProperty.cpp b/lib/Sema/SemaObjCProperty.cpp
index 72b6020..f4f4336 100644
--- a/lib/Sema/SemaObjCProperty.cpp
+++ b/lib/Sema/SemaObjCProperty.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/Initialization.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallString.h"
@@ -1854,6 +1855,39 @@
           Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule);
         else
           Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule);
+
+        // Look for a getter explicitly declared alongside the property.
+        // If we find one, use its location for the note.
+        SourceLocation noteLoc = PD->getLocation();
+        SourceLocation fixItLoc;
+        for (auto *getterRedecl : method->redecls()) {
+          if (getterRedecl->isImplicit())
+            continue;
+          if (getterRedecl->getDeclContext() != PD->getDeclContext())
+            continue;
+          noteLoc = getterRedecl->getLocation();
+          fixItLoc = getterRedecl->getLocEnd();
+        }
+
+        Preprocessor &PP = getPreprocessor();
+        TokenValue tokens[] = {
+          tok::kw___attribute, tok::l_paren, tok::l_paren,
+          PP.getIdentifierInfo("objc_method_family"), tok::l_paren,
+          PP.getIdentifierInfo("none"), tok::r_paren,
+          tok::r_paren, tok::r_paren
+        };
+        StringRef spelling = "__attribute__((objc_method_family(none)))";
+        StringRef macroName = PP.getLastMacroWithSpelling(noteLoc, tokens);
+        if (!macroName.empty())
+          spelling = macroName;
+
+        auto noteDiag = Diag(noteLoc, diag::note_cocoa_naming_declare_family)
+            << method->getDeclName() << spelling;
+        if (fixItLoc.isValid()) {
+          SmallString<64> fixItText(" ");
+          fixItText += spelling;
+          noteDiag << FixItHint::CreateInsertion(fixItLoc, fixItText);
+        }
       }
     }
   }
diff --git a/lib/Sema/SemaOpenMP.cpp b/lib/Sema/SemaOpenMP.cpp
index e4838de..d8bedd7 100644
--- a/lib/Sema/SemaOpenMP.cpp
+++ b/lib/Sema/SemaOpenMP.cpp
@@ -391,7 +391,8 @@
   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
   // in a Construct, C/C++, predetermined, p.1]
   //  Variables appearing in threadprivate directives are threadprivate.
-  if (D->getTLSKind() != VarDecl::TLS_None) {
+  if (D->getTLSKind() != VarDecl::TLS_None ||
+      D->getStorageClass() == SC_Register) {
     DVar.CKind = OMPC_threadprivate;
     return DVar;
   }
@@ -420,21 +421,23 @@
       DVar.CKind = OMPC_private;
       return DVar;
     }
-  }
 
-  // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
-  // in a Construct, C/C++, predetermined, p.4]
-  //  Static data members are shared.
-  if (D->isStaticDataMember()) {
-    // Variables with const-qualified type having no mutable member may be
-    // listed in a firstprivate clause, even if they are static data members.
-    DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
-                                 MatchesAlways(), FromParent);
-    if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
+    // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
+    // in a Construct, C/C++, predetermined, p.4]
+    //  Static data members are shared.
+    // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
+    // in a Construct, C/C++, predetermined, p.7]
+    //  Variables with static storage duration that are declared in a scope
+    //  inside the construct are shared.
+    if (D->isStaticDataMember() || D->isStaticLocal()) {
+      DSAVarData DVarTemp =
+          hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
+      if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
+        return DVar;
+
+      DVar.CKind = OMPC_shared;
       return DVar;
-
-    DVar.CKind = OMPC_shared;
-    return DVar;
+    }
   }
 
   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
@@ -462,15 +465,6 @@
     return DVar;
   }
 
-  // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
-  // in a Construct, C/C++, predetermined, p.7]
-  //  Variables with static storage duration that are declared in a scope
-  //  inside the construct are shared.
-  if (D->isStaticLocal()) {
-    DVar.CKind = OMPC_shared;
-    return DVar;
-  }
-
   // Explicitly specified attributes and local variables with predetermined
   // attributes.
   auto I = std::prev(StartI);
@@ -551,6 +545,19 @@
 
 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
 
+bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
+  assert(LangOpts.OpenMP && "OpenMP is not allowed");
+  if (DSAStack->getCurrentDirective() != OMPD_unknown) {
+    auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
+    if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
+      return true;
+    DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
+                                   /*FromParent=*/false);
+    return DVarPrivate.CKind != OMPC_unknown;
+  }
+  return false;
+}
+
 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
 
 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
@@ -828,8 +835,10 @@
     }
 
     // Check if this is a TLS variable.
-    if (VD->getTLSKind()) {
-      Diag(ILoc, diag::err_omp_var_thread_local) << VD;
+    if (VD->getTLSKind() != VarDecl::TLS_None ||
+        VD->getStorageClass() == SC_Register) {
+      Diag(ILoc, diag::err_omp_var_thread_local)
+          << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
       bool IsDecl =
           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
       Diag(VD->getLocation(),
@@ -1120,38 +1129,6 @@
                              Params);
     break;
   }
-  case OMPD_taskyield: {
-    Sema::CapturedParamNameType Params[] = {
-        std::make_pair(StringRef(), QualType()) // __context with shared vars
-    };
-    ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
-                             Params);
-    break;
-  }
-  case OMPD_barrier: {
-    Sema::CapturedParamNameType Params[] = {
-        std::make_pair(StringRef(), QualType()) // __context with shared vars
-    };
-    ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
-                             Params);
-    break;
-  }
-  case OMPD_taskwait: {
-    Sema::CapturedParamNameType Params[] = {
-        std::make_pair(StringRef(), QualType()) // __context with shared vars
-    };
-    ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
-                             Params);
-    break;
-  }
-  case OMPD_flush: {
-    Sema::CapturedParamNameType Params[] = {
-        std::make_pair(StringRef(), QualType()) // __context with shared vars
-    };
-    ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
-                             Params);
-    break;
-  }
   case OMPD_ordered: {
     Sema::CapturedParamNameType Params[] = {
         std::make_pair(StringRef(), QualType()) // __context with shared vars
@@ -1189,6 +1166,10 @@
     break;
   }
   case OMPD_threadprivate:
+  case OMPD_taskyield:
+  case OMPD_barrier:
+  case OMPD_taskwait:
+  case OMPD_flush:
     llvm_unreachable("OpenMP Directive is not allowed");
   case OMPD_unknown:
     llvm_unreachable("Unknown OpenMP directive");
@@ -2385,46 +2366,6 @@
   SourceRange IncSrcRange;
 };
 
-/// \brief The resulting expressions built for the OpenMP loop CodeGen for the
-/// whole collapsed loop nest. See class OMPLoopDirective for their description.
-struct BuiltLoopExprs {
-  Expr *IterationVarRef;
-  Expr *LastIteration;
-  Expr *CalcLastIteration;
-  Expr *PreCond;
-  Expr *Cond;
-  Expr *SeparatedCond;
-  Expr *Init;
-  Expr *Inc;
-  SmallVector<Expr *, 4> Counters;
-  SmallVector<Expr *, 4> Updates;
-  SmallVector<Expr *, 4> Finals;
-
-  bool builtAll() {
-    return IterationVarRef != nullptr && LastIteration != nullptr &&
-           PreCond != nullptr && Cond != nullptr && SeparatedCond != nullptr &&
-           Init != nullptr && Inc != nullptr;
-  }
-  void clear(unsigned size) {
-    IterationVarRef = nullptr;
-    LastIteration = nullptr;
-    CalcLastIteration = nullptr;
-    PreCond = nullptr;
-    Cond = nullptr;
-    SeparatedCond = nullptr;
-    Init = nullptr;
-    Inc = nullptr;
-    Counters.resize(size);
-    Updates.resize(size);
-    Finals.resize(size);
-    for (unsigned i = 0; i < size; ++i) {
-      Counters[i] = nullptr;
-      Updates[i] = nullptr;
-      Finals[i] = nullptr;
-    }
-  }
-};
-
 } // namespace
 
 /// \brief Called on a for stmt to check and extract its iteration space
@@ -2641,7 +2582,7 @@
 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
                 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
                 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
-                BuiltLoopExprs &Built) {
+                OMPLoopDirective::HelperExprs &Built) {
   unsigned NestedLoopCount = 1;
   if (NestedLoopCountExpr) {
     // Found 'collapse' clause - calculate collapse number.
@@ -2778,23 +2719,71 @@
       CurScope, InitLoc, BO_GT, LastIteration.get(),
       SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
 
-  // Build the iteration variable and its initialization to zero before loop.
+  QualType VType = LastIteration.get()->getType();
+  // Build variables passed into runtime, nesessary for worksharing directives.
+  ExprResult LB, UB, IL, ST, EUB;
+  if (isOpenMPWorksharingDirective(DKind)) {
+    // Lower bound variable, initialized with zero.
+    VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
+    LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
+    SemaRef.AddInitializerToDecl(
+        LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
+        /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
+
+    // Upper bound variable, initialized with last iteration number.
+    VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
+    UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
+    SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
+                                 /*DirectInit*/ false,
+                                 /*TypeMayContainAuto*/ false);
+
+    // A 32-bit variable-flag where runtime returns 1 for the last iteration.
+    // This will be used to implement clause 'lastprivate'.
+    QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
+    VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
+    IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
+    SemaRef.AddInitializerToDecl(
+        ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
+        /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
+
+    // Stride variable returned by runtime (we initialize it to 1 by default).
+    VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
+    ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
+    SemaRef.AddInitializerToDecl(
+        STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
+        /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
+
+    // Build expression: UB = min(UB, LastIteration)
+    // It is nesessary for CodeGen of directives with static scheduling.
+    ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
+                                                UB.get(), LastIteration.get());
+    ExprResult CondOp = SemaRef.ActOnConditionalOp(
+        InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
+    EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
+                             CondOp.get());
+    EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
+  }
+
+  // Build the iteration variable and its initialization before loop.
   ExprResult IV;
   ExprResult Init;
   {
-    VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc,
-                                   LastIteration.get()->getType(), ".omp.iv");
-    IV = SemaRef.BuildDeclRefExpr(IVDecl, LastIteration.get()->getType(),
-                                  VK_LValue, InitLoc);
-    Init = SemaRef.BuildBinOp(
-        CurScope, InitLoc, BO_Assign, IV.get(),
-        SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
+    VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
+    IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
+    Expr *RHS = isOpenMPWorksharingDirective(DKind)
+                    ? LB.get()
+                    : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
+    Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
+    Init = SemaRef.ActOnFinishFullExpr(Init.get());
   }
 
-  // Loop condition (IV < NumIterations)
+  // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
   SourceLocation CondLoc;
-  ExprResult Cond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
-                                       NumIterations.get());
+  ExprResult Cond =
+      isOpenMPWorksharingDirective(DKind)
+          ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
+          : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
+                               NumIterations.get());
   // Loop condition with 1 iteration separated (IV < LastIteration)
   ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
                                                 IV.get(), LastIteration.get());
@@ -2807,6 +2796,35 @@
   if (!Inc.isUsable())
     return 0;
   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
+  Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
+  if (!Inc.isUsable())
+    return 0;
+
+  // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
+  // Used for directives with static scheduling.
+  ExprResult NextLB, NextUB;
+  if (isOpenMPWorksharingDirective(DKind)) {
+    // LB + ST
+    NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
+    if (!NextLB.isUsable())
+      return 0;
+    // LB = LB + ST
+    NextLB =
+        SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
+    NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
+    if (!NextLB.isUsable())
+      return 0;
+    // UB + ST
+    NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
+    if (!NextUB.isUsable())
+      return 0;
+    // UB = UB + ST
+    NextUB =
+        SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
+    NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
+    if (!NextUB.isUsable())
+      return 0;
+  }
 
   // Build updates and final values of the loop counters.
   bool HasErrors = false;
@@ -2896,6 +2914,13 @@
   Built.SeparatedCond = SeparatedCond.get();
   Built.Init = Init.get();
   Built.Inc = Inc.get();
+  Built.LB = LB.get();
+  Built.UB = UB.get();
+  Built.IL = IL.get();
+  Built.ST = ST.get();
+  Built.EUB = EUB.get();
+  Built.NLB = NextLB.get();
+  Built.NUB = NextUB.get();
 
   return NestedLoopCount;
 }
@@ -2915,7 +2940,7 @@
     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
     SourceLocation EndLoc,
     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
-  BuiltLoopExprs B;
+  OMPLoopDirective::HelperExprs B;
   // In presence of clause 'collapse', it will define the nested loops number.
   unsigned NestedLoopCount =
       CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
@@ -2927,17 +2952,15 @@
          "omp simd loop exprs were not built");
 
   getCurFunction()->setHasBranchProtectedScope();
-  return OMPSimdDirective::Create(
-      Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
-      B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
-      B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
+  return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
+                                  Clauses, AStmt, B);
 }
 
 StmtResult Sema::ActOnOpenMPForDirective(
     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
     SourceLocation EndLoc,
     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
-  BuiltLoopExprs B;
+  OMPLoopDirective::HelperExprs B;
   // In presence of clause 'collapse', it will define the nested loops number.
   unsigned NestedLoopCount =
       CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
@@ -2949,17 +2972,15 @@
          "omp for loop exprs were not built");
 
   getCurFunction()->setHasBranchProtectedScope();
-  return OMPForDirective::Create(
-      Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
-      B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
-      B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
+  return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
+                                 Clauses, AStmt, B);
 }
 
 StmtResult Sema::ActOnOpenMPForSimdDirective(
     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
     SourceLocation EndLoc,
     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
-  BuiltLoopExprs B;
+  OMPLoopDirective::HelperExprs B;
   // In presence of clause 'collapse', it will define the nested loops number.
   unsigned NestedLoopCount =
       CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
@@ -2967,11 +2988,12 @@
   if (NestedLoopCount == 0)
     return StmtError();
 
+  assert((CurContext->isDependentContext() || B.builtAll()) &&
+         "omp for simd loop exprs were not built");
+
   getCurFunction()->setHasBranchProtectedScope();
-  return OMPForSimdDirective::Create(
-      Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
-      B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
-      B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
+  return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
+                                     Clauses, AStmt, B);
 }
 
 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
@@ -3026,6 +3048,23 @@
 
   getCurFunction()->setHasBranchProtectedScope();
 
+  // OpenMP [2.7.3, single Construct, Restrictions]
+  // The copyprivate clause must not be used with the nowait clause.
+  OMPClause *Nowait = nullptr;
+  OMPClause *Copyprivate = nullptr;
+  for (auto *Clause : Clauses) {
+    if (Clause->getClauseKind() == OMPC_nowait)
+      Nowait = Clause;
+    else if (Clause->getClauseKind() == OMPC_copyprivate)
+      Copyprivate = Clause;
+    if (Copyprivate && Nowait) {
+      Diag(Copyprivate->getLocStart(),
+           diag::err_omp_single_copyprivate_with_nowait);
+      Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
+      return StmtError();
+    }
+  }
+
   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
 }
 
@@ -3064,7 +3103,7 @@
   // longjmp() and throw() must not violate the entry/exit criteria.
   CS->getCapturedDecl()->setNothrow();
 
-  BuiltLoopExprs B;
+  OMPLoopDirective::HelperExprs B;
   // In presence of clause 'collapse', it will define the nested loops number.
   unsigned NestedLoopCount =
       CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
@@ -3076,10 +3115,8 @@
          "omp parallel for loop exprs were not built");
 
   getCurFunction()->setHasBranchProtectedScope();
-  return OMPParallelForDirective::Create(
-      Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
-      B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
-      B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
+  return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
+                                         NestedLoopCount, Clauses, AStmt, B);
 }
 
 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
@@ -3095,7 +3132,7 @@
   // longjmp() and throw() must not violate the entry/exit criteria.
   CS->getCapturedDecl()->setNothrow();
 
-  BuiltLoopExprs B;
+  OMPLoopDirective::HelperExprs B;
   // In presence of clause 'collapse', it will define the nested loops number.
   unsigned NestedLoopCount =
       CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
@@ -3105,9 +3142,7 @@
 
   getCurFunction()->setHasBranchProtectedScope();
   return OMPParallelForSimdDirective::Create(
-      Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
-      B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
-      B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
+      Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
 }
 
 StmtResult
@@ -3250,14 +3285,14 @@
   // expr or subexpressions of expr.
   // * For forms that allow multiple occurrences of x, the number of times
   // that x is evaluated is unspecified.
+  enum {
+    NotAnExpression,
+    NotAnAssignmentOp,
+    NotAScalarType,
+    NotAnLValue,
+    NoError
+  } ErrorFound = NoError;
   if (AtomicKind == OMPC_read) {
-    enum {
-      NotAnExpression,
-      NotAnAssignmentOp,
-      NotAScalarType,
-      NotAnLValue,
-      NoError
-    } ErrorFound = NoError;
     SourceLocation ErrorLoc, NoteLoc;
     SourceRange ErrorRange, NoteRange;
     // If clause is read:
@@ -3307,16 +3342,65 @@
     if (ErrorFound != NoError) {
       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
           << ErrorRange;
-      Diag(NoteLoc, diag::note_omp_atomic_read) << ErrorFound << NoteRange;
+      Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
+                                                      << NoteRange;
       return StmtError();
     } else if (CurContext->isDependentContext())
       V = X = nullptr;
   } else if (AtomicKind == OMPC_write) {
-    if (!isa<Expr>(Body)) {
-      Diag(Body->getLocStart(),
-           diag::err_omp_atomic_write_not_expression_statement);
-      return StmtError();
+    SourceLocation ErrorLoc, NoteLoc;
+    SourceRange ErrorRange, NoteRange;
+    // If clause is write:
+    //  x = expr;
+    if (auto AtomicBody = dyn_cast<Expr>(Body)) {
+      auto AtomicBinOp =
+          dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
+      if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
+        X = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
+        E = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
+        if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
+            (E->isInstantiationDependent() || E->getType()->isScalarType())) {
+          if (!X->isLValue()) {
+            ErrorFound = NotAnLValue;
+            ErrorLoc = AtomicBinOp->getExprLoc();
+            ErrorRange = AtomicBinOp->getSourceRange();
+            NoteLoc = X->getExprLoc();
+            NoteRange = X->getSourceRange();
+          }
+        } else if (!X->isInstantiationDependent() ||
+                   !E->isInstantiationDependent()) {
+          auto NotScalarExpr =
+              (X->isInstantiationDependent() || X->getType()->isScalarType())
+                  ? E
+                  : X;
+          ErrorFound = NotAScalarType;
+          ErrorLoc = AtomicBinOp->getExprLoc();
+          ErrorRange = AtomicBinOp->getSourceRange();
+          NoteLoc = NotScalarExpr->getExprLoc();
+          NoteRange = NotScalarExpr->getSourceRange();
+        }
+      } else {
+        ErrorFound = NotAnAssignmentOp;
+        ErrorLoc = AtomicBody->getExprLoc();
+        ErrorRange = AtomicBody->getSourceRange();
+        NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
+                              : AtomicBody->getExprLoc();
+        NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
+                                : AtomicBody->getSourceRange();
+      }
+    } else {
+      ErrorFound = NotAnExpression;
+      NoteLoc = ErrorLoc = Body->getLocStart();
+      NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
     }
+    if (ErrorFound != NoError) {
+      Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
+          << ErrorRange;
+      Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
+                                                      << NoteRange;
+      return StmtError();
+    } else if (CurContext->isDependentContext())
+      E = X = nullptr;
   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
     if (!isa<Expr>(Body)) {
       Diag(Body->getLocStart(),
@@ -4095,11 +4179,12 @@
     if (VDPrivate->isInvalidDecl())
       continue;
     CurContext->addDecl(VDPrivate);
-    auto VDPrivateRefExpr = DeclRefExpr::Create(
-        Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
-        /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
-        /*isEnclosingLocal*/ false, /*NameLoc*/ SourceLocation(), DE->getType(),
-        /*VK*/ VK_LValue);
+    auto VDPrivateRefExpr =
+        DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
+                            /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
+                            /*RefersToEnclosingVariableOrCapture*/ false,
+                            /*NameLoc*/ SourceLocation(), DE->getType(),
+                            /*VK*/ VK_LValue);
 
     DSAStack->addDSA(VD, DE, OMPC_private);
     Vars.push_back(DE);
@@ -4320,7 +4405,7 @@
       VDInitRefExpr = DeclRefExpr::Create(
           Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
           /*TemplateKWLoc*/ SourceLocation(), VDInit,
-          /*isEnclosingLocal*/ false, ELoc, Type,
+          /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
           /*VK*/ VK_LValue);
       VDInit->setIsUsed();
       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
@@ -4334,8 +4419,15 @@
       else
         VDPrivate->setInit(Result.getAs<Expr>());
     } else {
-      AddInitializerToDecl(VDPrivate, DefaultLvalueConversion(DE).get(),
-                           /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
+      AddInitializerToDecl(
+          VDPrivate,
+          DefaultLvalueConversion(
+              DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
+                                  SourceLocation(), DE->getDecl(),
+                                  /*RefersToEnclosingVariableOrCapture=*/true,
+                                  DE->getExprLoc(), DE->getType(),
+                                  /*VK=*/VK_LValue)).get(),
+          /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
     }
     if (VDPrivate->isInvalidDecl()) {
       if (IsImplicitClause) {
@@ -4345,11 +4437,12 @@
       continue;
     }
     CurContext->addDecl(VDPrivate);
-    auto VDPrivateRefExpr = DeclRefExpr::Create(
-        Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
-        /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
-        /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
-        /*VK*/ VK_LValue);
+    auto VDPrivateRefExpr =
+        DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
+                            /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
+                            /*RefersToEnclosingVariableOrCapture*/ false,
+                            DE->getLocStart(), DE->getType(),
+                            /*VK*/ VK_LValue);
     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
     Vars.push_back(DE);
     PrivateCopies.push_back(VDPrivateRefExpr);
diff --git a/lib/Sema/SemaOverload.cpp b/lib/Sema/SemaOverload.cpp
index 5e02647..664b6a4 100644
--- a/lib/Sema/SemaOverload.cpp
+++ b/lib/Sema/SemaOverload.cpp
@@ -286,6 +286,16 @@
   QualType FromType = getToType(0);
   QualType ToType = getToType(1);
   switch (Second) {
+  // 'bool' is an integral type; dispatch to the right place to handle it.
+  case ICK_Boolean_Conversion:
+    if (FromType->isRealFloatingType())
+      goto FloatingIntegralConversion;
+    if (FromType->isIntegralOrUnscopedEnumerationType())
+      goto IntegralConversion;
+    // Boolean conversions can be from pointers and pointers to members
+    // [conv.bool], and those aren't considered narrowing conversions.
+    return NK_Not_Narrowing;
+
   // -- from a floating-point type to an integer type, or
   //
   // -- from an integer type or unscoped enumeration type to a floating-point
@@ -293,6 +303,7 @@
   //    value after conversion will fit into the target type and will produce
   //    the original value when converted back to the original type, or
   case ICK_Floating_Integral:
+  FloatingIntegralConversion:
     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
       return NK_Type_Narrowing;
     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
@@ -357,13 +368,8 @@
   //    the source is a constant expression and the actual value after
   //    conversion will fit into the target type and will produce the original
   //    value when converted back to the original type.
-  case ICK_Boolean_Conversion:  // Bools are integers too.
-    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
-      // Boolean conversions can be from pointers and pointers to members
-      // [conv.bool], and those aren't considered narrowing conversions.
-      return NK_Not_Narrowing;
-    }  // Otherwise, fall through to the integral case.
-  case ICK_Integral_Conversion: {
+  case ICK_Integral_Conversion:
+  IntegralConversion: {
     assert(FromType->isIntegralOrUnscopedEnumerationType());
     assert(ToType->isIntegralOrUnscopedEnumerationType());
     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
@@ -1098,11 +1104,11 @@
   // Attempt user-defined conversion.
   OverloadCandidateSet Conversions(From->getExprLoc(),
                                    OverloadCandidateSet::CSK_Normal);
-  OverloadingResult UserDefResult
-    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
-                              AllowExplicit, AllowObjCConversionOnExplicit);
-
-  if (UserDefResult == OR_Success) {
+  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
+                                  Conversions, AllowExplicit,
+                                  AllowObjCConversionOnExplicit)) {
+  case OR_Success:
+  case OR_Deleted:
     ICS.setUserDefined();
     ICS.UserDefined.Before.setAsIdentityConversion();
     // C++ [over.ics.user]p4:
@@ -1131,7 +1137,9 @@
           ICS.Standard.Second = ICK_Derived_To_Base;
       }
     }
-  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
+    break;
+
+  case OR_Ambiguous:
     ICS.setAmbiguous();
     ICS.Ambiguous.setFromType(From->getType());
     ICS.Ambiguous.setToType(ToType);
@@ -1139,8 +1147,12 @@
          Cand != Conversions.end(); ++Cand)
       if (Cand->Viable)
         ICS.Ambiguous.addConversion(Cand->Function);
-  } else {
+    break;
+
+    // Fall through.
+  case OR_No_Viable_Function:
     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
+    break;
   }
 
   return ICS;
@@ -3093,11 +3105,8 @@
     if (CXXRecordDecl *FromRecordDecl
          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
       // Add all of the conversion functions as candidates.
-      std::pair<CXXRecordDecl::conversion_iterator,
-                CXXRecordDecl::conversion_iterator>
-        Conversions = FromRecordDecl->getVisibleConversionFunctions();
-      for (CXXRecordDecl::conversion_iterator
-             I = Conversions.first, E = Conversions.second; I != E; ++I) {
+      const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
+      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
         DeclAccessPair FoundDecl = I.getPair();
         NamedDecl *D = FoundDecl.getDecl();
         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
@@ -3129,8 +3138,10 @@
   bool HadMultipleCandidates = (CandidateSet.size() > 1);
 
   OverloadCandidateSet::iterator Best;
-  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
+  switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
+                                                        Best, true)) {
   case OR_Success:
+  case OR_Deleted:
     // Record the standard conversion we used and the conversion function.
     if (CXXConstructorDecl *Constructor
           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
@@ -3158,7 +3169,7 @@
       User.After.setAsIdentityConversion();
       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
       User.After.setAllToTypes(ToType);
-      return OR_Success;
+      return Result;
     }
     if (CXXConversionDecl *Conversion
                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
@@ -3184,15 +3195,12 @@
       //   user-defined conversion sequence (see 13.3.3 and
       //   13.3.3.1).
       User.After = Best->FinalConversion;
-      return OR_Success;
+      return Result;
     }
     llvm_unreachable("Not a constructor or conversion function?");
 
   case OR_No_Viable_Function:
     return OR_No_Viable_Function;
-  case OR_Deleted:
-    // No conversion here! We're done.
-    return OR_Deleted;
 
   case OR_Ambiguous:
     return OR_Ambiguous;
@@ -3329,7 +3337,26 @@
   // Two implicit conversion sequences of the same form are
   // indistinguishable conversion sequences unless one of the
   // following rules apply: (C++ 13.3.3.2p3):
+  
+  // List-initialization sequence L1 is a better conversion sequence than
+  // list-initialization sequence L2 if:
+  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
+  //   if not that,
+  // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
+  //   and N1 is smaller than N2.,
+  // even if one of the other rules in this paragraph would otherwise apply.
+  if (!ICS1.isBad()) {
+    if (ICS1.isStdInitializerListElement() &&
+        !ICS2.isStdInitializerListElement())
+      return ImplicitConversionSequence::Better;
+    if (!ICS1.isStdInitializerListElement() &&
+        ICS2.isStdInitializerListElement())
+      return ImplicitConversionSequence::Worse;
+  }
+
   if (ICS1.isStandard())
+    // Standard conversion sequence S1 is a better conversion sequence than
+    // standard conversion sequence S2 if [...]
     Result = CompareStandardConversionSequences(S,
                                                 ICS1.Standard, ICS2.Standard);
   else if (ICS1.isUserDefined()) {
@@ -3350,19 +3377,6 @@
                                           ICS2.UserDefined.ConversionFunction);
   }
 
-  // List-initialization sequence L1 is a better conversion sequence than
-  // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
-  // for some X and L2 does not.
-  if (Result == ImplicitConversionSequence::Indistinguishable &&
-      !ICS1.isBad()) {
-    if (ICS1.isStdInitializerListElement() &&
-        !ICS2.isStdInitializerListElement())
-      return ImplicitConversionSequence::Better;
-    if (!ICS1.isStdInitializerListElement() &&
-        ICS2.isStdInitializerListElement())
-      return ImplicitConversionSequence::Worse;
-  }
-
   return Result;
 }
 
@@ -4034,11 +4048,8 @@
     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
 
   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
-  std::pair<CXXRecordDecl::conversion_iterator,
-            CXXRecordDecl::conversion_iterator>
-    Conversions = T2RecordDecl->getVisibleConversionFunctions();
-  for (CXXRecordDecl::conversion_iterator
-         I = Conversions.first, E = Conversions.second; I != E; ++I) {
+  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
+  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
     NamedDecl *D = *I;
     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
     if (isa<UsingShadowDecl>(D))
@@ -4254,16 +4265,6 @@
   //     -- Otherwise, the reference shall be an lvalue reference to a
   //        non-volatile const type (i.e., cv1 shall be const), or the reference
   //        shall be an rvalue reference.
-  //
-  // We actually handle one oddity of C++ [over.ics.ref] at this
-  // point, which is that, due to p2 (which short-circuits reference
-  // binding by only attempting a simple conversion for non-direct
-  // bindings) and p3's strange wording, we allow a const volatile
-  // reference to bind to an rvalue. Hence the check for the presence
-  // of "const" rather than checking for "const" being the only
-  // qualifier.
-  // This is also the point where rvalue references and lvalue inits no longer
-  // go together.
   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
     return ICS;
 
@@ -4456,11 +4457,57 @@
   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
     return Result;
 
+  // Per DR1467:
+  //   If the parameter type is a class X and the initializer list has a single
+  //   element of type cv U, where U is X or a class derived from X, the
+  //   implicit conversion sequence is the one required to convert the element
+  //   to the parameter type.
+  //
+  //   Otherwise, if the parameter type is a character array [... ]
+  //   and the initializer list has a single element that is an
+  //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
+  //   implicit conversion sequence is the identity conversion.
+  if (From->getNumInits() == 1) {
+    if (ToType->isRecordType()) {
+      QualType InitType = From->getInit(0)->getType();
+      if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
+          S.IsDerivedFrom(InitType, ToType))
+        return TryCopyInitialization(S, From->getInit(0), ToType,
+                                     SuppressUserConversions,
+                                     InOverloadResolution,
+                                     AllowObjCWritebackConversion);
+    }
+    // FIXME: Check the other conditions here: array of character type,
+    // initializer is a string literal.
+    if (ToType->isArrayType()) {
+      InitializedEntity Entity =
+        InitializedEntity::InitializeParameter(S.Context, ToType,
+                                               /*Consumed=*/false);
+      if (S.CanPerformCopyInitialization(Entity, From)) {
+        Result.setStandard();
+        Result.Standard.setAsIdentityConversion();
+        Result.Standard.setFromType(ToType);
+        Result.Standard.setAllToTypes(ToType);
+        return Result;
+      }
+    }
+  }
+
+  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
   // C++11 [over.ics.list]p2:
   //   If the parameter type is std::initializer_list<X> or "array of X" and
   //   all the elements can be implicitly converted to X, the implicit
   //   conversion sequence is the worst conversion necessary to convert an
   //   element of the list to X.
+  //
+  // C++14 [over.ics.list]p3:
+  //   Otherwise, if the parameter type is "array of N X", if the initializer
+  //   list has exactly N elements or if it has fewer than N elements and X is
+  //   default-constructible, and if all the elements of the initializer list
+  //   can be implicitly converted to X, the implicit conversion sequence is
+  //   the worst conversion necessary to convert an element of the list to X.
+  //
+  // FIXME: We're missing a lot of these checks.
   bool toStdInitializerList = false;
   QualType X;
   if (ToType->isArrayType())
@@ -4499,6 +4546,7 @@
     return Result;
   }
 
+  // C++14 [over.ics.list]p4:
   // C++11 [over.ics.list]p3:
   //   Otherwise, if the parameter is a non-aggregate class X and overload
   //   resolution chooses a single best constructor [...] the implicit
@@ -4514,6 +4562,7 @@
                                     /*AllowObjCConversionOnExplicit=*/false);
   }
 
+  // C++14 [over.ics.list]p5:
   // C++11 [over.ics.list]p4:
   //   Otherwise, if the parameter has an aggregate type which can be
   //   initialized from the initializer list [...] the implicit conversion
@@ -4540,6 +4589,7 @@
     return Result;
   }
 
+  // C++14 [over.ics.list]p6:
   // C++11 [over.ics.list]p5:
   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
   if (ToType->isReferenceType()) {
@@ -4608,14 +4658,15 @@
     return Result;
   }
 
+  // C++14 [over.ics.list]p7:
   // C++11 [over.ics.list]p6:
   //   Otherwise, if the parameter type is not a class:
   if (!ToType->isRecordType()) {
-    //    - if the initializer list has one element, the implicit conversion
-    //      sequence is the one required to convert the element to the
-    //      parameter type.
+    //    - if the initializer list has one element that is not itself an
+    //      initializer list, the implicit conversion sequence is the one
+    //      required to convert the element to the parameter type.
     unsigned NumInits = From->getNumInits();
-    if (NumInits == 1)
+    if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
       Result = TryCopyInitialization(S, From->getInit(0), ToType,
                                      SuppressUserConversions,
                                      InOverloadResolution,
@@ -4631,6 +4682,7 @@
     return Result;
   }
 
+  // C++14 [over.ics.list]p8:
   // C++11 [over.ics.list]p7:
   //   In all cases other than those enumerated above, no conversion is possible
   return Result;
@@ -4894,41 +4946,51 @@
   // conversions are fine.
   switch (SCS.Second) {
   case ICK_Identity:
+  case ICK_NoReturn_Adjustment:
   case ICK_Integral_Promotion:
-  case ICK_Integral_Conversion:
-  case ICK_Zero_Event_Conversion:
+  case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
     return true;
 
   case ICK_Boolean_Conversion:
     // Conversion from an integral or unscoped enumeration type to bool is
-    // classified as ICK_Boolean_Conversion, but it's also an integral
-    // conversion, so it's permitted in a converted constant expression.
+    // classified as ICK_Boolean_Conversion, but it's also arguably an integral
+    // conversion, so we allow it in a converted constant expression.
+    //
+    // FIXME: Per core issue 1407, we should not allow this, but that breaks
+    // a lot of popular code. We should at least add a warning for this
+    // (non-conforming) extension.
     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
            SCS.getToType(2)->isBooleanType();
 
+  case ICK_Pointer_Conversion:
+  case ICK_Pointer_Member:
+    // C++1z: null pointer conversions and null member pointer conversions are
+    // only permitted if the source type is std::nullptr_t.
+    return SCS.getFromType()->isNullPtrType();
+
+  case ICK_Floating_Promotion:
+  case ICK_Complex_Promotion:
+  case ICK_Floating_Conversion:
+  case ICK_Complex_Conversion:
   case ICK_Floating_Integral:
+  case ICK_Compatible_Conversion:
+  case ICK_Derived_To_Base:
+  case ICK_Vector_Conversion:
+  case ICK_Vector_Splat:
   case ICK_Complex_Real:
+  case ICK_Block_Pointer_Conversion:
+  case ICK_TransparentUnionConversion:
+  case ICK_Writeback_Conversion:
+  case ICK_Zero_Event_Conversion:
     return false;
 
   case ICK_Lvalue_To_Rvalue:
   case ICK_Array_To_Pointer:
   case ICK_Function_To_Pointer:
-  case ICK_NoReturn_Adjustment:
+    llvm_unreachable("found a first conversion kind in Second");
+
   case ICK_Qualification:
-  case ICK_Compatible_Conversion:
-  case ICK_Vector_Conversion:
-  case ICK_Vector_Splat:
-  case ICK_Derived_To_Base:
-  case ICK_Pointer_Conversion:
-  case ICK_Pointer_Member:
-  case ICK_Block_Pointer_Conversion:
-  case ICK_Writeback_Conversion:
-  case ICK_Floating_Promotion:
-  case ICK_Complex_Promotion:
-  case ICK_Complex_Conversion:
-  case ICK_Floating_Conversion:
-  case ICK_TransparentUnionConversion:
-    llvm_unreachable("unexpected second conversion kind");
+    llvm_unreachable("found a third conversion kind in Second");
 
   case ICK_Num_Conversion_Kinds:
     break;
@@ -4940,67 +5002,71 @@
 /// CheckConvertedConstantExpression - Check that the expression From is a
 /// converted constant expression of type T, perform the conversion and produce
 /// the converted expression, per C++11 [expr.const]p3.
-ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
-                                                  llvm::APSInt &Value,
-                                                  CCEKind CCE) {
-  assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
-  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
+static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
+                                                   QualType T, APValue &Value,
+                                                   Sema::CCEKind CCE,
+                                                   bool RequireInt) {
+  assert(S.getLangOpts().CPlusPlus11 &&
+         "converted constant expression outside C++11");
 
-  if (checkPlaceholderForOverload(*this, From))
+  if (checkPlaceholderForOverload(S, From))
     return ExprError();
 
-  // C++11 [expr.const]p3 with proposed wording fixes:
-  //  A converted constant expression of type T is a core constant expression,
-  //  implicitly converted to a prvalue of type T, where the converted
-  //  expression is a literal constant expression and the implicit conversion
-  //  sequence contains only user-defined conversions, lvalue-to-rvalue
-  //  conversions, integral promotions, and integral conversions other than
-  //  narrowing conversions.
+  // C++1z [expr.const]p3:
+  //  A converted constant expression of type T is an expression,
+  //  implicitly converted to type T, where the converted
+  //  expression is a constant expression and the implicit conversion
+  //  sequence contains only [... list of conversions ...].
   ImplicitConversionSequence ICS =
-    TryImplicitConversion(From, T,
+    TryCopyInitialization(S, From, T,
                           /*SuppressUserConversions=*/false,
-                          /*AllowExplicit=*/false,
                           /*InOverloadResolution=*/false,
-                          /*CStyle=*/false,
-                          /*AllowObjcWritebackConversion=*/false);
+                          /*AllowObjcWritebackConversion=*/false,
+                          /*AllowExplicit=*/false);
   StandardConversionSequence *SCS = nullptr;
   switch (ICS.getKind()) {
   case ImplicitConversionSequence::StandardConversion:
-    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
-      return Diag(From->getLocStart(),
-                  diag::err_typecheck_converted_constant_expression_disallowed)
-               << From->getType() << From->getSourceRange() << T;
     SCS = &ICS.Standard;
     break;
   case ImplicitConversionSequence::UserDefinedConversion:
-    // We are converting from class type to an integral or enumeration type, so
-    // the Before sequence must be trivial.
-    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
-      return Diag(From->getLocStart(),
-                  diag::err_typecheck_converted_constant_expression_disallowed)
-               << From->getType() << From->getSourceRange() << T;
+    // We are converting to a non-class type, so the Before sequence
+    // must be trivial.
     SCS = &ICS.UserDefined.After;
     break;
   case ImplicitConversionSequence::AmbiguousConversion:
   case ImplicitConversionSequence::BadConversion:
-    if (!DiagnoseMultipleUserDefinedConversion(From, T))
-      return Diag(From->getLocStart(),
-                  diag::err_typecheck_converted_constant_expression)
-                    << From->getType() << From->getSourceRange() << T;
+    if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
+      return S.Diag(From->getLocStart(),
+                    diag::err_typecheck_converted_constant_expression)
+                << From->getType() << From->getSourceRange() << T;
     return ExprError();
 
   case ImplicitConversionSequence::EllipsisConversion:
     llvm_unreachable("ellipsis conversion in converted constant expression");
   }
 
-  ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
+  // Check that we would only use permitted conversions.
+  if (!CheckConvertedConstantConversions(S, *SCS)) {
+    return S.Diag(From->getLocStart(),
+                  diag::err_typecheck_converted_constant_expression_disallowed)
+             << From->getType() << From->getSourceRange() << T;
+  }
+  // [...] and where the reference binding (if any) binds directly.
+  if (SCS->ReferenceBinding && !SCS->DirectBinding) {
+    return S.Diag(From->getLocStart(),
+                  diag::err_typecheck_converted_constant_expression_indirect)
+             << From->getType() << From->getSourceRange() << T;
+  }
+
+  ExprResult Result =
+      S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
   if (Result.isInvalid())
     return Result;
 
   // Check for a narrowing implicit conversion.
   APValue PreNarrowingValue;
   QualType PreNarrowingType;
-  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
+  switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
                                 PreNarrowingType)) {
   case NK_Variable_Narrowing:
     // Implicit conversion to a narrower type, and the value is not a constant
@@ -5009,13 +5075,13 @@
     break;
 
   case NK_Constant_Narrowing:
-    Diag(From->getLocStart(), diag::ext_cce_narrowing)
+    S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
       << CCE << /*Constant*/1
-      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
+      << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
     break;
 
   case NK_Type_Narrowing:
-    Diag(From->getLocStart(), diag::ext_cce_narrowing)
+    S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
       << CCE << /*Constant*/0 << From->getType() << T;
     break;
   }
@@ -5025,12 +5091,15 @@
   Expr::EvalResult Eval;
   Eval.Diag = &Notes;
 
-  if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
+  if ((T->isReferenceType()
+           ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
+           : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
+      (RequireInt && !Eval.Val.isInt())) {
     // The expression can't be folded, so we can't keep it at this position in
     // the AST.
     Result = ExprError();
   } else {
-    Value = Eval.Val.getInt();
+    Value = Eval.Val;
 
     if (Notes.empty()) {
       // It's a constant expression.
@@ -5041,16 +5110,34 @@
   // It's not a constant expression. Produce an appropriate diagnostic.
   if (Notes.size() == 1 &&
       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
-    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
+    S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
   else {
-    Diag(From->getLocStart(), diag::err_expr_not_cce)
+    S.Diag(From->getLocStart(), diag::err_expr_not_cce)
       << CCE << From->getSourceRange();
     for (unsigned I = 0; I < Notes.size(); ++I)
-      Diag(Notes[I].first, Notes[I].second);
+      S.Diag(Notes[I].first, Notes[I].second);
   }
-  return Result;
+  return ExprError();
 }
 
+ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
+                                                  APValue &Value, CCEKind CCE) {
+  return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
+}
+
+ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
+                                                  llvm::APSInt &Value,
+                                                  CCEKind CCE) {
+  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
+
+  APValue V;
+  auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
+  if (!R.isInvalid())
+    Value = V.getInt();
+  return R;
+}
+
+
 /// dropPointerConversions - If the given standard conversion sequence
 /// involves any pointer conversions, remove them.  This may change
 /// the result type of the conversion sequence.
@@ -5312,21 +5399,18 @@
   UnresolvedSet<4>
       ViableConversions; // These are *potentially* viable in C++1y.
   UnresolvedSet<4> ExplicitConversions;
-  std::pair<CXXRecordDecl::conversion_iterator,
-            CXXRecordDecl::conversion_iterator> Conversions =
+  const auto &Conversions =
       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
 
   bool HadMultipleCandidates =
-      (std::distance(Conversions.first, Conversions.second) > 1);
+      (std::distance(Conversions.begin(), Conversions.end()) > 1);
 
   // To check that there is only one target type, in C++1y:
   QualType ToType;
   bool HasUniqueTargetType = true;
 
   // Collect explicit or viable (potentially in C++1y) conversions.
-  for (CXXRecordDecl::conversion_iterator I = Conversions.first,
-                                          E = Conversions.second;
-       I != E; ++I) {
+  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
     NamedDecl *D = (*I)->getUnderlyingDecl();
     CXXConversionDecl *Conversion;
     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
@@ -5519,7 +5603,8 @@
       // is irrelevant.
       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
                          QualType(), Expr::Classification::makeSimpleLValue(),
-                         Args, CandidateSet, SuppressUserConversions);
+                         Args, CandidateSet, SuppressUserConversions,
+                         PartialOverloading);
       return;
     }
     // We treat a constructor like a non-member function, since its object
@@ -5551,18 +5636,6 @@
   // Overload resolution is always an unevaluated context.
   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
 
-  if (Constructor) {
-    // C++ [class.copy]p3:
-    //   A member function template is never instantiated to perform the copy
-    //   of a class object to an object of its class type.
-    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
-    if (Args.size() == 1 &&
-        Constructor->isSpecializationCopyingObject() &&
-        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
-         IsDerivedFrom(Args[0]->getType(), ClassType)))
-      return;
-  }
-
   // Add this candidate
   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
   Candidate.FoundDecl = FoundDecl;
@@ -5572,12 +5645,27 @@
   Candidate.IgnoreObjectArgument = false;
   Candidate.ExplicitCallArguments = Args.size();
 
+  if (Constructor) {
+    // C++ [class.copy]p3:
+    //   A member function template is never instantiated to perform the copy
+    //   of a class object to an object of its class type.
+    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
+    if (Args.size() == 1 &&
+        Constructor->isSpecializationCopyingObject() &&
+        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
+         IsDerivedFrom(Args[0]->getType(), ClassType))) {
+      Candidate.Viable = false;
+      Candidate.FailureKind = ovl_fail_illegal_constructor;
+      return;
+    }
+  }
+
   unsigned NumParams = Proto->getNumParams();
 
   // (C++ 13.3.2p2): A candidate function having fewer than m
   // parameters is viable only if it has an ellipsis in its parameter
   // list (8.3.5).
-  if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
+  if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
       !Proto->isVariadic()) {
     Candidate.Viable = false;
     Candidate.FailureKind = ovl_fail_too_many_arguments;
@@ -5754,6 +5842,7 @@
   // Convert the arguments.
   SmallVector<Expr *, 16> ConvertedArgs;
   bool InitializationFailed = false;
+  bool ContainsValueDependentExpr = false;
   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
         !cast<CXXMethodDecl>(Function)->isStatic() &&
@@ -5766,6 +5855,7 @@
         InitializationFailed = true;
         break;
       }
+      ContainsValueDependentExpr |= R.get()->isValueDependent();
       ConvertedArgs.push_back(R.get());
     } else {
       ExprResult R =
@@ -5778,6 +5868,7 @@
         InitializationFailed = true;
         break;
       }
+      ContainsValueDependentExpr |= R.get()->isValueDependent();
       ConvertedArgs.push_back(R.get());
     }
   }
@@ -5788,9 +5879,16 @@
   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
     APValue Result;
     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
+    if (EIA->getCond()->isValueDependent()) {
+      // Don't even try now, we'll examine it after instantiation.
+      continue;
+    }
+
     if (!EIA->getCond()->EvaluateWithSubstitution(
-            Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) ||
-        !Result.isInt() || !Result.getInt().getBoolValue()) {
+            Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
+      if (!ContainsValueDependentExpr)
+        return EIA;
+    } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
       return EIA;
     }
   }
@@ -5802,8 +5900,9 @@
 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
                                  ArrayRef<Expr *> Args,
                                  OverloadCandidateSet& CandidateSet,
+                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
                                  bool SuppressUserConversions,
-                               TemplateArgumentListInfo *ExplicitTemplateArgs) {
+                                 bool PartialOverloading) {
   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
@@ -5812,10 +5911,10 @@
                            cast<CXXMethodDecl>(FD)->getParent(),
                            Args[0]->getType(), Args[0]->Classify(Context),
                            Args.slice(1), CandidateSet,
-                           SuppressUserConversions);
+                           SuppressUserConversions, PartialOverloading);
       else
         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
-                             SuppressUserConversions);
+                             SuppressUserConversions, PartialOverloading);
     } else {
       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
@@ -5825,11 +5924,13 @@
                                    ExplicitTemplateArgs,
                                    Args[0]->getType(),
                                    Args[0]->Classify(Context), Args.slice(1),
-                                   CandidateSet, SuppressUserConversions);
+                                   CandidateSet, SuppressUserConversions,
+                                   PartialOverloading);
       else
         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
                                      ExplicitTemplateArgs, Args,
-                                     CandidateSet, SuppressUserConversions);
+                                     CandidateSet, SuppressUserConversions,
+                                     PartialOverloading);
     }
   }
 }
@@ -5877,7 +5978,8 @@
                          Expr::Classification ObjectClassification,
                          ArrayRef<Expr *> Args,
                          OverloadCandidateSet &CandidateSet,
-                         bool SuppressUserConversions) {
+                         bool SuppressUserConversions,
+                         bool PartialOverloading) {
   const FunctionProtoType *Proto
     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
   assert(Proto && "Methods without a prototype cannot be overloaded");
@@ -5910,7 +6012,8 @@
   // (C++ 13.3.2p2): A candidate function having fewer than m
   // parameters is viable only if it has an ellipsis in its parameter
   // list (8.3.5).
-  if (Args.size() > NumParams && !Proto->isVariadic()) {
+  if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
+      !Proto->isVariadic()) {
     Candidate.Viable = false;
     Candidate.FailureKind = ovl_fail_too_many_arguments;
     return;
@@ -5922,7 +6025,7 @@
   // parameter list is truncated on the right, so that there are
   // exactly m parameters.
   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
-  if (Args.size() < MinRequiredArgs) {
+  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
     // Not enough arguments.
     Candidate.Viable = false;
     Candidate.FailureKind = ovl_fail_too_few_arguments;
@@ -6004,7 +6107,8 @@
                                  Expr::Classification ObjectClassification,
                                  ArrayRef<Expr *> Args,
                                  OverloadCandidateSet& CandidateSet,
-                                 bool SuppressUserConversions) {
+                                 bool SuppressUserConversions,
+                                 bool PartialOverloading) {
   if (!CandidateSet.isNewCandidate(MethodTmpl))
     return;
 
@@ -6021,7 +6125,7 @@
   FunctionDecl *Specialization = nullptr;
   if (TemplateDeductionResult Result
       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
-                                Specialization, Info)) {
+                                Specialization, Info, PartialOverloading)) {
     OverloadCandidate &Candidate = CandidateSet.addCandidate();
     Candidate.FoundDecl = FoundDecl;
     Candidate.Function = MethodTmpl->getTemplatedDecl();
@@ -6042,7 +6146,7 @@
          "Specialization is not a member function?");
   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
                      ActingContext, ObjectType, ObjectClassification, Args,
-                     CandidateSet, SuppressUserConversions);
+                     CandidateSet, SuppressUserConversions, PartialOverloading);
 }
 
 /// \brief Add a C++ function template specialization as a candidate
@@ -6054,7 +6158,8 @@
                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
                                    ArrayRef<Expr *> Args,
                                    OverloadCandidateSet& CandidateSet,
-                                   bool SuppressUserConversions) {
+                                   bool SuppressUserConversions,
+                                   bool PartialOverloading) {
   if (!CandidateSet.isNewCandidate(FunctionTemplate))
     return;
 
@@ -6071,7 +6176,7 @@
   FunctionDecl *Specialization = nullptr;
   if (TemplateDeductionResult Result
         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
-                                  Specialization, Info)) {
+                                  Specialization, Info, PartialOverloading)) {
     OverloadCandidate &Candidate = CandidateSet.addCandidate();
     Candidate.FoundDecl = FoundDecl;
     Candidate.Function = FunctionTemplate->getTemplatedDecl();
@@ -6089,7 +6194,7 @@
   // deduction as a candidate.
   assert(Specialization && "Missing function template specialization?");
   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
-                       SuppressUserConversions);
+                       SuppressUserConversions, PartialOverloading);
 }
 
 /// Determine whether this is an allowable conversion from the result
@@ -6836,12 +6941,7 @@
       return;
 
     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
-    std::pair<CXXRecordDecl::conversion_iterator,
-              CXXRecordDecl::conversion_iterator>
-      Conversions = ClassDecl->getVisibleConversionFunctions();
-    for (CXXRecordDecl::conversion_iterator
-           I = Conversions.first, E = Conversions.second; I != E; ++I) {
-      NamedDecl *D = I.getDecl();
+    for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
       if (isa<UsingShadowDecl>(D))
         D = cast<UsingShadowDecl>(D)->getTargetDecl();
 
@@ -6905,13 +7005,7 @@
     if (!ClassDecl->hasDefinition())
       return VRQuals;
 
-    std::pair<CXXRecordDecl::conversion_iterator,
-              CXXRecordDecl::conversion_iterator>
-      Conversions = ClassDecl->getVisibleConversionFunctions();
-
-    for (CXXRecordDecl::conversion_iterator
-           I = Conversions.first, E = Conversions.second; I != E; ++I) {
-      NamedDecl *D = I.getDecl();
+    for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
       if (isa<UsingShadowDecl>(D))
         D = cast<UsingShadowDecl>(D)->getTargetDecl();
       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
@@ -8030,7 +8124,7 @@
   bool HasArithmeticOrEnumeralCandidateType = false;
   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
-    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
+    CandidateTypes.emplace_back(*this);
     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
                                                  OpLoc,
                                                  true,
@@ -8243,7 +8337,7 @@
     } else
       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
                                    FoundDecl, ExplicitTemplateArgs,
-                                   Args, CandidateSet);
+                                   Args, CandidateSet, PartialOverloading);
   }
 }
 
@@ -9200,6 +9294,13 @@
   case ovl_fail_bad_deduction:
     return DiagnoseBadDeduction(S, Cand, NumArgs);
 
+  case ovl_fail_illegal_constructor: {
+    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
+      << (Fn->getPrimaryTemplate() ? 1 : 0);
+    MaybeEmitInheritedConstructorNote(S, Fn);
+    return;
+  }
+
   case ovl_fail_trivial_conversion:
   case ovl_fail_bad_final_conversion:
   case ovl_fail_final_conversion_not_exact:
@@ -10308,7 +10409,8 @@
       assert(!KnownValid && "Explicit template arguments?");
       return;
     }
-    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
+    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
+                           /*SuppressUsedConversions=*/false,
                            PartialOverloading);
     return;
   }
@@ -10316,7 +10418,9 @@
   if (FunctionTemplateDecl *FuncTemplate
       = dyn_cast<FunctionTemplateDecl>(Callee)) {
     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
-                                   ExplicitTemplateArgs, Args, CandidateSet);
+                                   ExplicitTemplateArgs, Args, CandidateSet,
+                                   /*SuppressUsedConversions=*/false,
+                                   PartialOverloading);
     return;
   }
 
@@ -10841,7 +10945,7 @@
   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
 
   // Add the candidates from the given function set.
-  AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
+  AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
 
   // Add operator candidates that are member functions.
   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
@@ -11050,7 +11154,7 @@
   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
 
   // Add the candidates from the given function set.
-  AddFunctionCandidates(Fns, Args, CandidateSet, false);
+  AddFunctionCandidates(Fns, Args, CandidateSet);
 
   // Add operator candidates that are member functions.
   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
@@ -11144,7 +11248,12 @@
         // Cut off the implicit 'this'.
         if (isa<CXXMethodDecl>(FnDecl))
           ArgsArray = ArgsArray.slice(1);
-        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 
+
+        // Check for a self move.
+        if (Op == OO_Equal)
+          DiagnoseSelfMove(Args[0], Args[1], OpLoc);
+
+        checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
                   TheCall->getSourceRange(), VariadicDoesNotApply);
 
         return MaybeBindToTemporary(TheCall);
@@ -11486,6 +11595,10 @@
     return MaybeBindToTemporary(call);
   }
 
+  if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
+    return new (Context)
+        CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
+
   UnbridgedCastsSet UnbridgedCasts;
   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
     return ExprError();
@@ -11745,11 +11858,9 @@
   //   functions for each conversion function declared in an
   //   accessible base class provided the function is not hidden
   //   within T by another intervening declaration.
-  std::pair<CXXRecordDecl::conversion_iterator,
-            CXXRecordDecl::conversion_iterator> Conversions
-    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
-  for (CXXRecordDecl::conversion_iterator
-         I = Conversions.first, E = Conversions.second; I != E; ++I) {
+  const auto &Conversions =
+      cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
+  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
     NamedDecl *D = *I;
     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
     if (isa<UsingShadowDecl>(D))
@@ -12094,8 +12205,8 @@
 
   OverloadCandidateSet CandidateSet(UDSuffixLoc,
                                     OverloadCandidateSet::CSK_Normal);
-  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
-                        TemplateArgs);
+  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
+                        /*SuppressUserConversions=*/true);
 
   bool HadMultipleCandidates = (CandidateSet.size() > 1);
 
diff --git a/lib/Sema/SemaPseudoObject.cpp b/lib/Sema/SemaPseudoObject.cpp
index 5e92d5d..935128b 100644
--- a/lib/Sema/SemaPseudoObject.cpp
+++ b/lib/Sema/SemaPseudoObject.cpp
@@ -1051,17 +1051,13 @@
   
   // Look for a conversion to an integral, enumeration type, or
   // objective-C pointer type.
-  std::pair<CXXRecordDecl::conversion_iterator,
-            CXXRecordDecl::conversion_iterator> Conversions
-    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
-  
   int NoIntegrals=0, NoObjCIdPointers=0;
   SmallVector<CXXConversionDecl *, 4> ConversionDecls;
-    
-  for (CXXRecordDecl::conversion_iterator
-         I = Conversions.first, E = Conversions.second; I != E; ++I) {
-    if (CXXConversionDecl *Conversion
-        = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
+
+  for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl())
+                          ->getVisibleConversionFunctions()) {
+    if (CXXConversionDecl *Conversion =
+            dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) {
       QualType CT = Conversion->getConversionType().getNonReferenceType();
       if (CT->isIntegralOrEnumerationType()) {
         ++NoIntegrals;
@@ -1446,7 +1442,7 @@
   ExprResult GetterExpr = S.ActOnMemberAccessExpr(
     S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
     RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
-    GetterName, nullptr, true);
+    GetterName, nullptr);
   if (GetterExpr.isInvalid()) {
     S.Diag(RefExpr->getMemberLoc(),
            diag::error_cannot_find_suitable_accessor) << 0 /* getter */
@@ -1476,7 +1472,7 @@
   ExprResult SetterExpr = S.ActOnMemberAccessExpr(
     S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
     RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
-    SetterName, nullptr, true);
+    SetterName, nullptr);
   if (SetterExpr.isInvalid()) {
     S.Diag(RefExpr->getMemberLoc(),
            diag::error_cannot_find_suitable_accessor) << 1 /* setter */
diff --git a/lib/Sema/SemaStmt.cpp b/lib/Sema/SemaStmt.cpp
index 0b9608a..bc5c155 100644
--- a/lib/Sema/SemaStmt.cpp
+++ b/lib/Sema/SemaStmt.cpp
@@ -265,10 +265,6 @@
         Diag(Loc, diag::warn_unused_result) << R1 << R2;
         return;
       }
-      if (MD->isPropertyAccessor()) {
-        Diag(Loc, diag::warn_unused_property_expr);
-        return;
-      }
     }
   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
     const Expr *Source = POE->getSyntacticForm();
@@ -687,26 +683,39 @@
   }
 }
 
+typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
+
 /// Returns true if we should emit a diagnostic about this case expression not
 /// being a part of the enum used in the switch controlling expression.
-static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
+static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
                                               const EnumDecl *ED,
-                                              const Expr *CaseExpr) {
-  // Don't warn if the 'case' expression refers to a static const variable of
-  // the enum type.
-  CaseExpr = CaseExpr->IgnoreParenImpCasts();
-  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
+                                              const Expr *CaseExpr,
+                                              EnumValsTy::iterator &EI,
+                                              EnumValsTy::iterator &EIEnd,
+                                              const llvm::APSInt &Val) {
+  bool FlagType = ED->hasAttr<FlagEnumAttr>();
+
+  if (const DeclRefExpr *DRE =
+          dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
-      if (!VD->hasGlobalStorage())
-        return true;
       QualType VarType = VD->getType();
-      if (!VarType.isConstQualified())
-        return true;
-      QualType EnumType = Ctx.getTypeDeclType(ED);
-      if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
+      QualType EnumType = S.Context.getTypeDeclType(ED);
+      if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
+          S.Context.hasSameUnqualifiedType(EnumType, VarType))
         return false;
     }
   }
+
+  if (FlagType) {
+    return !S.IsValueInFlagEnum(ED, Val, false);
+  } else {
+    while (EI != EIEnd && EI->first < Val)
+      EI++;
+
+    if (EI != EIEnd && EI->first == Val)
+      return false;
+  }
+
   return true;
 }
 
@@ -717,9 +726,10 @@
   assert(SS == getCurFunction()->SwitchStack.back() &&
          "switch stack missing push/pop!");
 
+  getCurFunction()->SwitchStack.pop_back();
+
   if (!BodyStmt) return StmtError();
   SS->setBody(BodyStmt, SwitchLoc);
-  getCurFunction()->SwitchStack.pop_back();
 
   Expr *CondExpr = SS->getCond();
   if (!CondExpr) return StmtError();
@@ -1045,8 +1055,6 @@
     // If switch has default case, then ignore it.
     if (!CaseListIsErroneous  && !HasConstantCond && ET) {
       const EnumDecl *ED = ET->getDecl();
-      typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
-        EnumValsTy;
       EnumValsTy EnumVals;
 
       // Gather all enum values, set their type and sort them,
@@ -1057,57 +1065,48 @@
         EnumVals.push_back(std::make_pair(Val, EDI));
       }
       std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
-      EnumValsTy::iterator EIend =
+      auto EI = EnumVals.begin(), EIEnd =
         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
 
       // See which case values aren't in enum.
-      EnumValsTy::const_iterator EI = EnumVals.begin();
       for (CaseValsTy::const_iterator CI = CaseVals.begin();
-           CI != CaseVals.end(); CI++) {
-        while (EI != EIend && EI->first < CI->first)
-          EI++;
-        if (EI == EIend || EI->first > CI->first) {
-          Expr *CaseExpr = CI->second->getLHS();
-          if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
-            Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
-              << CondTypeBeforePromotion;
-        }
+          CI != CaseVals.end(); CI++) {
+        Expr *CaseExpr = CI->second->getLHS();
+        if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
+                                              CI->first))
+          Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
+            << CondTypeBeforePromotion;
       }
+
       // See which of case ranges aren't in enum
       EI = EnumVals.begin();
       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
-           RI != CaseRanges.end() && EI != EIend; RI++) {
-        while (EI != EIend && EI->first < RI->first)
-          EI++;
-
-        if (EI == EIend || EI->first != RI->first) {
-          Expr *CaseExpr = RI->second->getLHS();
-          if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
-            Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
-              << CondTypeBeforePromotion;
-        }
+          RI != CaseRanges.end(); RI++) {
+        Expr *CaseExpr = RI->second->getLHS();
+        if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
+                                              RI->first))
+          Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
+            << CondTypeBeforePromotion;
 
         llvm::APSInt Hi =
           RI->second->getRHS()->EvaluateKnownConstInt(Context);
         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
-        while (EI != EIend && EI->first < Hi)
-          EI++;
-        if (EI == EIend || EI->first != Hi) {
-          Expr *CaseExpr = RI->second->getRHS();
-          if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
-            Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
-              << CondTypeBeforePromotion;
-        }
+
+        CaseExpr = RI->second->getRHS();
+        if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
+                                              Hi))
+          Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
+            << CondTypeBeforePromotion;
       }
 
       // Check which enum vals aren't in switch
-      CaseValsTy::const_iterator CI = CaseVals.begin();
-      CaseRangesTy::const_iterator RI = CaseRanges.begin();
+      auto CI = CaseVals.begin();
+      auto RI = CaseRanges.begin();
       bool hasCasesNotInSwitch = false;
 
       SmallVector<DeclarationName,8> UnhandledNames;
 
-      for (EI = EnumVals.begin(); EI != EIend; EI++){
+      for (EI = EnumVals.begin(); EI != EIEnd; EI++){
         // Drop unneeded case values
         while (CI != CaseVals.end() && CI->first < EI->first)
           CI++;
@@ -1194,30 +1193,37 @@
         llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
         AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
         const EnumDecl *ED = ET->getDecl();
-        typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
-            EnumValsTy;
-        EnumValsTy EnumVals;
 
-        // Gather all enum values, set their type and sort them,
-        // allowing easier comparison with rhs constant.
-        for (auto *EDI : ED->enumerators()) {
-          llvm::APSInt Val = EDI->getInitVal();
-          AdjustAPSInt(Val, DstWidth, DstIsSigned);
-          EnumVals.push_back(std::make_pair(Val, EDI));
-        }
-        if (EnumVals.empty())
-          return;
-        std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
-        EnumValsTy::iterator EIend =
-            std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
-
-        // See which values aren't in the enum.
-        EnumValsTy::const_iterator EI = EnumVals.begin();
-        while (EI != EIend && EI->first < RhsVal)
-          EI++;
-        if (EI == EIend || EI->first != RhsVal) {
-          Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
+        if (ED->hasAttr<FlagEnumAttr>()) {
+          if (!IsValueInFlagEnum(ED, RhsVal, true))
+            Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
               << DstType.getUnqualifiedType();
+        } else {
+          typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
+              EnumValsTy;
+          EnumValsTy EnumVals;
+
+          // Gather all enum values, set their type and sort them,
+          // allowing easier comparison with rhs constant.
+          for (auto *EDI : ED->enumerators()) {
+            llvm::APSInt Val = EDI->getInitVal();
+            AdjustAPSInt(Val, DstWidth, DstIsSigned);
+            EnumVals.push_back(std::make_pair(Val, EDI));
+          }
+          if (EnumVals.empty())
+            return;
+          std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
+          EnumValsTy::iterator EIend =
+              std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
+
+          // See which values aren't in the enum.
+          EnumValsTy::const_iterator EI = EnumVals.begin();
+          while (EI != EIend && EI->first < RhsVal)
+            EI++;
+          if (EI == EIend || EI->first != RhsVal) {
+            Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
+                << DstType.getUnqualifiedType();
+          }
         }
       }
     }
@@ -1676,11 +1682,16 @@
   if (!collection)
     return ExprError();
 
+  ExprResult result = CorrectDelayedTyposInExpr(collection);
+  if (!result.isUsable())
+    return ExprError();
+  collection = result.get();
+
   // Bail out early if we've got a type-dependent expression.
   if (collection->isTypeDependent()) return collection;
 
   // Perform normal l-value conversion.
-  ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
+  result = DefaultFunctionArrayLvalueConversion(collection);
   if (result.isInvalid())
     return ExprError();
   collection = result.get();
@@ -2469,7 +2480,7 @@
   // - in a return statement in a function [where] ...
   // ... the expression is the name of a non-volatile automatic object ...
   DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
-  if (!DR || DR->refersToEnclosingLocal())
+  if (!DR || DR->refersToEnclosingVariableOrCapture())
     return nullptr;
   VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
   if (!VD)
@@ -2637,8 +2648,12 @@
         return StmtError();
       RetValExp = Result.get();
 
+      // DR1048: even prior to C++14, we should use the 'auto' deduction rules
+      // when deducing a return type for a lambda-expression (or by extension
+      // for a block). These rules differ from the stated C++11 rules only in
+      // that they remove top-level cv-qualifiers.
       if (!CurContext->isDependentContext())
-        FnRetType = RetValExp->getType();
+        FnRetType = RetValExp->getType().getUnqualifiedType();
       else
         FnRetType = CurCap->ReturnType = Context.DependentTy;
     } else {
@@ -3025,14 +3040,26 @@
 
     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
   } else if (!RetValExp && !HasDependentReturnType) {
-    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
-    // C99 6.8.6.4p1 (ext_ since GCC warns)
-    if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
+    FunctionDecl *FD = getCurFunctionDecl();
 
-    if (FunctionDecl *FD = getCurFunctionDecl())
+    unsigned DiagID;
+    if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
+      // C++11 [stmt.return]p2
+      DiagID = diag::err_constexpr_return_missing_expr;
+      FD->setInvalidDecl();
+    } else if (getLangOpts().C99) {
+      // C99 6.8.6.4p1 (ext_ since GCC warns)
+      DiagID = diag::ext_return_missing_expr;
+    } else {
+      // C90 6.6.6.4p4
+      DiagID = diag::warn_return_missing_expr;
+    }
+
+    if (FD)
       Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
     else
       Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
+
     Result = new (Context) ReturnStmt(ReturnLoc);
   } else {
     assert(RetValExp || HasDependentReturnType);
@@ -3272,6 +3299,14 @@
   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
     Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
 
+  sema::FunctionScopeInfo *FSI = getCurFunction();
+
+  // C++ try is incompatible with SEH __try.
+  if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
+    Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
+    Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
+  }
+
   const unsigned NumHandlers = Handlers.size();
   assert(NumHandlers > 0 &&
          "The parser shouldn't call this if there are no handlers.");
@@ -3314,7 +3349,7 @@
     }
   }
 
-  getCurFunction()->setHasBranchProtectedScope();
+  FSI->setHasCXXTry(TryLoc);
 
   // FIXME: We should detect handlers that cannot catch anything because an
   // earlier handler catches a superclass. Need to find a method that is not
@@ -3325,16 +3360,35 @@
   return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
 }
 
-StmtResult
-Sema::ActOnSEHTryBlock(bool IsCXXTry,
-                       SourceLocation TryLoc,
-                       Stmt *TryBlock,
-                       Stmt *Handler) {
+StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
+                                  Stmt *TryBlock, Stmt *Handler) {
   assert(TryBlock && Handler);
 
-  getCurFunction()->setHasBranchProtectedScope();
+  sema::FunctionScopeInfo *FSI = getCurFunction();
 
-  return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
+  // SEH __try is incompatible with C++ try. Borland appears to support this,
+  // however.
+  if (!getLangOpts().Borland) {
+    if (FSI->FirstCXXTryLoc.isValid()) {
+      Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
+      Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
+    }
+  }
+
+  FSI->setHasSEHTry(TryLoc);
+
+  // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
+  // track if they use SEH.
+  DeclContext *DC = CurContext;
+  while (DC && !DC->isFunctionOrMethod())
+    DC = DC->getParent();
+  FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
+  if (FD)
+    FD->setUsesSEHTry(true);
+  else
+    Diag(TryLoc, diag::err_seh_try_outside_functions);
+
+  return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
 }
 
 StmtResult
diff --git a/lib/Sema/SemaStmtAsm.cpp b/lib/Sema/SemaStmtAsm.cpp
index a2e436a..c091cf8 100644
--- a/lib/Sema/SemaStmtAsm.cpp
+++ b/lib/Sema/SemaStmtAsm.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Sema/SemaInternal.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/TargetInfo.h"
@@ -86,6 +87,11 @@
   WorkList.push_back(E);
   while (WorkList.size()) {
     Expr *E = WorkList.pop_back_val();
+    if (isa<CXXThisExpr>(E)) {
+      S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref);
+      S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
+      return true;
+    }
     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
       if (isa<ParmVarDecl>(DRE->getDecl())) {
         S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
@@ -116,15 +122,11 @@
   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
 
   // The parser verifies that there is a string literal here.
-  if (!AsmString->isAscii())
-    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
-      << AsmString->getSourceRange());
+  assert(AsmString->isAscii());
 
   for (unsigned i = 0; i != NumOutputs; i++) {
     StringLiteral *Literal = Constraints[i];
-    if (!Literal->isAscii())
-      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
-        << Literal->getSourceRange());
+    assert(Literal->isAscii());
 
     StringRef OutputName;
     if (Names[i])
@@ -136,31 +138,57 @@
                             diag::err_asm_invalid_output_constraint)
                        << Info.getConstraintStr());
 
+    ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
+    if (ER.isInvalid())
+      return StmtError();
+    Exprs[i] = ER.get();
+
     // Check that the output exprs are valid lvalues.
     Expr *OutputExpr = Exprs[i];
-    if (CheckAsmLValue(OutputExpr, *this))
-      return StmtError(Diag(OutputExpr->getLocStart(),
-                            diag::err_asm_invalid_lvalue_in_output)
-                       << OutputExpr->getSourceRange());
 
     // Referring to parameters is not allowed in naked functions.
     if (CheckNakedParmReference(OutputExpr, *this))
       return StmtError();
 
-    if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
-                            diag::err_dereference_incomplete_type))
-      return StmtError();
-
     OutputConstraintInfos.push_back(Info);
 
-    const Type *Ty = OutputExpr->getType().getTypePtr();
-
-    // If this is a dependent type, just continue. We don't know the size of a
-    // dependent type.
-    if (Ty->isDependentType())
+    // If this is dependent, just continue.
+    if (OutputExpr->isTypeDependent())
       continue;
 
-    unsigned Size = Context.getTypeSize(Ty);
+    Expr::isModifiableLvalueResult IsLV =
+        OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
+    switch (IsLV) {
+    case Expr::MLV_Valid:
+      // Cool, this is an lvalue.
+      break;
+    case Expr::MLV_ArrayType:
+      // This is OK too.
+      break;
+    case Expr::MLV_LValueCast: {
+      const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
+      if (!getLangOpts().HeinousExtensions) {
+        Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
+            << OutputExpr->getSourceRange();
+      } else {
+        Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
+            << OutputExpr->getSourceRange();
+      }
+      // Accept, even if we emitted an error diagnostic.
+      break;
+    }
+    case Expr::MLV_IncompleteType:
+    case Expr::MLV_IncompleteVoidType:
+      if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
+                              diag::err_dereference_incomplete_type))
+        return StmtError();
+    default:
+      return StmtError(Diag(OutputExpr->getLocStart(),
+                            diag::err_asm_invalid_lvalue_in_output)
+                       << OutputExpr->getSourceRange());
+    }
+
+    unsigned Size = Context.getTypeSize(OutputExpr->getType());
     if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
                                                     Size))
       return StmtError(Diag(OutputExpr->getLocStart(),
@@ -172,9 +200,7 @@
 
   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
     StringLiteral *Literal = Constraints[i];
-    if (!Literal->isAscii())
-      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
-        << Literal->getSourceRange());
+    assert(Literal->isAscii());
 
     StringRef InputName;
     if (Names[i])
@@ -188,6 +214,11 @@
                        << Info.getConstraintStr());
     }
 
+    ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
+    if (ER.isInvalid())
+      return StmtError();
+    Exprs[i] = ER.get();
+
     Expr *InputExpr = Exprs[i];
 
     // Referring to parameters is not allowed in naked functions.
@@ -201,6 +232,19 @@
                               diag::err_asm_invalid_lvalue_in_input)
                          << Info.getConstraintStr()
                          << InputExpr->getSourceRange());
+    } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
+      llvm::APSInt Result;
+      if (!InputExpr->EvaluateAsInt(Result, Context))
+        return StmtError(
+            Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
+            << Info.getConstraintStr() << InputExpr->getSourceRange());
+      if (Result.slt(Info.getImmConstantMin()) ||
+          Result.sgt(Info.getImmConstantMax()))
+        return StmtError(Diag(InputExpr->getLocStart(),
+                              diag::err_invalid_asm_value_for_constraint)
+                         << Result.toString(10) << Info.getConstraintStr()
+                         << InputExpr->getSourceRange());
+
     } else {
       ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
       if (Result.isInvalid())
@@ -240,9 +284,7 @@
   // Check that the clobbers are valid.
   for (unsigned i = 0; i != NumClobbers; i++) {
     StringLiteral *Literal = Clobbers[i];
-    if (!Literal->isAscii())
-      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
-        << Literal->getSourceRange());
+    assert(Literal->isAscii());
 
     StringRef Clobber = Literal->getString();
 
@@ -271,32 +313,22 @@
     if (!Piece.isOperand()) continue;
 
     // Look for the correct constraint index.
-    unsigned Idx = 0;
-    unsigned ConstraintIdx = 0;
-    for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
-      TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
-      if (Idx == Piece.getOperandNo())
-        break;
-      ++Idx;
+    unsigned ConstraintIdx = Piece.getOperandNo();
+    unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
 
-      if (Info.isReadWrite()) {
-        if (Idx == Piece.getOperandNo())
+    // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
+    // modifier '+'.
+    if (ConstraintIdx >= NumOperands) {
+      unsigned I = 0, E = NS->getNumOutputs();
+
+      for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
+        if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
+          ConstraintIdx = I;
           break;
-        ++Idx;
-      }
-    }
+        }
 
-    for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
-      TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
-      if (Idx == Piece.getOperandNo())
-        break;
-      ++Idx;
-
-      if (Info.isReadWrite()) {
-        if (Idx == Piece.getOperandNo())
-          break;
-        ++Idx;
-      }
+      assert(I != E && "Invalid operand number should have been caught in "
+                       " AnalyzeAsmString");
     }
 
     // Now that we have the right indexes go ahead and check.
@@ -325,8 +357,28 @@
   }
 
   // Validate tied input operands for type mismatches.
+  unsigned NumAlternatives = ~0U;
+  for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
+    TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
+    StringRef ConstraintStr = Info.getConstraintStr();
+    unsigned AltCount = ConstraintStr.count(',') + 1;
+    if (NumAlternatives == ~0U)
+      NumAlternatives = AltCount;
+    else if (NumAlternatives != AltCount)
+      return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
+                            diag::err_asm_unexpected_constraint_alternatives)
+                       << NumAlternatives << AltCount);
+  }
   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
+    StringRef ConstraintStr = Info.getConstraintStr();
+    unsigned AltCount = ConstraintStr.count(',') + 1;
+    if (NumAlternatives == ~0U)
+      NumAlternatives = AltCount;
+    else if (NumAlternatives != AltCount)
+      return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
+                            diag::err_asm_unexpected_constraint_alternatives)
+                       << NumAlternatives << AltCount);
 
     // If this is a tied constraint, verify that the output and input have
     // either exactly the same type, or that they are int/ptr operands with the
diff --git a/lib/Sema/SemaTemplate.cpp b/lib/Sema/SemaTemplate.cpp
index 08ab0a0..6cba79a 100644
--- a/lib/Sema/SemaTemplate.cpp
+++ b/lib/Sema/SemaTemplate.cpp
@@ -651,12 +651,8 @@
   //   A non-type template-parameter of type "array of T" or
   //   "function returning T" is adjusted to be of type "pointer to
   //   T" or "pointer to function returning T", respectively.
-  else if (T->isArrayType())
-    // FIXME: Keep the type prior to promotion?
-    return Context.getArrayDecayedType(T);
-  else if (T->isFunctionType())
-    // FIXME: Keep the type prior to promotion?
-    return Context.getPointerType(T);
+  else if (T->isArrayType() || T->isFunctionType())
+    return Context.getDecayedType(T);
 
   Diag(Loc, diag::err_template_nontype_parm_bad_type)
     << T;
@@ -719,7 +715,8 @@
       return Param;
 
     TemplateArgument Converted;
-    ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
+    ExprResult DefaultRes =
+        CheckTemplateArgument(Param, Param->getType(), Default, Converted);
     if (DefaultRes.isInvalid()) {
       Param->setInvalidDecl();
       return Param;
@@ -1801,7 +1798,7 @@
       }
     } else if (const TemplateSpecializationType *TST
                                      = T->getAs<TemplateSpecializationType>()) {
-      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {        
+      if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
         ExpectedTemplateParams = Template->getTemplateParameters();
         NeedNonemptyTemplateHeader = true;        
       }
@@ -3358,7 +3355,7 @@
 /// \param Param The template parameter against which the argument will be
 /// checked.
 ///
-/// \param Arg The template argument.
+/// \param Arg The template argument, which may be updated due to conversions.
 ///
 /// \param Template The template in which the template argument resides.
 ///
@@ -3436,6 +3433,13 @@
       if (Res.isInvalid())
         return true;
 
+      // If the resulting expression is new, then use it in place of the
+      // old expression in the template argument.
+      if (Res.get() != Arg.getArgument().getAsExpr()) {
+        TemplateArgument TA(Res.get());
+        Arg = TemplateArgumentLoc(TA, Res.get());
+      }
+
       Converted.push_back(Result);
       break;
     }
@@ -3643,9 +3647,14 @@
                                      TemplateArgumentListInfo &TemplateArgs,
                                      bool PartialTemplateArgs,
                           SmallVectorImpl<TemplateArgument> &Converted) {
+  // Make a copy of the template arguments for processing.  Only make the
+  // changes at the end when successful in matching the arguments to the
+  // template.
+  TemplateArgumentListInfo NewArgs = TemplateArgs;
+
   TemplateParameterList *Params = Template->getTemplateParameters();
 
-  SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
+  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
 
   // C++ [temp.arg]p1:
   //   [...] The type and form of each template-argument specified in
@@ -3654,7 +3663,7 @@
   //   template-parameter-list.
   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
   SmallVector<TemplateArgument, 2> ArgumentPack;
-  unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
+  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
   LocalInstantiationScope InstScope(*this, true);
   for (TemplateParameterList::iterator Param = Params->begin(),
                                        ParamEnd = Params->end();
@@ -3690,21 +3699,21 @@
 
     if (ArgIdx < NumArgs) {
       // Check the template argument we were given.
-      if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
+      if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
                                 TemplateLoc, RAngleLoc,
                                 ArgumentPack.size(), Converted))
         return true;
 
       bool PackExpansionIntoNonPack =
-          TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
+          NewArgs[ArgIdx].getArgument().isPackExpansion() &&
           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
       if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
         // Core issue 1430: we have a pack expansion as an argument to an
         // alias template, and it's not part of a parameter pack. This
         // can't be canonicalized, so reject it now.
-        Diag(TemplateArgs[ArgIdx].getLocation(),
+        Diag(NewArgs[ArgIdx].getLocation(),
              diag::err_alias_template_expansion_into_fixed_list)
-          << TemplateArgs[ArgIdx].getSourceRange();
+          << NewArgs[ArgIdx].getSourceRange();
         Diag((*Param)->getLocation(), diag::note_template_param_here);
         return true;
       }
@@ -3736,7 +3745,7 @@
         }
 
         while (ArgIdx < NumArgs) {
-          Converted.push_back(TemplateArgs[ArgIdx].getArgument());
+          Converted.push_back(NewArgs[ArgIdx].getArgument());
           ++ArgIdx;
         }
 
@@ -3787,8 +3796,7 @@
     // the default argument.
     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
       if (!TTP->hasDefaultArgument())
-        return diagnoseArityMismatch(*this, Template, TemplateLoc, 
-                                     TemplateArgs);
+        return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
 
       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
                                                              Template,
@@ -3804,8 +3812,7 @@
     } else if (NonTypeTemplateParmDecl *NTTP
                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
       if (!NTTP->hasDefaultArgument())
-        return diagnoseArityMismatch(*this, Template, TemplateLoc, 
-                                     TemplateArgs);
+        return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
 
       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
                                                               TemplateLoc,
@@ -3822,8 +3829,7 @@
         = cast<TemplateTemplateParmDecl>(*Param);
 
       if (!TempParm->hasDefaultArgument())
-        return diagnoseArityMismatch(*this, Template, TemplateLoc, 
-                                     TemplateArgs);
+        return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
 
       NestedNameSpecifierLoc QualifierLoc;
       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
@@ -3851,12 +3857,12 @@
                               RAngleLoc, 0, Converted))
       return true;
 
-    // Core issue 150 (assumed resolution): if this is a template template 
-    // parameter, keep track of the default template arguments from the 
+    // Core issue 150 (assumed resolution): if this is a template template
+    // parameter, keep track of the default template arguments from the
     // template definition.
     if (isTemplateTemplateParameter)
-      TemplateArgs.addArgument(Arg);
-    
+      NewArgs.addArgument(Arg);
+
     // Move to the next template parameter and argument.
     ++Param;
     ++ArgIdx;
@@ -3868,15 +3874,18 @@
   // still dependent).
   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
-    while (ArgIdx < NumArgs &&
-           TemplateArgs[ArgIdx].getArgument().isPackExpansion())
-      Converted.push_back(TemplateArgs[ArgIdx++].getArgument());
+    while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
+      Converted.push_back(NewArgs[ArgIdx++].getArgument());
   }
 
   // If we have any leftover arguments, then there were too many arguments.
   // Complain and fail.
   if (ArgIdx < NumArgs)
-    return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
+    return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
+
+  // No problems found with the new argument list, propagate changes back
+  // to caller.
+  TemplateArgs = NewArgs;
 
   return false;
 }
@@ -4742,30 +4751,152 @@
 ///
 /// This routine implements the semantics of C++ [temp.arg.nontype].
 /// If an error occurred, it returns ExprError(); otherwise, it
-/// returns the converted template argument. \p
-/// InstantiatedParamType is the type of the non-type template
-/// parameter after it has been instantiated.
+/// returns the converted template argument. \p ParamType is the
+/// type of the non-type template parameter after it has been instantiated.
 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
-                                       QualType InstantiatedParamType, Expr *Arg,
+                                       QualType ParamType, Expr *Arg,
                                        TemplateArgument &Converted,
                                        CheckTemplateArgumentKind CTAK) {
   SourceLocation StartLoc = Arg->getLocStart();
 
   // If either the parameter has a dependent type or the argument is
   // type-dependent, there's nothing we can check now.
-  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
+  if (ParamType->isDependentType() || Arg->isTypeDependent()) {
     // FIXME: Produce a cloned, canonical expression?
     Converted = TemplateArgument(Arg);
     return Arg;
   }
 
+  // We should have already dropped all cv-qualifiers by now.
+  assert(!ParamType.hasQualifiers() &&
+         "non-type template parameter type cannot be qualified");
+
+  if (CTAK == CTAK_Deduced &&
+      !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
+    // C++ [temp.deduct.type]p17:
+    //   If, in the declaration of a function template with a non-type
+    //   template-parameter, the non-type template-parameter is used
+    //   in an expression in the function parameter-list and, if the
+    //   corresponding template-argument is deduced, the
+    //   template-argument type shall match the type of the
+    //   template-parameter exactly, except that a template-argument
+    //   deduced from an array bound may be of any integral type.
+    Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
+      << Arg->getType().getUnqualifiedType()
+      << ParamType.getUnqualifiedType();
+    Diag(Param->getLocation(), diag::note_template_param_here);
+    return ExprError();
+  }
+
+  if (getLangOpts().CPlusPlus1z) {
+    // FIXME: We can do some limited checking for a value-dependent but not
+    // type-dependent argument.
+    if (Arg->isValueDependent()) {
+      Converted = TemplateArgument(Arg);
+      return Arg;
+    }
+
+    // C++1z [temp.arg.nontype]p1:
+    //   A template-argument for a non-type template parameter shall be
+    //   a converted constant expression of the type of the template-parameter.
+    APValue Value;
+    ExprResult ArgResult = CheckConvertedConstantExpression(
+        Arg, ParamType, Value, CCEK_TemplateArg);
+    if (ArgResult.isInvalid())
+      return ExprError();
+
+    QualType CanonParamType = Context.getCanonicalType(ParamType);
+
+    // Convert the APValue to a TemplateArgument.
+    switch (Value.getKind()) {
+    case APValue::Uninitialized:
+      assert(ParamType->isNullPtrType());
+      Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
+      break;
+    case APValue::Int:
+      assert(ParamType->isIntegralOrEnumerationType());
+      Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
+      break;
+    case APValue::MemberPointer: {
+      assert(ParamType->isMemberPointerType());
+
+      // FIXME: We need TemplateArgument representation and mangling for these.
+      if (!Value.getMemberPointerPath().empty()) {
+        Diag(Arg->getLocStart(),
+             diag::err_template_arg_member_ptr_base_derived_not_supported)
+            << Value.getMemberPointerDecl() << ParamType
+            << Arg->getSourceRange();
+        return ExprError();
+      }
+
+      auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
+      Converted = VD ? TemplateArgument(VD, CanonParamType)
+                     : TemplateArgument(CanonParamType, /*isNullPtr*/true);
+      break;
+    }
+    case APValue::LValue: {
+      //   For a non-type template-parameter of pointer or reference type,
+      //   the value of the constant expression shall not refer to
+      assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
+             ParamType->isNullPtrType());
+      // -- a temporary object
+      // -- a string literal
+      // -- the result of a typeid expression, or
+      // -- a predefind __func__ variable
+      if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
+        if (isa<CXXUuidofExpr>(E)) {
+          Converted = TemplateArgument(const_cast<Expr*>(E));
+          break;
+        }
+        Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
+          << Arg->getSourceRange();
+        return ExprError();
+      }
+      auto *VD = const_cast<ValueDecl *>(
+          Value.getLValueBase().dyn_cast<const ValueDecl *>());
+      // -- a subobject
+      if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
+          VD && VD->getType()->isArrayType() &&
+          Value.getLValuePath()[0].ArrayIndex == 0 &&
+          !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
+        // Per defect report (no number yet):
+        //   ... other than a pointer to the first element of a complete array
+        //       object.
+      } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
+                 Value.isLValueOnePastTheEnd()) {
+        Diag(StartLoc, diag::err_non_type_template_arg_subobject)
+          << Value.getAsString(Context, ParamType);
+        return ExprError();
+      }
+      assert((VD || !ParamType->isReferenceType()) &&
+             "null reference should not be a constant expression");
+      assert((!VD || !ParamType->isNullPtrType()) &&
+             "non-null value of type nullptr_t?");
+      Converted = VD ? TemplateArgument(VD, CanonParamType)
+                     : TemplateArgument(CanonParamType, /*isNullPtr*/true);
+      break;
+    }
+    case APValue::AddrLabelDiff:
+      return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
+    case APValue::Float:
+    case APValue::ComplexInt:
+    case APValue::ComplexFloat:
+    case APValue::Vector:
+    case APValue::Array:
+    case APValue::Struct:
+    case APValue::Union:
+      llvm_unreachable("invalid kind for template argument");
+    }
+
+    return ArgResult.get();
+  }
+
   // C++ [temp.arg.nontype]p5:
   //   The following conversions are performed on each expression used
   //   as a non-type template-argument. If a non-type
   //   template-argument cannot be converted to the type of the
   //   corresponding template-parameter then the program is
   //   ill-formed.
-  QualType ParamType = InstantiatedParamType;
   if (ParamType->isIntegralOrEnumerationType()) {
     // C++11:
     //   -- for a non-type template-parameter of integral or
@@ -4777,23 +4908,6 @@
     //      enumeration type, integral promotions (4.5) and integral
     //      conversions (4.7) are applied.
 
-    if (CTAK == CTAK_Deduced &&
-        !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
-      // C++ [temp.deduct.type]p17:
-      //   If, in the declaration of a function template with a non-type
-      //   template-parameter, the non-type template-parameter is used
-      //   in an expression in the function parameter-list and, if the
-      //   corresponding template-argument is deduced, the
-      //   template-argument type shall match the type of the
-      //   template-parameter exactly, except that a template-argument
-      //   deduced from an array bound may be of any integral type.
-      Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
-        << Arg->getType().getUnqualifiedType()
-        << ParamType.getUnqualifiedType();
-      Diag(Param->getLocation(), diag::note_template_param_here);
-      return ExprError();
-    }
-
     if (getLangOpts().CPlusPlus11) {
       // We can't check arbitrary value-dependent arguments.
       // FIXME: If there's no viable conversion to the template parameter type,
@@ -4871,9 +4985,8 @@
         return ExprError();
     }
 
-    // From here on out, all we care about are the unqualified forms
-    // of the parameter and argument types.
-    ParamType = ParamType.getUnqualifiedType();
+    // From here on out, all we care about is the unqualified form
+    // of the argument type.
     ArgType = ArgType.getUnqualifiedType();
 
     // Try to convert the argument to the parameter's type.
@@ -4890,7 +5003,7 @@
       // We can't perform this conversion.
       Diag(Arg->getLocStart(),
            diag::err_template_arg_not_convertible)
-        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
+        << Arg->getType() << ParamType << Arg->getSourceRange();
       Diag(Param->getLocation(), diag::note_template_param_here);
       return ExprError();
     }
@@ -6333,14 +6446,11 @@
 /// \brief Strips various properties off an implicit instantiation
 /// that has just been explicitly specialized.
 static void StripImplicitInstantiation(NamedDecl *D) {
-  D->dropAttrs();
+  D->dropAttr<DLLImportAttr>();
+  D->dropAttr<DLLExportAttr>();
 
-  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
+  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
     FD->setInlineSpecified(false);
-
-    for (auto I : FD->params())
-      I->dropAttrs();
-  }
 }
 
 /// \brief Compute the diagnostic location for an explicit instantiation
@@ -7067,9 +7177,27 @@
   //   There are two forms of explicit instantiation: an explicit instantiation
   //   definition and an explicit instantiation declaration. An explicit
   //   instantiation declaration begins with the extern keyword. [...]
-  TemplateSpecializationKind TSK
-    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
-                           : TSK_ExplicitInstantiationDeclaration;
+  TemplateSpecializationKind TSK = ExternLoc.isInvalid()
+                                       ? TSK_ExplicitInstantiationDefinition
+                                       : TSK_ExplicitInstantiationDeclaration;
+
+  if (TSK == TSK_ExplicitInstantiationDeclaration) {
+    // Check for dllexport class template instantiation declarations.
+    for (AttributeList *A = Attr; A; A = A->getNext()) {
+      if (A->getKind() == AttributeList::AT_DLLExport) {
+        Diag(ExternLoc,
+             diag::warn_attribute_dllexport_explicit_instantiation_decl);
+        Diag(A->getLoc(), diag::note_attribute);
+        break;
+      }
+    }
+
+    if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
+      Diag(ExternLoc,
+           diag::warn_attribute_dllexport_explicit_instantiation_decl);
+      Diag(A->getLocation(), diag::note_attribute);
+    }
+  }
 
   // Translate the parser's template argument list in our AST format.
   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
@@ -7906,11 +8034,7 @@
 
   DeclarationName Name(&II);
   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
-  NestedNameSpecifier *NNS = SS.getScopeRep();
-  if (NNS->getKind() == NestedNameSpecifier::Super)
-    LookupInSuper(Result, NNS->getAsRecordDecl());
-  else
-    LookupQualifiedName(Result, Ctx);
+  LookupQualifiedName(Result, Ctx, SS);
   unsigned DiagID = 0;
   Decl *Referenced = nullptr;
   switch (Result.getResultKind()) {
diff --git a/lib/Sema/SemaTemplateDeduction.cpp b/lib/Sema/SemaTemplateDeduction.cpp
index 221a84d..3515918 100644
--- a/lib/Sema/SemaTemplateDeduction.cpp
+++ b/lib/Sema/SemaTemplateDeduction.cpp
@@ -91,30 +91,6 @@
                         TemplateDeductionInfo &Info,
                         SmallVectorImpl<DeducedTemplateArgument> &Deduced);
 
-/// \brief Whether template argument deduction for two reference parameters
-/// resulted in the argument type, parameter type, or neither type being more
-/// qualified than the other.
-enum DeductionQualifierComparison {
-  NeitherMoreQualified = 0,
-  ParamMoreQualified,
-  ArgMoreQualified
-};
-
-/// \brief Stores the result of comparing two reference parameters while
-/// performing template argument deduction for partial ordering of function
-/// templates.
-struct RefParamPartialOrderingComparison {
-  /// \brief Whether the parameter type is an rvalue reference type.
-  bool ParamIsRvalueRef;
-  /// \brief Whether the argument type is an rvalue reference type.
-  bool ArgIsRvalueRef;
-
-  /// \brief Whether the parameter or argument (or neither) is more qualified.
-  DeductionQualifierComparison Qualifiers;
-};
-
-
-
 static Sema::TemplateDeductionResult
 DeduceTemplateArgumentsByTypeMatch(Sema &S,
                                    TemplateParameterList *TemplateParams,
@@ -124,9 +100,7 @@
                                    SmallVectorImpl<DeducedTemplateArgument> &
                                                       Deduced,
                                    unsigned TDF,
-                                   bool PartialOrdering = false,
-                            SmallVectorImpl<RefParamPartialOrderingComparison> *
-                                                 RefParamComparisons = nullptr);
+                                   bool PartialOrdering = false);
 
 static Sema::TemplateDeductionResult
 DeduceTemplateArguments(Sema &S,
@@ -784,9 +758,6 @@
 /// deduction for during partial ordering for a call
 /// (C++0x [temp.deduct.partial]).
 ///
-/// \param RefParamComparisons If we're performing template argument deduction
-/// in the context of partial ordering, the set of qualifier comparisons.
-///
 /// \returns the result of template argument deduction so far. Note that a
 /// "success" result means that template argument deduction has not yet failed,
 /// but it may still fail, later, for other reasons.
@@ -798,9 +769,7 @@
                         TemplateDeductionInfo &Info,
                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
                         unsigned TDF,
-                        bool PartialOrdering = false,
-                        SmallVectorImpl<RefParamPartialOrderingComparison> *
-                                                RefParamComparisons = nullptr) {
+                        bool PartialOrdering = false) {
   // Fast-path check to see if we have too many/too few arguments.
   if (NumParams != NumArgs &&
       !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
@@ -836,8 +805,7 @@
             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
                                                  Params[ParamIdx], Args[ArgIdx],
                                                  Info, Deduced, TDF,
-                                                 PartialOrdering,
-                                                 RefParamComparisons))
+                                                 PartialOrdering))
         return Result;
 
       ++ArgIdx;
@@ -869,8 +837,7 @@
       if (Sema::TemplateDeductionResult Result
             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
                                                  Args[ArgIdx], Info, Deduced,
-                                                 TDF, PartialOrdering,
-                                                 RefParamComparisons))
+                                                 TDF, PartialOrdering))
         return Result;
 
       PackScope.nextPackElement();
@@ -967,9 +934,6 @@
 /// \param PartialOrdering Whether we're performing template argument deduction
 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
 ///
-/// \param RefParamComparisons If we're performing template argument deduction
-/// in the context of partial ordering, the set of qualifier comparisons.
-///
 /// \returns the result of template argument deduction so far. Note that a
 /// "success" result means that template argument deduction has not yet failed,
 /// but it may still fail, later, for other reasons.
@@ -980,9 +944,7 @@
                                    TemplateDeductionInfo &Info,
                             SmallVectorImpl<DeducedTemplateArgument> &Deduced,
                                    unsigned TDF,
-                                   bool PartialOrdering,
-                            SmallVectorImpl<RefParamPartialOrderingComparison> *
-                                                          RefParamComparisons) {
+                                   bool PartialOrdering) {
   // We only want to look at the canonical types, since typedefs and
   // sugar are not part of template argument deduction.
   QualType Param = S.Context.getCanonicalType(ParamIn);
@@ -995,7 +957,7 @@
     Arg = ArgExpansion->getPattern();
 
   if (PartialOrdering) {
-    // C++0x [temp.deduct.partial]p5:
+    // C++11 [temp.deduct.partial]p5:
     //   Before the partial ordering is done, certain transformations are
     //   performed on the types used for partial ordering:
     //     - If P is a reference type, P is replaced by the type referred to.
@@ -1008,42 +970,42 @@
     if (ArgRef)
       Arg = ArgRef->getPointeeType();
 
-    if (RefParamComparisons && ParamRef && ArgRef) {
-      // C++0x [temp.deduct.partial]p6:
-      //   If both P and A were reference types (before being replaced with the
-      //   type referred to above), determine which of the two types (if any) is
-      //   more cv-qualified than the other; otherwise the types are considered
-      //   to be equally cv-qualified for partial ordering purposes. The result
-      //   of this determination will be used below.
+    if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
+      // C++11 [temp.deduct.partial]p9:
+      //   If, for a given type, deduction succeeds in both directions (i.e.,
+      //   the types are identical after the transformations above) and both
+      //   P and A were reference types [...]:
+      //     - if [one type] was an lvalue reference and [the other type] was
+      //       not, [the other type] is not considered to be at least as
+      //       specialized as [the first type]
+      //     - if [one type] is more cv-qualified than [the other type],
+      //       [the other type] is not considered to be at least as specialized
+      //       as [the first type]
+      // Objective-C ARC adds:
+      //     - [one type] has non-trivial lifetime, [the other type] has
+      //       __unsafe_unretained lifetime, and the types are otherwise
+      //       identical
       //
-      // We save this information for later, using it only when deduction
-      // succeeds in both directions.
-      RefParamPartialOrderingComparison Comparison;
-      Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
-      Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
-      Comparison.Qualifiers = NeitherMoreQualified;
-      
+      // A is "considered to be at least as specialized" as P iff deduction
+      // succeeds, so we model this as a deduction failure. Note that
+      // [the first type] is P and [the other type] is A here; the standard
+      // gets this backwards.
       Qualifiers ParamQuals = Param.getQualifiers();
       Qualifiers ArgQuals = Arg.getQualifiers();
-      if (ParamQuals.isStrictSupersetOf(ArgQuals))
-        Comparison.Qualifiers = ParamMoreQualified;
-      else if (ArgQuals.isStrictSupersetOf(ParamQuals))
-        Comparison.Qualifiers = ArgMoreQualified;
-      else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() &&
-               ArgQuals.withoutObjCLifetime()
-                 == ParamQuals.withoutObjCLifetime()) {
-        // Prefer binding to non-__unsafe_autoretained parameters.
-        if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
-            ParamQuals.getObjCLifetime())
-          Comparison.Qualifiers = ParamMoreQualified;
-        else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
-                 ArgQuals.getObjCLifetime())
-          Comparison.Qualifiers = ArgMoreQualified;
+      if ((ParamRef->isLValueReferenceType() &&
+           !ArgRef->isLValueReferenceType()) ||
+          ParamQuals.isStrictSupersetOf(ArgQuals) ||
+          (ParamQuals.hasNonTrivialObjCLifetime() &&
+           ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
+           ParamQuals.withoutObjCLifetime() ==
+               ArgQuals.withoutObjCLifetime())) {
+        Info.FirstArg = TemplateArgument(ParamIn);
+        Info.SecondArg = TemplateArgument(ArgIn);
+        return Sema::TDK_NonDeducedMismatch;
       }
-      RefParamComparisons->push_back(Comparison);
     }
 
-    // C++0x [temp.deduct.partial]p7:
+    // C++11 [temp.deduct.partial]p7:
     //   Remove any top-level cv-qualifiers:
     //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
     //       version of P.
@@ -2588,6 +2550,9 @@
     = Function->getType()->getAs<FunctionProtoType>();
   assert(Proto && "Function template does not have a prototype?");
 
+  // Isolate our substituted parameters from our caller.
+  LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
+
   // Instantiate the types of each of the function parameters given the
   // explicitly-specified template arguments. If the function has a trailing
   // return type, substitute it after the arguments to ensure we substitute
@@ -2781,7 +2746,8 @@
                                       unsigned NumExplicitlySpecified,
                                       FunctionDecl *&Specialization,
                                       TemplateDeductionInfo &Info,
-        SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
+        SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
+                                      bool PartialOverloading) {
   TemplateParameterList *TemplateParams
     = FunctionTemplate->getTemplateParameters();
 
@@ -2908,6 +2874,8 @@
                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
                                                   Builder.size()));
+      if (PartialOverloading) break;
+
       return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
     }
 
@@ -3133,34 +3101,16 @@
   //   are ignored for type deduction.
   if (ParamType.hasQualifiers())
     ParamType = ParamType.getUnqualifiedType();
+
+  //   [...] If P is a reference type, the type referred to by P is
+  //   used for type deduction.
   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
-  if (ParamRefType) {
-    QualType PointeeType = ParamRefType->getPointeeType();
+  if (ParamRefType)
+    ParamType = ParamRefType->getPointeeType();
 
-    // If the argument has incomplete array type, try to complete its type.
-    if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
-      ArgType = Arg->getType();
-
-    //   [C++0x] If P is an rvalue reference to a cv-unqualified
-    //   template parameter and the argument is an lvalue, the type
-    //   "lvalue reference to A" is used in place of A for type
-    //   deduction.
-    if (isa<RValueReferenceType>(ParamType)) {
-      if (!PointeeType.getQualifiers() &&
-          isa<TemplateTypeParmType>(PointeeType) &&
-          Arg->Classify(S.Context).isLValue() &&
-          Arg->getType() != S.Context.OverloadTy &&
-          Arg->getType() != S.Context.BoundMemberTy)
-        ArgType = S.Context.getLValueReferenceType(ArgType);
-    }
-
-    //   [...] If P is a reference type, the type referred to by P is used
-    //   for type deduction.
-    ParamType = PointeeType;
-  }
-
-  // Overload sets usually make this parameter an undeduced
-  // context, but there are sometimes special circumstances.
+  // Overload sets usually make this parameter an undeduced context,
+  // but there are sometimes special circumstances.  Typically
+  // involving a template-id-expr.
   if (ArgType == S.Context.OverloadTy) {
     ArgType = ResolveOverloadForDeduction(S, TemplateParams,
                                           Arg, ParamType,
@@ -3170,12 +3120,17 @@
   }
 
   if (ParamRefType) {
+    // If the argument has incomplete array type, try to complete its type.
+    if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
+      ArgType = Arg->getType();
+
     // C++0x [temp.deduct.call]p3:
-    //   [...] If P is of the form T&&, where T is a template parameter, and
-    //   the argument is an lvalue, the type A& is used in place of A for
-    //   type deduction.
+    //   If P is an rvalue reference to a cv-unqualified template
+    //   parameter and the argument is an lvalue, the type "lvalue
+    //   reference to A" is used in place of A for type deduction.
     if (ParamRefType->isRValueReferenceType() &&
-        ParamRefType->getAs<TemplateTypeParmType>() &&
+        !ParamType.getQualifiers() &&
+        isa<TemplateTypeParmType>(ParamType) &&
         Arg->isLValue())
       ArgType = S.Context.getLValueReferenceType(ArgType);
   } else {
@@ -3295,26 +3250,28 @@
 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
     FunctionTemplateDecl *FunctionTemplate,
     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
-    FunctionDecl *&Specialization, TemplateDeductionInfo &Info) {
+    FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
+    bool PartialOverloading) {
   if (FunctionTemplate->isInvalidDecl())
     return TDK_Invalid;
 
   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
+  unsigned NumParams = Function->getNumParams();
 
   // C++ [temp.deduct.call]p1:
   //   Template argument deduction is done by comparing each function template
   //   parameter type (call it P) with the type of the corresponding argument
   //   of the call (call it A) as described below.
   unsigned CheckArgs = Args.size();
-  if (Args.size() < Function->getMinRequiredArguments())
+  if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
     return TDK_TooFewArguments;
-  else if (Args.size() > Function->getNumParams()) {
+  else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
     const FunctionProtoType *Proto
       = Function->getType()->getAs<FunctionProtoType>();
     if (Proto->isTemplateVariadic())
       /* Do nothing */;
     else if (Proto->isVariadic())
-      CheckArgs = Function->getNumParams();
+      CheckArgs = NumParams;
     else
       return TDK_TooManyArguments;
   }
@@ -3341,7 +3298,7 @@
     NumExplicitlySpecified = Deduced.size();
   } else {
     // Just fill in the parameter types from the function declaration.
-    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
+    for (unsigned I = 0; I != NumParams; ++I)
       ParamTypes.push_back(Function->getParamDecl(I)->getType());
   }
 
@@ -3349,8 +3306,8 @@
   Deduced.resize(TemplateParams->size());
   unsigned ArgIdx = 0;
   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
-  for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
-       ParamIdx != NumParams; ++ParamIdx) {
+  for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
+       ParamIdx != NumParamTypes; ++ParamIdx) {
     QualType OrigParamType = ParamTypes[ParamIdx];
     QualType ParamType = OrigParamType;
     
@@ -3419,7 +3376,7 @@
     //   the function parameter pack. For a function parameter pack that does
     //   not occur at the end of the parameter-declaration-list, the type of
     //   the parameter pack is a non-deduced context.
-    if (ParamIdx + 1 < NumParams)
+    if (ParamIdx + 1 < NumParamTypes)
       break;
 
     QualType ParamPattern = ParamExpansion->getPattern();
@@ -3489,7 +3446,8 @@
 
   return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
                                          NumExplicitlySpecified, Specialization,
-                                         Info, &OriginalCallArgs);
+                                         Info, &OriginalCallArgs,
+                                         PartialOverloading);
 }
 
 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
@@ -3989,7 +3947,7 @@
         return DAR_FailedAlreadyDiagnosed;
       }
 
-      QualType Deduced = BuildDecltypeType(Init, Init->getLocStart());
+      QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
       // FIXME: Support a non-canonical deduced type for 'auto'.
       Deduced = Context.getCanonicalType(Deduced);
       Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
@@ -4150,8 +4108,7 @@
                                      FunctionTemplateDecl *FT1,
                                      FunctionTemplateDecl *FT2,
                                      TemplatePartialOrderingContext TPOC,
-                                     unsigned NumCallArguments1,
-    SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
+                                     unsigned NumCallArguments1) {
   FunctionDecl *FD1 = FT1->getTemplatedDecl();
   FunctionDecl *FD2 = FT2->getTemplatedDecl();
   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
@@ -4216,8 +4173,7 @@
       Args2.resize(NumComparedArguments);
     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
                                 Args1.data(), Args1.size(), Info, Deduced,
-                                TDF_None, /*PartialOrdering=*/true,
-                                RefParamComparisons))
+                                TDF_None, /*PartialOrdering=*/true))
       return false;
 
     break;
@@ -4229,7 +4185,7 @@
     if (DeduceTemplateArgumentsByTypeMatch(
             S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
             Info, Deduced, TDF_None,
-            /*PartialOrdering=*/true, RefParamComparisons))
+            /*PartialOrdering=*/true))
       return false;
     break;
 
@@ -4239,8 +4195,7 @@
     if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
                                            FD2->getType(), FD1->getType(),
                                            Info, Deduced, TDF_None,
-                                           /*PartialOrdering=*/true,
-                                           RefParamComparisons))
+                                           /*PartialOrdering=*/true))
       return false;
     break;
   }
@@ -4339,83 +4294,17 @@
                                  TemplatePartialOrderingContext TPOC,
                                  unsigned NumCallArguments1,
                                  unsigned NumCallArguments2) {
-  SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
-                                          NumCallArguments1, nullptr);
+                                          NumCallArguments1);
   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
-                                          NumCallArguments2,
-                                          &RefParamComparisons);
+                                          NumCallArguments2);
 
   if (Better1 != Better2) // We have a clear winner
-    return Better1? FT1 : FT2;
+    return Better1 ? FT1 : FT2;
 
   if (!Better1 && !Better2) // Neither is better than the other
     return nullptr;
 
-  // C++0x [temp.deduct.partial]p10:
-  //   If for each type being considered a given template is at least as
-  //   specialized for all types and more specialized for some set of types and
-  //   the other template is not more specialized for any types or is not at
-  //   least as specialized for any types, then the given template is more
-  //   specialized than the other template. Otherwise, neither template is more
-  //   specialized than the other.
-  Better1 = false;
-  Better2 = false;
-  for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
-    // C++0x [temp.deduct.partial]p9:
-    //   If, for a given type, deduction succeeds in both directions (i.e., the
-    //   types are identical after the transformations above) and both P and A
-    //   were reference types (before being replaced with the type referred to
-    //   above):
-
-    //     -- if the type from the argument template was an lvalue reference
-    //        and the type from the parameter template was not, the argument
-    //        type is considered to be more specialized than the other;
-    //        otherwise,
-    if (!RefParamComparisons[I].ArgIsRvalueRef &&
-        RefParamComparisons[I].ParamIsRvalueRef) {
-      Better2 = true;
-      if (Better1)
-        return nullptr;
-      continue;
-    } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
-               RefParamComparisons[I].ArgIsRvalueRef) {
-      Better1 = true;
-      if (Better2)
-        return nullptr;
-      continue;
-    }
-
-    //     -- if the type from the argument template is more cv-qualified than
-    //        the type from the parameter template (as described above), the
-    //        argument type is considered to be more specialized than the
-    //        other; otherwise,
-    switch (RefParamComparisons[I].Qualifiers) {
-    case NeitherMoreQualified:
-      break;
-
-    case ParamMoreQualified:
-      Better1 = true;
-      if (Better2)
-        return nullptr;
-      continue;
-
-    case ArgMoreQualified:
-      Better2 = true;
-      if (Better1)
-        return nullptr;
-      continue;
-    }
-
-    //     -- neither type is more specialized than the other.
-  }
-
-  assert(!(Better1 && Better2) && "Should have broken out in the loop above");
-  if (Better1)
-    return FT1;
-  else if (Better2)
-    return FT2;
-
   // FIXME: This mimics what GCC implements, but doesn't match up with the
   // proposed resolution for core issue 692. This area needs to be sorted out,
   // but for now we attempt to maintain compatibility.
@@ -4588,8 +4477,7 @@
   bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
                                             PS2->getTemplateParameters(),
                                             PT2, PT1, Info, Deduced, TDF_None,
-                                            /*PartialOrdering=*/true,
-                                            /*RefParamComparisons=*/nullptr);
+                                            /*PartialOrdering=*/true);
   if (Better1) {
     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
     InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
@@ -4602,8 +4490,7 @@
   Deduced.resize(PS1->getTemplateParameters()->size());
   bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
       *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
-      /*PartialOrdering=*/true,
-      /*RefParamComparisons=*/nullptr);
+      /*PartialOrdering=*/true);
   if (Better2) {
     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
                                                  Deduced.end());
@@ -4646,8 +4533,7 @@
   Deduced.resize(PS2->getTemplateParameters()->size());
   bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
       *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
-      /*PartialOrdering=*/true,
-      /*RefParamComparisons=*/nullptr);
+      /*PartialOrdering=*/true);
   if (Better1) {
     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
                                                  Deduced.end());
@@ -4663,8 +4549,7 @@
   bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
                                             PS1->getTemplateParameters(),
                                             PT1, PT2, Info, Deduced, TDF_None,
-                                            /*PartialOrdering=*/true,
-                                            /*RefParamComparisons=*/nullptr);
+                                            /*PartialOrdering=*/true);
   if (Better2) {
     SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
     InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
diff --git a/lib/Sema/SemaTemplateInstantiate.cpp b/lib/Sema/SemaTemplateInstantiate.cpp
index c05960b..ed0d5a5 100644
--- a/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/lib/Sema/SemaTemplateInstantiate.cpp
@@ -207,6 +207,12 @@
     sema::TemplateDeductionInfo *DeductionInfo) {
   SavedInNonInstantiationSFINAEContext =
       SemaRef.InNonInstantiationSFINAEContext;
+  // Don't allow further instantiation if a fatal error has occcured.  Any
+  // diagnostics we might have raised will not be visible.
+  if (SemaRef.Diags.hasFatalErrorOccurred()) {
+    Invalid = true;
+    return;
+  }
   Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
   if (!Invalid) {
     ActiveTemplateInstantiation Inst;
@@ -2762,8 +2768,7 @@
   return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
 }
 
-
-static const Decl* getCanonicalParmVarDecl(const Decl *D) {
+static const Decl *getCanonicalParmVarDecl(const Decl *D) {
   // When storing ParmVarDecls in the local instantiation scope, we always
   // want to use the ParmVarDecl from the canonical function declaration,
   // since the map is then valid for any redeclaration or definition of that
@@ -2771,7 +2776,10 @@
   if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
       unsigned i = PV->getFunctionScopeIndex();
-      return FD->getCanonicalDecl()->getParamDecl(i);
+      // This parameter might be from a freestanding function type within the
+      // function and isn't necessarily referring to one of FD's parameters.
+      if (FD->getParamDecl(i) == PV)
+        return FD->getCanonicalDecl()->getParamDecl(i);
     }
   }
   return D;
@@ -2820,12 +2828,22 @@
 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
   D = getCanonicalParmVarDecl(D);
   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
-  if (Stored.isNull())
+  if (Stored.isNull()) {
+#ifndef NDEBUG
+    // It should not be present in any surrounding scope either.
+    LocalInstantiationScope *Current = this;
+    while (Current->CombineWithOuterScope && Current->Outer) {
+      Current = Current->Outer;
+      assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
+             "Instantiated local in inner and outer scopes");
+    }
+#endif
     Stored = Inst;
-  else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
+  } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
     Pack->push_back(Inst);
-  else
+  } else {
     assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
+  }
 }
 
 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 
@@ -2836,9 +2854,16 @@
 }
 
 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
+#ifndef NDEBUG
+  // This should be the first time we've been told about this decl.
+  for (LocalInstantiationScope *Current = this;
+       Current && Current->CombineWithOuterScope; Current = Current->Outer)
+    assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
+           "Creating local pack after instantiation of local");
+#endif
+
   D = getCanonicalParmVarDecl(D);
   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
-  assert(Stored.isNull() && "Already instantiated this local");
   DeclArgumentPack *Pack = new DeclArgumentPack;
   Stored = Pack;
   ArgumentPacks.push_back(Pack);
diff --git a/lib/Sema/SemaTemplateInstantiateDecl.cpp b/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9ba9c14..1df0701 100644
--- a/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2360,8 +2360,10 @@
 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
                                      ClassScopeFunctionSpecializationDecl *Decl) {
   CXXMethodDecl *OldFD = Decl->getSpecialization();
-  CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
-                                                                nullptr, true));
+  CXXMethodDecl *NewFD =
+    cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
+  if (!NewFD)
+    return nullptr;
 
   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
                         Sema::ForRedeclaration);
@@ -3311,12 +3313,8 @@
   // it marks vtables used in late parsed templates as used.
   SavePendingLocalImplicitInstantiationsRAII
       SavedPendingLocalImplicitInstantiations(*this);
-  std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
-      SavePendingInstantiationsAndVTableUses;
-  if (Recursive) {
-    SavePendingInstantiationsAndVTableUses.reset(
-        new SavePendingInstantiationsAndVTableUsesRAII(*this));
-  }
+  SavePendingInstantiationsAndVTableUsesRAII
+      SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
 
   // Call the LateTemplateParser callback if there is a need to late parse
   // a templated function definition.
@@ -3461,8 +3459,8 @@
     // instantiation of this template.
     PerformPendingInstantiations();
 
-    // Restore PendingInstantiations and VTableUses.
-    SavePendingInstantiationsAndVTableUses.reset();
+    // PendingInstantiations and VTableUses are restored through
+    // SavePendingInstantiationsAndVTableUses's destructor.
   }
 }
 
@@ -3778,12 +3776,8 @@
       // If we're performing recursive template instantiation, create our own
       // queue of pending implicit instantiations that we will instantiate
       // later, while we're still within our own instantiation context.
-      std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
-          SavePendingInstantiationsAndVTableUses;
-      if (Recursive) {
-        SavePendingInstantiationsAndVTableUses.reset(
-            new SavePendingInstantiationsAndVTableUsesRAII(*this));
-      }
+      SavePendingInstantiationsAndVTableUsesRAII
+          SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
 
       LocalInstantiationScope Local(*this);
 
@@ -3810,8 +3804,8 @@
         // instantiation of this template.
         PerformPendingInstantiations();
 
-        // Restore PendingInstantiations and VTableUses.
-        SavePendingInstantiationsAndVTableUses.reset();
+        // PendingInstantiations and VTableUses are restored through
+        // SavePendingInstantiationsAndVTableUses's destructor.
       }
     }
 
@@ -3897,12 +3891,8 @@
   // while we're still within our own instantiation context.
   SavePendingLocalImplicitInstantiationsRAII
       SavedPendingLocalImplicitInstantiations(*this);
-  std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
-      SavePendingInstantiationsAndVTableUses;
-  if (Recursive) {
-    SavePendingInstantiationsAndVTableUses.reset(
-        new SavePendingInstantiationsAndVTableUsesRAII(*this));
-  }
+  SavePendingInstantiationsAndVTableUsesRAII
+      SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
 
   // Enter the scope of this instantiation. We don't use
   // PushDeclContext because we don't have a scope.
@@ -3968,8 +3958,8 @@
     // instantiation of this template.
     PerformPendingInstantiations();
 
-    // Restore PendingInstantiations and VTableUses.
-    SavePendingInstantiationsAndVTableUses.reset();
+    // PendingInstantiations and VTableUses are restored through
+    // SavePendingInstantiationsAndVTableUses's destructor.
   }
 }
 
diff --git a/lib/Sema/SemaTemplateVariadic.cpp b/lib/Sema/SemaTemplateVariadic.cpp
index f5883e4..e4fab71 100644
--- a/lib/Sema/SemaTemplateVariadic.cpp
+++ b/lib/Sema/SemaTemplateVariadic.cpp
@@ -782,11 +782,11 @@
                  Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
         return true;
 
-      if (Chunk.Fun.hasTrailingReturnType() &&
-          Chunk.Fun.getTrailingReturnType()
-              .get()
-              ->containsUnexpandedParameterPack())
-        return true;
+      if (Chunk.Fun.hasTrailingReturnType()) {
+        QualType T = Chunk.Fun.getTrailingReturnType().get();
+	if (!T.isNull() && T->containsUnexpandedParameterPack())
+	  return true;
+      }
       break;
 
     case DeclaratorChunk::MemberPointer:
diff --git a/lib/Sema/SemaType.cpp b/lib/Sema/SemaType.cpp
index fcb9c72..5614225 100644
--- a/lib/Sema/SemaType.cpp
+++ b/lib/Sema/SemaType.cpp
@@ -112,7 +112,6 @@
     case AttributeList::AT_SysVABI: \
     case AttributeList::AT_Regparm: \
     case AttributeList::AT_Pcs: \
-    case AttributeList::AT_PnaclCall: \
     case AttributeList::AT_IntelOclBicc
 
 // Microsoft-specific type qualifiers.
@@ -869,7 +868,9 @@
     else
       Result = Context.DoubleTy;
 
-    if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
+    if (S.getLangOpts().OpenCL &&
+        !((S.getLangOpts().OpenCLVersion >= 120) ||
+          S.getOpenCLOptions().cl_khr_fp64)) {
       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
       declarator.setInvalidType(true);
     }
@@ -1007,16 +1008,7 @@
       const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
       const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
       const bool IsParameterPack = declarator.hasEllipsis();
-      
-      // Create a name for the invented template parameter type.
-      std::string InventedTemplateParamName = "$auto-";
-      llvm::raw_string_ostream ss(InventedTemplateParamName);
-      ss << TemplateParameterDepth; 
-      ss << "-" << AutoParameterPosition;
-      ss.flush();
 
-      IdentifierInfo& TemplateParamII = Context.Idents.get(
-                                        InventedTemplateParamName.c_str());
       // Turns out we must create the TemplateTypeParmDecl here to 
       // retrieve the corresponding template parameter type. 
       TemplateTypeParmDecl *CorrespondingTemplateParam =
@@ -1031,7 +1023,7 @@
         /*NameLoc*/ declarator.getLocStart(),  
         TemplateParameterDepth, 
         AutoParameterPosition,  // our template param index 
-        /* Identifier*/ &TemplateParamII, false, IsParameterPack);
+        /* Identifier*/ nullptr, false, IsParameterPack);
       LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
       // Replace the 'auto' in the function parameter with this invented 
       // template type parameter.
@@ -1109,8 +1101,9 @@
         S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
           << Result << DS.getSourceRange();
       else if (TypeQuals & DeclSpec::TQ_volatile)
-        S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers)
-          << Result << DS.getSourceRange();
+        S.Diag(DS.getVolatileSpecLoc(),
+               diag::warn_typecheck_function_qualifiers)
+            << Result << DS.getSourceRange();
       else {
         assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
                "Has CVRA quals but not C, V, R, or A?");
@@ -1176,6 +1169,7 @@
       Result = Qualified;
   }
 
+  assert(!Result.isNull() && "This function should not return a null type");
   return Result;
 }
 
@@ -1188,6 +1182,9 @@
 
 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
                                   Qualifiers Qs, const DeclSpec *DS) {
+  if (T.isNull())
+    return QualType();
+
   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
   // object or incomplete types shall not be restrict-qualified."
   if (Qs.hasRestrict()) {
@@ -1226,6 +1223,9 @@
 
 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
                                   unsigned CVRA, const DeclSpec *DS) {
+  if (T.isNull())
+    return QualType();
+
   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
   unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
 
@@ -1810,13 +1810,7 @@
   // exception specification.
   if (CheckDistantExceptionSpec(T)) {
     Diag(Loc, diag::err_distant_exception_spec);
-
-    // FIXME: If we're doing this as part of template instantiation,
-    // we should return immediately.
-
-    // Build the type anyway, but use the canonical type so that the
-    // exception specifiers are stripped off.
-    T = Context.getCanonicalType(T);
+    return QualType();
   }
 
   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
@@ -2334,6 +2328,7 @@
     }
   }
 
+  assert(!T.isNull() && "This function should not return a null type");
   return T;
 }
 
@@ -2476,14 +2471,31 @@
     }
   }
 
-  return S.Context.getDefaultCallingConvention(FTI.isVariadic,
-                                               IsCXXInstanceMethod);
+  CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
+                                                         IsCXXInstanceMethod);
+
+  // Attribute AT_OpenCLKernel affects the calling convention only on
+  // the SPIR target, hence it cannot be treated as a calling
+  // convention attribute. This is the simplest place to infer
+  // "spir_kernel" for OpenCL kernels on SPIR.
+  if (CC == CC_SpirFunction) {
+    for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
+         Attr; Attr = Attr->getNext()) {
+      if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
+        CC = CC_SpirKernel;
+        break;
+      }
+    }
+  }
+
+  return CC;
 }
 
 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
                                                 QualType declSpecType,
                                                 TypeSourceInfo *TInfo) {
-
+  // The TypeSourceInfo that this function returns will not be a null type.
+  // If there is an error, this function will fill in a dummy type as fallback.
   QualType T = declSpecType;
   Declarator &D = state.getDeclarator();
   Sema &S = state.getSema();
@@ -2791,8 +2803,16 @@
       // class type in C++.
       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
           !(S.getLangOpts().CPlusPlus &&
-            (T->isDependentType() || T->isRecordType())))
-        diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
+            (T->isDependentType() || T->isRecordType()))) {
+	if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
+	    D.getFunctionDefinitionKind() == FDK_Definition) {
+	  // [6.9.1/3] qualified void return is invalid on a C
+	  // function definition.  Apparently ok on declarations and
+	  // in C++ though (!)
+	  S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
+	} else
+	  diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
+      }
 
       // Objective-C ARC ownership qualifiers are ignored on the function
       // return type (by type canonicalization). Complain if this attribute
@@ -3048,7 +3068,8 @@
       }
 
       if (!ClsType.isNull())
-        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
+        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
+                                     D.getIdentifier());
       if (T.isNull()) {
         T = Context.IntTy;
         D.setInvalidType(true);
@@ -3068,6 +3089,8 @@
       processTypeAttrs(state, T, TAL_DeclChunk, attrs);
   }
 
+  assert(!T.isNull() && "T must not be null after this point");
+
   if (LangOpts.CPlusPlus && T->isFunctionType()) {
     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
@@ -3156,12 +3179,11 @@
   }
 
   // Apply any undistributed attributes from the declarator.
-  if (!T.isNull())
-    if (AttributeList *attrs = D.getAttributes())
-      processTypeAttrs(state, T, TAL_DeclName, attrs);
+  if (AttributeList *attrs = D.getAttributes())
+    processTypeAttrs(state, T, TAL_DeclName, attrs);
 
   // Diagnose any ignored type attributes.
-  if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
+  state.diagnoseIgnoredTypeAttrs(T);
 
   // C++0x [dcl.constexpr]p9:
   //  A constexpr specifier used in an object declaration declares the object
@@ -3172,7 +3194,7 @@
 
   // If there was an ellipsis in the declarator, the declaration declares a
   // parameter pack whose type may be a pack expansion type.
-  if (D.hasEllipsis() && !T.isNull()) {
+  if (D.hasEllipsis()) {
     // C++0x [dcl.fct]p13:
     //   A declarator-id or abstract-declarator containing an ellipsis shall
     //   only be used in a parameter-declaration. Such a parameter-declaration
@@ -3237,15 +3259,15 @@
     case Declarator::TemplateTypeArgContext:
       // FIXME: We may want to allow parameter packs in block-literal contexts
       // in the future.
-      S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
+      S.Diag(D.getEllipsisLoc(),
+             diag::err_ellipsis_in_declarator_not_parameter);
       D.setEllipsisLoc(SourceLocation());
       break;
     }
   }
 
-  if (T.isNull())
-    return Context.getNullTypeSourceInfo();
-  else if (D.isInvalidType())
+  assert(!T.isNull() && "T must not be null at the end of this function");
+  if (D.isInvalidType())
     return Context.getTrivialTypeSourceInfo(T);
 
   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
@@ -3264,8 +3286,6 @@
 
   TypeSourceInfo *ReturnTypeInfo = nullptr;
   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
-  if (T.isNull())
-    return Context.getNullTypeSourceInfo();
 
   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
     inferARCWriteback(state, T);
@@ -3379,8 +3399,6 @@
 
   TypeSourceInfo *ReturnTypeInfo = nullptr;
   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
-  if (declSpecTy.isNull())
-    return Context.getNullTypeSourceInfo();
 
   if (getLangOpts().ObjCAutoRefCount) {
     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
@@ -3425,8 +3443,6 @@
   case AttributedType::attr_pcs:
   case AttributedType::attr_pcs_vfp:
     return AttributeList::AT_Pcs;
-  case AttributedType::attr_pnaclcall:
-    return AttributeList::AT_PnaclCall;
   case AttributedType::attr_inteloclbicc:
     return AttributeList::AT_IntelOclBicc;
   case AttributedType::attr_ms_abi:
@@ -3981,6 +3997,8 @@
       ASIdx = LangAS::opencl_local; break;
     case AttributeList::AT_OpenCLConstantAddressSpace:
       ASIdx = LangAS::opencl_constant; break;
+    case AttributeList::AT_OpenCLGenericAddressSpace:
+      ASIdx = LangAS::opencl_generic; break;
     default:
       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
       ASIdx = 0; break;
@@ -4453,8 +4471,6 @@
         .Case("aapcs", AttributedType::attr_pcs)
         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
   }
-  case AttributeList::AT_PnaclCall:
-    return AttributedType::attr_pnaclcall;
   case AttributeList::AT_IntelOclBicc:
     return AttributedType::attr_inteloclbicc;
   case AttributeList::AT_MSABI:
@@ -4892,6 +4908,7 @@
     case AttributeList::AT_OpenCLGlobalAddressSpace:
     case AttributeList::AT_OpenCLLocalAddressSpace:
     case AttributeList::AT_OpenCLConstantAddressSpace:
+    case AttributeList::AT_OpenCLGenericAddressSpace:
     case AttributeList::AT_AddressSpace:
       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
       attr.setUsedAsTypeAttr();
@@ -5515,11 +5532,19 @@
   return T;
 }
 
-QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
+QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
+                                 bool AsUnevaluated) {
   ExprResult ER = CheckPlaceholderExpr(E);
   if (ER.isInvalid()) return QualType();
   E = ER.get();
 
+  if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
+      E->HasSideEffects(Context, false)) {
+    // The expression operand for decltype is in an unevaluated expression
+    // context, so side effects could result in unintended consequences.
+    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
+  }
+
   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
 }
 
diff --git a/lib/Sema/TreeTransform.h b/lib/Sema/TreeTransform.h
index 295d208..e1d0d18 100644
--- a/lib/Sema/TreeTransform.h
+++ b/lib/Sema/TreeTransform.h
@@ -7834,6 +7834,9 @@
 template<typename Derived>
 ExprResult
 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
+  if (InitListExpr *Syntactic = E->getSyntacticForm())
+    E = Syntactic;
+
   bool InitChanged = false;
 
   SmallVector<Expr*, 4> Inits;
@@ -7841,8 +7844,12 @@
                                   Inits, &InitChanged))
     return ExprError();
 
-  if (!getDerived().AlwaysRebuild() && !InitChanged)
-    return E;
+  if (!getDerived().AlwaysRebuild() && !InitChanged) {
+    // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
+    // in some cases. We can't reuse it in general, because the syntactic and
+    // semantic forms are linked, and we can't know that semantic form will
+    // match even if the syntactic form does.
+  }
 
   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
                                       E->getRBraceLoc(), E->getType());
@@ -9121,6 +9128,8 @@
   }
 
   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
+  Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
+
   // Transform the template parameters, and add them to the current
   // instantiation scope. The null case is handled correctly.
   LSI->GLTemplateParameterList = getDerived().TransformTemplateParameterList(
@@ -9145,10 +9154,10 @@
           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
                                               ExceptionStorage, Changed);
         });
+    if (NewCallOpType.isNull())
+      return ExprError();
     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
                                                         NewCallOpType);
-    if (!NewCallOpTSI)
-      return ExprError();
   }
 
   // Create the local class that will describe the lambda.
@@ -9168,6 +9177,10 @@
 
   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
 
+  // TransformLambdaScope will manage the function scope, so we can disable the
+  // cleanup.
+  FuncScopeCleanup.disable();
+
   return getDerived().TransformLambdaScope(E, NewCallOperator, 
       InitCaptureExprsAndTypes);
 }
@@ -10714,11 +10727,9 @@
        !BaseType->getAs<PointerType>()->getPointeeType()
                                               ->template getAs<RecordType>())){
     // This pseudo-destructor expression is still a pseudo-destructor.
-    return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
-                                             isArrow? tok::arrow : tok::period,
-                                             SS, ScopeType, CCLoc, TildeLoc,
-                                             Destroyed,
-                                             /*FIXME?*/true);
+    return SemaRef.BuildPseudoDestructorExpr(
+        Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
+        CCLoc, TildeLoc, Destroyed);
   }
 
   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
diff --git a/lib/Serialization/ASTCommon.cpp b/lib/Serialization/ASTCommon.cpp
index 1339322..04425ac 100644
--- a/lib/Serialization/ASTCommon.cpp
+++ b/lib/Serialization/ASTCommon.cpp
@@ -223,6 +223,24 @@
 }
 
 bool serialization::needsAnonymousDeclarationNumber(const NamedDecl *D) {
+  // Friend declarations in dependent contexts aren't anonymous in the usual
+  // sense, but they cannot be found by name lookup in their semantic context
+  // (or indeed in any context), so we treat them as anonymous.
+  //
+  // This doesn't apply to friend tag decls; Sema makes those available to name
+  // lookup in the surrounding context.
+  if (D->getFriendObjectKind() &&
+      D->getLexicalDeclContext()->isDependentContext() && !isa<TagDecl>(D)) {
+    // For function templates and class templates, the template is numbered and
+    // not its pattern.
+    if (auto *FD = dyn_cast<FunctionDecl>(D))
+      return !FD->getDescribedFunctionTemplate();
+    if (auto *RD = dyn_cast<CXXRecordDecl>(D))
+      return !RD->getDescribedClassTemplate();
+    return true;
+  }
+
+  // Otherwise, we only care about anonymous class members.
   if (D->getDeclName() || !isa<CXXRecordDecl>(D->getLexicalDeclContext()))
     return false;
   return isa<TagDecl>(D) || isa<FieldDecl>(D);
diff --git a/lib/Serialization/ASTCommon.h b/lib/Serialization/ASTCommon.h
index 38a0ff5..88cdbcf 100644
--- a/lib/Serialization/ASTCommon.h
+++ b/lib/Serialization/ASTCommon.h
@@ -15,6 +15,7 @@
 #define LLVM_CLANG_LIB_SERIALIZATION_ASTCOMMON_H
 
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclFriend.h"
 #include "clang/Serialization/ASTBitCodes.h"
 
 namespace clang {
@@ -85,6 +86,24 @@
 /// declaration number.
 bool needsAnonymousDeclarationNumber(const NamedDecl *D);
 
+/// \brief Visit each declaration within \c DC that needs an anonymous
+/// declaration number and call \p Visit with the declaration and its number.
+template<typename Fn> void numberAnonymousDeclsWithin(const DeclContext *DC,
+                                                      Fn Visit) {
+  unsigned Index = 0;
+  for (Decl *LexicalD : DC->decls()) {
+    // For a friend decl, we care about the declaration within it, if any.
+    if (auto *FD = dyn_cast<FriendDecl>(LexicalD))
+      LexicalD = FD->getFriendDecl();
+
+    auto *ND = dyn_cast_or_null<NamedDecl>(LexicalD);
+    if (!ND || !needsAnonymousDeclarationNumber(ND))
+      continue;
+
+    Visit(ND, Index++);
+  }
+}
+
 } // namespace serialization
 
 } // namespace clang
diff --git a/lib/Serialization/ASTReader.cpp b/lib/Serialization/ASTReader.cpp
index 1bbadfc..0ee2b2b 100644
--- a/lib/Serialization/ASTReader.cpp
+++ b/lib/Serialization/ASTReader.cpp
@@ -108,9 +108,12 @@
 }
 
 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
-    const HeaderSearchOptions &HSOpts, bool Complain) {
-  return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
-         Second->ReadHeaderSearchOptions(HSOpts, Complain);
+    const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
+    bool Complain) {
+  return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
+                                        Complain) ||
+         Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
+                                         Complain);
 }
 bool ChainedASTReaderListener::ReadPreprocessorOptions(
     const PreprocessorOptions &PPOpts, bool Complain,
@@ -464,7 +467,7 @@
     Macros[MacroName] = std::make_pair(MacroBody, false);
   }
 }
-         
+
 /// \brief Check the preprocessor options deserialized from the control block
 /// against the preprocessor options in an existing preprocessor.
 ///
@@ -591,6 +594,36 @@
                                   PP.getLangOpts());
 }
 
+/// Check the header search options deserialized from the control block
+/// against the header search options in an existing preprocessor.
+///
+/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
+static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                     StringRef SpecificModuleCachePath,
+                                     StringRef ExistingModuleCachePath,
+                                     DiagnosticsEngine *Diags,
+                                     const LangOptions &LangOpts) {
+  if (LangOpts.Modules) {
+    if (SpecificModuleCachePath != ExistingModuleCachePath) {
+      if (Diags)
+        Diags->Report(diag::err_pch_modulecache_mismatch)
+          << SpecificModuleCachePath << ExistingModuleCachePath;
+      return true;
+    }
+  }
+
+  return false;
+}
+
+bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                           StringRef SpecificModuleCachePath,
+                                           bool Complain) {
+  return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
+                                  PP.getHeaderSearchInfo().getModuleCachePath(),
+                                  Complain ? &Reader.Diags : nullptr,
+                                  PP.getLangOpts());
+}
+
 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
   PP.setCounterValue(Value);
 }
@@ -650,14 +683,14 @@
 
   Result.ID = Reader.getGlobalSelectorID(
       F, endian::readNext<uint32_t, little, unaligned>(d));
-  unsigned NumInstanceMethodsAndBits =
-      endian::readNext<uint16_t, little, unaligned>(d);
-  unsigned NumFactoryMethodsAndBits =
-      endian::readNext<uint16_t, little, unaligned>(d);
-  Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
-  Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
-  unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
-  unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
+  unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
+  unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
+  Result.InstanceBits = FullInstanceBits & 0x3;
+  Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
+  Result.FactoryBits = FullFactoryBits & 0x3;
+  Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
+  unsigned NumInstanceMethods = FullInstanceBits >> 3;
+  unsigned NumFactoryMethods = FullFactoryBits >> 3;
 
   // Load instance methods
   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
@@ -1029,7 +1062,7 @@
 /// \brief Read the line table in the source manager block.
 /// \returns true if there was an error.
 bool ASTReader::ParseLineTable(ModuleFile &F,
-                               SmallVectorImpl<uint64_t> &Record) {
+                               const RecordData &Record) {
   unsigned Idx = 0;
   LineTableInfo &LineTable = SourceMgr.getLineTable();
 
@@ -1037,10 +1070,7 @@
   std::map<int, int> FileIDs;
   for (int I = 0, N = Record[Idx++]; I != N; ++I) {
     // Extract the file name
-    unsigned FilenameLen = Record[Idx++];
-    std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
-    Idx += FilenameLen;
-    MaybeAddSystemRootToFilename(F, Filename);
+    auto Filename = ReadPath(F, Record, Idx);
     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
   }
 
@@ -1483,11 +1513,11 @@
 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
   return llvm::hash_combine(ikey.Size, ikey.ModTime);
 }
-    
+
 HeaderFileInfoTrait::internal_key_type 
 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
   internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
-                             FE->getName() };
+                             FE->getName(), /*Imported*/false };
   return ikey;
 }
     
@@ -1495,14 +1525,24 @@
   if (a.Size != b.Size || a.ModTime != b.ModTime)
     return false;
 
-  if (strcmp(a.Filename, b.Filename) == 0)
+  if (llvm::sys::path::is_absolute(a.Filename) &&
+      strcmp(a.Filename, b.Filename) == 0)
     return true;
   
   // Determine whether the actual files are equivalent.
   FileManager &FileMgr = Reader.getFileManager();
-  const FileEntry *FEA = FileMgr.getFile(a.Filename);
-  const FileEntry *FEB = FileMgr.getFile(b.Filename);
-  return (FEA && FEA == FEB);
+  auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
+    if (!Key.Imported)
+      return FileMgr.getFile(Key.Filename);
+
+    std::string Resolved = Key.Filename;
+    Reader.ResolveImportedPath(M, Resolved);
+    return FileMgr.getFile(Resolved);
+  };
+
+  const FileEntry *FEA = GetFile(a);
+  const FileEntry *FEB = GetFile(b);
+  return FEA && FEA == FEB;
 }
     
 std::pair<unsigned, unsigned>
@@ -1520,6 +1560,7 @@
   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
   ikey.Filename = (const char *)d;
+  ikey.Imported = true;
   return ikey;
 }
 
@@ -1559,7 +1600,14 @@
       FileManager &FileMgr = Reader.getFileManager();
       ModuleMap &ModMap =
           Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
-      ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
+      // FIXME: This information should be propagated through the
+      // SUBMODULE_HEADER etc records rather than from here.
+      // FIXME: We don't ever mark excluded headers.
+      std::string Filename = key.Filename;
+      if (key.Imported)
+        Reader.ResolveImportedPath(M, Filename);
+      Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
+      ModMap.addHeader(Mod, H, HFI.getHeaderRole());
     }
   }
 
@@ -2079,14 +2127,14 @@
   off_t StoredSize;
   time_t StoredTime;
   bool Overridden;
-  
+
   assert(Record[0] == ID && "Bogus stored ID or offset");
   StoredSize = static_cast<off_t>(Record[1]);
   StoredTime = static_cast<time_t>(Record[2]);
   Overridden = static_cast<bool>(Record[3]);
   Filename = Blob;
-  MaybeAddSystemRootToFilename(F, Filename);
-  
+  ResolveImportedPath(F, Filename);
+
   InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
   return R;
 }
@@ -2224,46 +2272,22 @@
   return IF;
 }
 
-const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
-  ModuleFile &M = ModuleMgr.getPrimaryModule();
-  std::string Filename = filenameStrRef;
-  MaybeAddSystemRootToFilename(M, Filename);
-  const FileEntry *File = FileMgr.getFile(Filename);
-  if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
-      M.OriginalDir != CurrentDir) {
-    std::string resolved = resolveFileRelativeToOriginalDir(Filename,
-                                                            M.OriginalDir,
-                                                            CurrentDir);
-    if (!resolved.empty())
-      File = FileMgr.getFile(resolved);
-  }
-
-  return File;
+/// \brief If we are loading a relocatable PCH or module file, and the filename
+/// is not an absolute path, add the system or module root to the beginning of
+/// the file name.
+void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
+  // Resolve relative to the base directory, if we have one.
+  if (!M.BaseDirectory.empty())
+    return ResolveImportedPath(Filename, M.BaseDirectory);
 }
 
-/// \brief If we are loading a relocatable PCH file, and the filename is
-/// not an absolute path, add the system root to the beginning of the file
-/// name.
-void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
-                                             std::string &Filename) {
-  // If this is not a relocatable PCH file, there's nothing to do.
-  if (!M.RelocatablePCH)
-    return;
-
+void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
     return;
 
-  if (isysroot.empty()) {
-    // If no system root was given, default to '/'
-    Filename.insert(Filename.begin(), '/');
-    return;
-  }
-
-  unsigned Length = isysroot.size();
-  if (isysroot[Length - 1] != '/')
-    Filename.insert(Filename.begin(), '/');
-
-  Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
+  SmallString<128> Buffer;
+  llvm::sys::path::append(Buffer, Prefix, Filename);
+  Filename.assign(Buffer.begin(), Buffer.end());
 }
 
 ASTReader::ASTReadResult
@@ -2383,6 +2407,9 @@
       }
 
       F.RelocatablePCH = Record[4];
+      // Relative paths in a relocatable PCH are relative to our sysroot.
+      if (F.RelocatablePCH)
+        F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
 
       const std::string &CurBranch = getClangFullRepositoryVersion();
       StringRef ASTBranch = Blob;
@@ -2413,10 +2440,7 @@
         off_t StoredSize = (off_t)Record[Idx++];
         time_t StoredModTime = (time_t)Record[Idx++];
         ASTFileSignature StoredSignature = Record[Idx++];
-        unsigned Length = Record[Idx++];
-        SmallString<128> ImportedFile(Record.begin() + Idx,
-                                      Record.begin() + Idx + Length);
-        Idx += Length;
+        auto ImportedFile = ReadPath(F, Record, Idx);
 
         // Load the AST file.
         switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
@@ -2500,7 +2524,7 @@
       F.OriginalSourceFileID = FileID::get(Record[0]);
       F.ActualOriginalSourceFileName = Blob;
       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
-      MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
+      ResolveImportedPath(F, F.OriginalSourceFileName);
       break;
 
     case ORIGINAL_FILE_ID:
@@ -2517,6 +2541,32 @@
         Listener->ReadModuleName(F.ModuleName);
       break;
 
+    case MODULE_DIRECTORY: {
+      assert(!F.ModuleName.empty() &&
+             "MODULE_DIRECTORY found before MODULE_NAME");
+      // If we've already loaded a module map file covering this module, we may
+      // have a better path for it (relative to the current build).
+      Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
+      if (M && M->Directory) {
+        // If we're implicitly loading a module, the base directory can't
+        // change between the build and use.
+        if (F.Kind != MK_ExplicitModule) {
+          const DirectoryEntry *BuildDir =
+              PP.getFileManager().getDirectory(Blob);
+          if (!BuildDir || BuildDir != M->Directory) {
+            if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
+              Diag(diag::err_imported_module_relocated)
+                  << F.ModuleName << Blob << M->Directory->getName();
+            return OutOfDate;
+          }
+        }
+        F.BaseDirectory = M->Directory->getName();
+      } else {
+        F.BaseDirectory = Blob;
+      }
+      break;
+    }
+
     case MODULE_MAP_FILE:
       if (ASTReadResult Result =
               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
@@ -2526,7 +2576,7 @@
     case INPUT_FILE_OFFSETS:
       NumInputs = Record[0];
       NumUserInputs = Record[1];
-      F.InputFileOffsets = (const uint32_t *)Blob.data();
+      F.InputFileOffsets = (const uint64_t *)Blob.data();
       F.InputFilesLoaded.resize(NumInputs);
       break;
     }
@@ -3337,7 +3387,7 @@
                                   const ModuleFile *ImportedBy,
                                   unsigned ClientLoadCapabilities) {
   unsigned Idx = 0;
-  F.ModuleMapPath = ReadString(Record, Idx);
+  F.ModuleMapPath = ReadPath(F, Record, Idx);
 
   if (F.Kind == MK_ExplicitModule) {
     // For an explicitly-loaded module, we don't care whether the original
@@ -3384,7 +3434,7 @@
     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
       // FIXME: we should use input files rather than storing names.
-      std::string Filename = ReadString(Record, Idx);
+      std::string Filename = ReadPath(F, Record, Idx);
       const FileEntry *F =
           FileMgr.getFile(Filename, false, false);
       if (F == nullptr) {
@@ -3440,7 +3490,7 @@
   bool Found = false;
   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
     if (!Found) {
-      if (List->Method == Method) {
+      if (List->getMethod() == Method) {
         Found = true;
       } else {
         // Keep searching.
@@ -3449,9 +3499,9 @@
     }
 
     if (List->getNext())
-      List->Method = List->getNext()->Method;
+      List->setMethod(List->getNext()->getMethod());
     else
-      List->Method = Method;
+      List->setMethod(Method);
   }
 }
 
@@ -4167,16 +4217,19 @@
     const LangOptions &ExistingLangOpts;
     const TargetOptions &ExistingTargetOpts;
     const PreprocessorOptions &ExistingPPOpts;
+    std::string ExistingModuleCachePath;
     FileManager &FileMgr;
-    
+
   public:
     SimplePCHValidator(const LangOptions &ExistingLangOpts,
                        const TargetOptions &ExistingTargetOpts,
                        const PreprocessorOptions &ExistingPPOpts,
+                       StringRef ExistingModuleCachePath,
                        FileManager &FileMgr)
       : ExistingLangOpts(ExistingLangOpts),
         ExistingTargetOpts(ExistingTargetOpts),
         ExistingPPOpts(ExistingPPOpts),
+        ExistingModuleCachePath(ExistingModuleCachePath),
         FileMgr(FileMgr)
     {
     }
@@ -4190,6 +4243,13 @@
                            bool Complain) override {
       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
     }
+    bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
+                                 StringRef SpecificModuleCachePath,
+                                 bool Complain) override {
+      return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
+                                      ExistingModuleCachePath,
+                                      nullptr, ExistingLangOpts);
+    }
     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
                                  bool Complain,
                                  std::string &SuggestedPredefines) override {
@@ -4251,6 +4311,7 @@
   
   // Scan for ORIGINAL_FILE inside the control block.
   RecordData Record;
+  std::string ModuleDir;
   while (1) {
     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
@@ -4275,9 +4336,14 @@
     case MODULE_NAME:
       Listener.ReadModuleName(Blob);
       break;
+    case MODULE_DIRECTORY:
+      ModuleDir = Blob;
+      break;
     case MODULE_MAP_FILE: {
       unsigned Idx = 0;
-      Listener.ReadModuleMapFile(ReadString(Record, Idx));
+      auto Path = ReadString(Record, Idx);
+      ResolveImportedPath(Path, ModuleDir);
+      Listener.ReadModuleMapFile(Path);
       break;
     }
     case LANGUAGE_OPTIONS:
@@ -4320,7 +4386,7 @@
 
       unsigned NumInputFiles = Record[0];
       unsigned NumUserFiles = Record[1];
-      const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
+      const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
       for (unsigned I = 0; I != NumInputFiles; ++I) {
         // Go find this input file.
         bool isSystemFile = I >= NumUserFiles;
@@ -4339,7 +4405,10 @@
         switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
         case INPUT_FILE:
           bool Overridden = static_cast<bool>(Record[3]);
-          shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
+          std::string Filename = Blob;
+          ResolveImportedPath(Filename, ModuleDir);
+          shouldContinue =
+              Listener.visitInputFile(Filename, isSystemFile, Overridden);
           break;
         }
         if (!shouldContinue)
@@ -4356,11 +4425,9 @@
       while (Idx < N) {
         // Read information about the AST file.
         Idx += 5; // ImportLoc, Size, ModTime, Signature
-        unsigned Length = Record[Idx++];
-        SmallString<128> ImportedFile(Record.begin() + Idx,
-                                      Record.begin() + Idx + Length);
-        Idx += Length;
-        Listener.visitImport(ImportedFile);
+        std::string Filename = ReadString(Record, Idx);
+        ResolveImportedPath(Filename, ModuleDir);
+        Listener.visitImport(Filename);
       }
       break;
     }
@@ -4377,8 +4444,10 @@
                                     FileManager &FileMgr,
                                     const LangOptions &LangOpts,
                                     const TargetOptions &TargetOpts,
-                                    const PreprocessorOptions &PPOpts) {
-  SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
+                                    const PreprocessorOptions &PPOpts,
+                                    std::string ExistingModuleCachePath) {
+  SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
+                               ExistingModuleCachePath, FileMgr);
   return !readASTFileControlBlock(Filename, FileMgr, validator);
 }
 
@@ -4509,9 +4578,13 @@
         if (!CurrentModule->getUmbrellaHeader())
           ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
         else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
-          if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
-            Error("mismatched umbrella headers in submodule");
-          return OutOfDate;
+          // This can be a spurious difference caused by changing the VFS to
+          // point to a different copy of the file, and it is too late to
+          // to rebuild safely.
+          // FIXME: If we wrote the virtual paths instead of the 'real' paths,
+          // after input file validation only real problems would remain and we
+          // could just error. For now, assume it's okay.
+          break;
         }
       }
       break;
@@ -4749,8 +4822,10 @@
   HSOpts.UseStandardSystemIncludes = Record[Idx++];
   HSOpts.UseStandardCXXIncludes = Record[Idx++];
   HSOpts.UseLibcxx = Record[Idx++];
+  std::string SpecificModuleCachePath = ReadString(Record, Idx);
 
-  return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
+  return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
+                                          Complain);
 }
 
 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
@@ -4799,21 +4874,22 @@
   return std::make_pair(M, LocalIndex);
 }
 
-std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
+llvm::iterator_range<PreprocessingRecord::iterator>
 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
                                              Mod.NumPreprocessedEntities);
 
-  return std::make_pair(PreprocessingRecord::iterator(),
-                        PreprocessingRecord::iterator());
+  return llvm::make_range(PreprocessingRecord::iterator(),
+                          PreprocessingRecord::iterator());
 }
 
-std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
+llvm::iterator_range<ASTReader::ModuleDeclIterator>
 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
-  return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
-                        ModuleDeclIterator(this, &Mod,
-                                 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
+  return llvm::make_range(
+      ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
+      ModuleDeclIterator(this, &Mod,
+                         Mod.FileSortedDecls + Mod.NumFileSortedDecls));
 }
 
 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
@@ -6057,6 +6133,12 @@
   return GetDecl(ID);
 }
 
+template<typename TemplateSpecializationDecl>
+static void completeRedeclChainForTemplateSpecialization(Decl *D) {
+  if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
+    TSD->getSpecializedTemplate()->LoadLazySpecializations();
+}
+
 void ASTReader::CompleteRedeclChain(const Decl *D) {
   if (NumCurrentElementsDeserializing) {
     // We arrange to not care about the complete redeclaration chain while we're
@@ -6090,6 +6172,15 @@
       D->getDeclContext()->decls_begin();
     }
   }
+
+  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
+    CTSD->getSpecializedTemplate()->LoadLazySpecializations();
+  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
+    VTSD->getSpecializedTemplate()->LoadLazySpecializations();
+  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
+    if (auto *Template = FD->getPrimaryTemplate())
+      Template->LoadLazySpecializations();
+  }
 }
 
 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
@@ -6436,13 +6527,16 @@
     ArrayRef<const DeclContext *> Contexts;
     DeclarationName Name;
     SmallVectorImpl<NamedDecl *> &Decls;
+    llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
 
   public:
     DeclContextNameLookupVisitor(ASTReader &Reader,
                                  ArrayRef<const DeclContext *> Contexts,
                                  DeclarationName Name,
-                                 SmallVectorImpl<NamedDecl *> &Decls)
-      : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
+                                 SmallVectorImpl<NamedDecl *> &Decls,
+                                 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
+      : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
+        DeclSet(DeclSet) { }
 
     static bool visit(ModuleFile &M, void *UserData) {
       DeclContextNameLookupVisitor *This
@@ -6491,7 +6585,8 @@
 
         // Record this declaration.
         FoundAnything = true;
-        This->Decls.push_back(ND);
+        if (This->DeclSet.insert(ND).second)
+          This->Decls.push_back(ND);
       }
 
       return FoundAnything;
@@ -6531,6 +6626,7 @@
   Deserializing LookupResults(this);
 
   SmallVector<NamedDecl *, 64> Decls;
+  llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
 
   // Compute the declaration contexts we need to look into. Multiple such
   // declaration contexts occur when two declaration contexts from disjoint
@@ -6548,7 +6644,7 @@
   }
 
   auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
-    DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
+    DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
 
     // If we can definitively determine which module file to look into,
     // only look there. Otherwise, look in all module files.
@@ -6574,9 +6670,15 @@
         (Kind == DeclarationName::CXXOperatorName &&
          Name.getCXXOverloadedOperator() == OO_Equal)) {
       auto Merged = MergedLookups.find(DC);
-      if (Merged != MergedLookups.end())
-        for (auto *MergedDC : Merged->second)
-          LookUpInContexts(MergedDC);
+      if (Merged != MergedLookups.end()) {
+        for (unsigned I = 0; I != Merged->second.size(); ++I) {
+          const DeclContext *Context = Merged->second[I];
+          LookUpInContexts(Context);
+          // We might have just added some more merged lookups. If so, our
+          // iterator is now invalid, so grab a fresh one before continuing.
+          Merged = MergedLookups.find(DC);
+        }
+      }
     }
   }
 
@@ -6592,6 +6694,7 @@
     ASTReader &Reader;
     SmallVectorImpl<const DeclContext *> &Contexts;
     DeclsMap &Decls;
+    llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
     bool VisitAll;
 
   public:
@@ -6636,7 +6739,8 @@
 
           // Record this declaration.
           FoundAnything = true;
-          This->Decls[ND->getDeclName()].push_back(ND);
+          if (This->DeclSet.insert(ND).second)
+            This->Decls[ND->getDeclName()].push_back(ND);
         }
       }
 
@@ -7032,15 +7136,18 @@
     unsigned PriorGeneration;
     unsigned InstanceBits;
     unsigned FactoryBits;
+    bool InstanceHasMoreThanOneDecl;
+    bool FactoryHasMoreThanOneDecl;
     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
 
   public:
-    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 
+    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
                           unsigned PriorGeneration)
-      : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
-        InstanceBits(0), FactoryBits(0) { }
-    
+        : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
+          InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
+          FactoryHasMoreThanOneDecl(false) {}
+
     static bool visit(ModuleFile &M, void *UserData) {
       ReadMethodPoolVisitor *This
         = static_cast<ReadMethodPoolVisitor *>(UserData);
@@ -7074,6 +7181,8 @@
       This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
       This->InstanceBits = Data.InstanceBits;
       This->FactoryBits = Data.FactoryBits;
+      This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
+      This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
       return true;
     }
     
@@ -7089,6 +7198,10 @@
 
     unsigned getInstanceBits() const { return InstanceBits; }
     unsigned getFactoryBits() const { return FactoryBits; }
+    bool instanceHasMoreThanOneDecl() const {
+      return InstanceHasMoreThanOneDecl;
+    }
+    bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
   };
 } } // end namespace clang::serialization
 
@@ -7123,11 +7236,17 @@
   Sema &S = *getSema();
   Sema::GlobalMethodPool::iterator Pos
     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
-  
+
+  Pos->second.first.setBits(Visitor.getInstanceBits());
+  Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
+  Pos->second.second.setBits(Visitor.getFactoryBits());
+  Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
+
+  // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
+  // when building a module we keep every method individually and may need to
+  // update hasMoreThanOneDecl as we add the methods.
   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
-  Pos->second.first.setBits(Visitor.getInstanceBits());
-  Pos->second.second.setBits(Visitor.getFactoryBits());
 }
 
 void ASTReader::ReadKnownNamespaces(
@@ -8040,6 +8159,13 @@
   return Result;
 }
 
+std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
+                                unsigned &Idx) {
+  std::string Filename = ReadString(Record, Idx);
+  ResolveImportedPath(F, Filename);
+  return Filename;
+}
+
 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 
                                          unsigned &Idx) {
   unsigned Major = Record[Idx++];
@@ -8247,7 +8373,12 @@
       loadDeclUpdateRecords(Update.first, Update.second);
     }
   }
-  
+
+  // At this point, all update records for loaded decls are in place, so any
+  // fake class definitions should have become real.
+  assert(PendingFakeDefinitionData.empty() &&
+         "faked up a class definition but never saw the real one");
+
   // If we deserialized any C++ or Objective-C class definitions, any
   // Objective-C protocol definitions, or any redeclarable templates, make sure
   // that all redeclarations point to the definitions. Note that this can only 
@@ -8389,6 +8520,10 @@
       // completed. We only really need to mark FieldDecls as invalid here.
       if (!isa<TagDecl>(D))
         D->setInvalidDecl();
+      
+      // Ensure we don't accidentally recursively enter deserialization while
+      // we're producing our diagnostic.
+      Deserializing RecursionGuard(this);
 
       std::string CanonDefModule =
           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
@@ -8410,6 +8545,13 @@
     }
   }
 
+  if (OdrMergeFailures.empty())
+    return;
+
+  // Ensure we don't accidentally recursively enter deserialization while
+  // we're producing our diagnostics.
+  Deserializing RecursionGuard(this);
+
   // Issue any pending ODR-failure diagnostics.
   for (auto &Merge : OdrMergeFailures) {
     // If we've already pointed out a specific problem with this class, don't
diff --git a/lib/Serialization/ASTReaderDecl.cpp b/lib/Serialization/ASTReaderDecl.cpp
index a783183..339d0b8 100644
--- a/lib/Serialization/ASTReaderDecl.cpp
+++ b/lib/Serialization/ASTReaderDecl.cpp
@@ -103,11 +103,11 @@
       return Reader.getSubmodule(readSubmoduleID(R, I));
     }
 
-    void ReadCXXRecordDefinition(CXXRecordDecl *D);
+    void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
                                const RecordData &R, unsigned &I);
     void MergeDefinitionData(CXXRecordDecl *D,
-                             struct CXXRecordDecl::DefinitionData &NewDD);
+                             struct CXXRecordDecl::DefinitionData &&NewDD);
 
     static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
                                                  DeclContext *DC,
@@ -124,20 +124,22 @@
     class RedeclarableResult {
       ASTReader &Reader;
       GlobalDeclID FirstID;
+      Decl *MergeWith;
       mutable bool Owning;
       Decl::Kind DeclKind;
-      
-      void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
-      
+
+      void operator=(RedeclarableResult &) = delete;
+
     public:
       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
-                         Decl::Kind DeclKind)
-        : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
+                         Decl *MergeWith, Decl::Kind DeclKind)
+        : Reader(Reader), FirstID(FirstID), MergeWith(MergeWith),
+          Owning(true), DeclKind(DeclKind) {}
 
-      RedeclarableResult(const RedeclarableResult &Other)
-        : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
-          DeclKind(Other.DeclKind)
-      { 
+      RedeclarableResult(RedeclarableResult &&Other)
+        : Reader(Other.Reader), FirstID(Other.FirstID),
+          MergeWith(Other.MergeWith), Owning(Other.Owning),
+          DeclKind(Other.DeclKind) {
         Other.Owning = false;
       }
 
@@ -146,10 +148,14 @@
             Reader.PendingDeclChainsKnown.insert(FirstID).second)
           Reader.PendingDeclChains.push_back(FirstID);
       }
-      
+
       /// \brief Retrieve the first ID.
       GlobalDeclID getFirstID() const { return FirstID; }
-      
+
+      /// \brief Get a known declaration that this should be merged with, if
+      /// any.
+      Decl *getKnownMergeTarget() const { return MergeWith; }
+
       /// \brief Do not introduce this declaration ID into the set of pending
       /// declaration chains.
       void suppress() {
@@ -171,7 +177,7 @@
       unsigned AnonymousDeclNumber;
       IdentifierInfo *TypedefNameForLinkage;
 
-      void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
+      void operator=(FindExistingResult&) = delete;
 
     public:
       FindExistingResult(ASTReader &Reader)
@@ -205,6 +211,8 @@
       operator T*() const { return dyn_cast_or_null<T>(Existing); }
     };
 
+    static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
+                                                    DeclContext *DC);
     FindExistingResult findExisting(NamedDecl *D);
 
   public:
@@ -470,8 +478,7 @@
 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
   VisitDecl(ND);
   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
-  if (needsAnonymousDeclarationNumber(ND))
-    AnonymousDeclNumber = Record[Idx++];
+  AnonymousDeclNumber = Record[Idx++];
 }
 
 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
@@ -1353,11 +1360,27 @@
 }
 
 void ASTDeclReader::MergeDefinitionData(
-    CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &MergeDD) {
+    CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
   assert(D->DefinitionData.getNotUpdated() &&
          "merging class definition into non-definition");
   auto &DD = *D->DefinitionData.getNotUpdated();
 
+  auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
+  if (PFDI != Reader.PendingFakeDefinitionData.end() &&
+      PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
+    // We faked up this definition data because we found a class for which we'd
+    // not yet loaded the definition. Replace it with the real thing now.
+    assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
+    PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
+
+    // Don't change which declaration is the definition; that is required
+    // to be invariant once we select it.
+    auto *Def = DD.Definition;
+    DD = std::move(MergeDD);
+    DD.Definition = Def;
+    return;
+  }
+
   // If the new definition has new special members, let the name lookup
   // code know that it needs to look in the new definition too.
   //
@@ -1442,7 +1465,7 @@
     Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition);
 }
 
-void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D) {
+void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
   struct CXXRecordDecl::DefinitionData *DD;
   ASTContext &C = Reader.getContext();
 
@@ -1457,19 +1480,29 @@
 
   ReadCXXDefinitionData(*DD, Record, Idx);
 
-  // If we're reading an update record, we might already have a definition for
-  // this record. If so, just merge into it.
-  if (D->DefinitionData.getNotUpdated()) {
-    MergeDefinitionData(D, *DD);
+  // We might already have a definition for this record. This can happen either
+  // because we're reading an update record, or because we've already done some
+  // merging. Either way, just merge into it.
+  CXXRecordDecl *Canon = D->getCanonicalDecl();
+  if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
+    if (CanonDD->Definition != DD->Definition)
+      Reader.MergedDeclContexts.insert(
+          std::make_pair(DD->Definition, CanonDD->Definition));
+    MergeDefinitionData(Canon, std::move(*DD));
+    D->DefinitionData = Canon->DefinitionData;
     return;
   }
 
   // Propagate the DefinitionData pointer to the canonical declaration, so
   // that all other deserialized declarations will see it.
-  CXXRecordDecl *Canon = D->getCanonicalDecl();
   if (Canon == D) {
     D->DefinitionData = DD;
     D->IsCompleteDefinition = true;
+
+    // If this is an update record, we can have redeclarations already. Make a
+    // note that we need to propagate the DefinitionData pointer onto them.
+    if (Update)
+      Reader.PendingDefinitions.insert(D);
   } else if (auto *CanonDD = Canon->DefinitionData.getNotUpdated()) {
     // We have already deserialized a definition of this record. This
     // definition is no longer really a definition. Note that the pre-existing
@@ -1478,7 +1511,7 @@
         std::make_pair(D, CanonDD->Definition));
     D->DefinitionData = Canon->DefinitionData;
     D->IsCompleteDefinition = false;
-    MergeDefinitionData(D, *DD);
+    MergeDefinitionData(D, std::move(*DD));
   } else {
     Canon->DefinitionData = DD;
     D->DefinitionData = Canon->DefinitionData;
@@ -1535,7 +1568,7 @@
 
   bool WasDefinition = Record[Idx++];
   if (WasDefinition)
-    ReadCXXRecordDefinition(D);
+    ReadCXXRecordDefinition(D, /*Update*/false);
   else
     // Propagate DefinitionData pointer from the canonical declaration.
     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
@@ -1823,7 +1856,7 @@
         // definition.
         if (auto *DDD = D->DefinitionData.getNotUpdated()) {
           if (auto *CanonDD = CanonSpec->DefinitionData.getNotUpdated()) {
-            MergeDefinitionData(CanonSpec, *DDD);
+            MergeDefinitionData(CanonSpec, std::move(*DDD));
             Reader.PendingDefinitions.erase(D);
             Reader.MergedDeclContexts.insert(
                 std::make_pair(D, CanonDD->Definition));
@@ -2049,15 +2082,23 @@
 }
 
 template <typename T>
-ASTDeclReader::RedeclarableResult 
+ASTDeclReader::RedeclarableResult
 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
   DeclID FirstDeclID = ReadDeclID(Record, Idx);
-  
+  Decl *MergeWith = nullptr;
+
   // 0 indicates that this declaration was the only declaration of its entity,
   // and is used for space optimization.
   if (FirstDeclID == 0)
     FirstDeclID = ThisDeclID;
-  
+  else if (Record[Idx++]) {
+    // We need to merge with FirstDeclID. Read it now to ensure that it is
+    // before us in the redecl chain, then forget we saw it so that we will
+    // merge with it.
+    MergeWith = Reader.GetDecl(FirstDeclID);
+    FirstDeclID = ThisDeclID;
+  }
+
   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
   if (FirstDecl != D) {
     // We delay loading of the redeclaration chain to avoid deeply nested calls.
@@ -2072,7 +2113,7 @@
                              
   // The result structure takes care to note that we need to load the 
   // other declaration chains for this ID.
-  return RedeclarableResult(Reader, FirstDeclID,
+  return RedeclarableResult(Reader, FirstDeclID, MergeWith,
                             static_cast<T *>(D)->getKind());
 }
 
@@ -2099,7 +2140,10 @@
   if (!Reader.getContext().getLangOpts().Modules)
     return;
 
-  if (FindExistingResult ExistingRes = findExisting(D))
+  if (auto *Existing = Redecl.getKnownMergeTarget())
+    // We already know of an existing declaration we should merge with.
+    mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
+  else if (FindExistingResult ExistingRes = findExisting(D))
     if (T *Existing = ExistingRes)
       mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
 }
@@ -2120,7 +2164,8 @@
   auto *DPattern = D->getTemplatedDecl();
   auto *ExistingPattern = Existing->getTemplatedDecl();
   RedeclarableResult Result(Reader, DPattern->getCanonicalDecl()->getGlobalID(),
-                            DPattern->getKind());
+                            /*MergeWith*/ExistingPattern, DPattern->getKind());
+
   if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
     // Merge with any existing definition.
     // FIXME: This is duplicated in several places. Refactor.
@@ -2128,7 +2173,7 @@
         cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
     if (auto *DDD = DClass->DefinitionData.getNotUpdated()) {
       if (auto *ExistingDD = ExistingClass->DefinitionData.getNotUpdated()) {
-        MergeDefinitionData(ExistingClass, *DDD);
+        MergeDefinitionData(ExistingClass, std::move(*DDD));
         Reader.PendingDefinitions.erase(DClass);
         Reader.MergedDeclContexts.insert(
             std::make_pair(DClass, ExistingDD->Definition));
@@ -2529,42 +2574,68 @@
 
 /// Find the context in which we should search for previous declarations when
 /// looking for declarations to merge.
-static DeclContext *getPrimaryContextForMerging(DeclContext *DC) {
+DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
+                                                        DeclContext *DC) {
   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
     return ND->getOriginalNamespace();
 
-  // There is one tricky case here: if DC is a class with no definition, then
-  // we're merging a declaration whose definition is added by an update record,
-  // but we've not yet loaded that update record. In this case, we use the
-  // canonical declaration for merging until we get a real definition.
-  // FIXME: When we add a definition, we may need to move the partial lookup
-  // information from the canonical declaration onto the chosen definition.
-  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
-    return RD->getPrimaryContext();
+  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
+    // Try to dig out the definition.
+    auto *DD = RD->DefinitionData.getNotUpdated();
+    if (!DD)
+      DD = RD->getCanonicalDecl()->DefinitionData.getNotUpdated();
+
+    // If there's no definition yet, then DC's definition is added by an update
+    // record, but we've not yet loaded that update record. In this case, we
+    // commit to DC being the canonical definition now, and will fix this when
+    // we load the update record.
+    if (!DD) {
+      DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD);
+      RD->IsCompleteDefinition = true;
+      RD->DefinitionData = DD;
+      RD->getCanonicalDecl()->DefinitionData = DD;
+
+      // Track that we did this horrible thing so that we can fix it later.
+      Reader.PendingFakeDefinitionData.insert(
+          std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
+    }
+
+    return DD->Definition;
+  }
 
   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
                                                       : nullptr;
 
+  // We can see the TU here only if we have no Sema object. In that case,
+  // there's no TU scope to look in, so using the DC alone is sufficient.
+  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
+    return TU;
+
   return nullptr;
 }
 
 ASTDeclReader::FindExistingResult::~FindExistingResult() {
+  // Record that we had a typedef name for linkage whether or not we merge
+  // with that declaration.
+  if (TypedefNameForLinkage) {
+    DeclContext *DC = New->getDeclContext()->getRedeclContext();
+    Reader.ImportedTypedefNamesForLinkage.insert(
+        std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
+    return;
+  }
+
   if (!AddResult || Existing)
     return;
 
   DeclarationName Name = New->getDeclName();
   DeclContext *DC = New->getDeclContext()->getRedeclContext();
-  if (TypedefNameForLinkage) {
-    Reader.ImportedTypedefNamesForLinkage.insert(
-        std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
-  } else if (!Name) {
-    assert(needsAnonymousDeclarationNumber(New));
+  if (needsAnonymousDeclarationNumber(New)) {
     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
                                AnonymousDeclNumber, New);
   } else if (DC->isTranslationUnit() && Reader.SemaObj) {
     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, Name);
-  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
+  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
     // Add the declaration to its redeclaration context so later merging
     // lookups will find it.
     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
@@ -2608,17 +2679,12 @@
   // If this is the first time, but we have parsed a declaration of the context,
   // build the anonymous declaration list from the parsed declaration.
   if (!cast<Decl>(DC)->isFromASTFile()) {
-    unsigned Index = 0;
-    for (Decl *LexicalD : DC->decls()) {
-      auto *ND = dyn_cast<NamedDecl>(LexicalD);
-      if (!ND || !needsAnonymousDeclarationNumber(ND))
-        continue;
-      if (Previous.size() == Index)
+    numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) {
+      if (Previous.size() == Number)
         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
       else
-        Previous[Index] = cast<NamedDecl>(ND->getCanonicalDecl());
-      ++Index;
-    }
+        Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
+    });
   }
 
   return Index < Previous.size() ? Previous[Index] : nullptr;
@@ -2667,10 +2733,9 @@
     // was not imported.
   }
 
-  if (!Name) {
+  if (needsAnonymousDeclarationNumber(D)) {
     // This is an anonymous declaration that we may need to merge. Look it up
     // in its context by number.
-    assert(needsAnonymousDeclarationNumber(D));
     if (auto *Existing = getAnonymousDeclForMerging(
             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
       if (isSameEntity(Existing, D))
@@ -2710,7 +2775,7 @@
           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
                                     TypedefNameForLinkage);
     }
-  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(DC)) {
+  } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
@@ -3199,47 +3264,53 @@
 }
 
 namespace {
-  /// \brief Module visitor class that finds all of the redeclarations of a 
-  /// 
+  /// \brief Module visitor class that finds all of the redeclarations of a
+  /// redeclarable declaration.
   class RedeclChainVisitor {
     ASTReader &Reader;
     SmallVectorImpl<DeclID> &SearchDecls;
     llvm::SmallPtrSetImpl<Decl *> &Deserialized;
     GlobalDeclID CanonID;
     SmallVector<Decl *, 4> Chain;
-    
+
   public:
     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
                        llvm::SmallPtrSetImpl<Decl *> &Deserialized,
                        GlobalDeclID CanonID)
       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
-        CanonID(CanonID) { 
-      for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
-        addToChain(Reader.GetDecl(SearchDecls[I]));
+        CanonID(CanonID) {
+      // Ensure that the canonical ID goes at the start of the chain.
+      addToChain(Reader.GetDecl(CanonID));
     }
-    
+
     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
       if (Preorder)
         return false;
-      
+
       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
     }
-    
+
     void addToChain(Decl *D) {
       if (!D)
         return;
-      
+
       if (Deserialized.erase(D))
         Chain.push_back(D);
     }
-    
+
     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
       // Map global ID of the first declaration down to the local ID
       // used in this module file.
       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
       if (!ID)
         return;
-      
+
+      // If the search decl was from this module, add it to the chain before any
+      // of its redeclarations in this module or users of it, and after any from
+      // imported modules.
+      if (CanonID != GlobalID && Reader.isDeclIDFromModule(GlobalID, M))
+        addToChain(Reader.GetDecl(GlobalID));
+
       // Perform a binary search to find the local redeclarations for this
       // declaration (if any).
       const LocalRedeclarationsInfo Compare = { ID, 0 };
@@ -3513,13 +3584,25 @@
   while (Idx < Record.size()) {
     switch ((DeclUpdateKind)Record[Idx++]) {
     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
+      auto *RD = cast<CXXRecordDecl>(D);
       // FIXME: If we also have an update record for instantiating the
       // definition of D, we need that to happen before we get here.
       Decl *MD = Reader.ReadDecl(ModuleFile, Record, Idx);
       assert(MD && "couldn't read decl from update record");
       // FIXME: We should call addHiddenDecl instead, to add the member
       // to its DeclContext.
-      cast<CXXRecordDecl>(D)->addedMember(MD);
+      RD->addedMember(MD);
+
+      // If we've added a new special member to a class definition that is not
+      // the canonical definition, then we need special member lookups in the
+      // canonical definition to also look into our class.
+      auto *DD = RD->DefinitionData.getNotUpdated();
+      if (DD && DD->Definition != RD) {
+        auto &Merged = Reader.MergedLookups[DD->Definition];
+        // FIXME: Avoid the linear-time scan here.
+        if (std::find(Merged.begin(), Merged.end(), RD) == Merged.end())
+          Merged.push_back(RD);
+      }
       break;
     }
 
@@ -3583,16 +3666,20 @@
 
     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
       auto *RD = cast<CXXRecordDecl>(D);
-      bool HadDefinition = RD->getDefinition();
-      ReadCXXRecordDefinition(RD);
+      auto *OldDD = RD->DefinitionData.getNotUpdated();
+      bool HadRealDefinition =
+          OldDD && (OldDD->Definition != RD ||
+                    !Reader.PendingFakeDefinitionData.count(OldDD));
+      ReadCXXRecordDefinition(RD, /*Update*/true);
+
       // Visible update is handled separately.
       uint64_t LexicalOffset = Record[Idx++];
-      if (!HadDefinition && LexicalOffset) {
+      if (!HadRealDefinition && LexicalOffset) {
         RD->setHasExternalLexicalStorage(true);
         Reader.ReadDeclContextStorage(ModuleFile, ModuleFile.DeclsCursor,
-                                          std::make_pair(LexicalOffset, 0),
-                                          ModuleFile.DeclContextInfos[RD]);
-        Reader.PendingDefinitions.insert(RD);
+                                      std::make_pair(LexicalOffset, 0),
+                                      ModuleFile.DeclContextInfos[RD]);
+        Reader.PendingFakeDefinitionData.erase(OldDD);
       }
 
       auto TSK = (TemplateSpecializationKind)Record[Idx++];
diff --git a/lib/Serialization/ASTReaderInternals.h b/lib/Serialization/ASTReaderInternals.h
index 60494b1..d1b032b 100644
--- a/lib/Serialization/ASTReaderInternals.h
+++ b/lib/Serialization/ASTReaderInternals.h
@@ -156,6 +156,8 @@
     SelectorID ID;
     unsigned InstanceBits;
     unsigned FactoryBits;
+    bool InstanceHasMoreThanOneDecl;
+    bool FactoryHasMoreThanOneDecl;
     SmallVector<ObjCMethodDecl *, 2> Instance;
     SmallVector<ObjCMethodDecl *, 2> Factory;
   };
@@ -194,8 +196,8 @@
 ///
 /// The on-disk hash table contains a mapping from each header path to 
 /// information about that header (how many times it has been included, its
-/// controlling macro, etc.). Note that we actually hash based on the 
-/// filename, and support "deep" comparisons of file names based on current
+/// controlling macro, etc.). Note that we actually hash based on the size
+/// and mtime, and support "deep" comparisons of file names based on current
 /// inode numbers, so that the search can cope with non-normalized path names
 /// and symlinks.
 class HeaderFileInfoTrait {
@@ -211,6 +213,7 @@
     off_t Size;
     time_t ModTime;
     const char *Filename;
+    bool Imported;
   };
   typedef const internal_key_type &internal_key_ref;
   
diff --git a/lib/Serialization/ASTReaderStmt.cpp b/lib/Serialization/ASTReaderStmt.cpp
index e0308d7..4ef2e73 100644
--- a/lib/Serialization/ASTReaderStmt.cpp
+++ b/lib/Serialization/ASTReaderStmt.cpp
@@ -433,7 +433,7 @@
   E->DeclRefExprBits.HasFoundDecl = Record[Idx++];
   E->DeclRefExprBits.HasTemplateKWAndArgsInfo = Record[Idx++];
   E->DeclRefExprBits.HadMultipleCandidates = Record[Idx++];
-  E->DeclRefExprBits.RefersToEnclosingLocal = Record[Idx++];
+  E->DeclRefExprBits.RefersToEnclosingVariableOrCapture = Record[Idx++];
   unsigned NumTemplateArgs = 0;
   if (E->hasTemplateKWAndArgsInfo())
     NumTemplateArgs = Record[Idx++];
@@ -2002,6 +2002,15 @@
   D->setCond(Fst, Snd);
   D->setInit(Reader.ReadSubExpr());
   D->setInc(Reader.ReadSubExpr());
+  if (isOpenMPWorksharingDirective(D->getDirectiveKind())) {
+    D->setIsLastIterVariable(Reader.ReadSubExpr());
+    D->setLowerBoundVariable(Reader.ReadSubExpr());
+    D->setUpperBoundVariable(Reader.ReadSubExpr());
+    D->setStrideVariable(Reader.ReadSubExpr());
+    D->setEnsureUpperBound(Reader.ReadSubExpr());
+    D->setNextLowerBound(Reader.ReadSubExpr());
+    D->setNextUpperBound(Reader.ReadSubExpr());
+  }
   SmallVector<Expr *, 4> Sub;
   unsigned CollapsedNum = D->getCollapsedNumber();
   Sub.reserve(CollapsedNum);
diff --git a/lib/Serialization/ASTWriter.cpp b/lib/Serialization/ASTWriter.cpp
index b9be775..3af2a40 100644
--- a/lib/Serialization/ASTWriter.cpp
+++ b/lib/Serialization/ASTWriter.cpp
@@ -941,10 +941,11 @@
 
   // Preprocessor Block.
   BLOCK(PREPROCESSOR_BLOCK);
+  RECORD(PP_MACRO_DIRECTIVE_HISTORY);
   RECORD(PP_MACRO_OBJECT_LIKE);
   RECORD(PP_MACRO_FUNCTION_LIKE);
   RECORD(PP_TOKEN);
-  
+
   // Decls and Types block.
   BLOCK(DECLTYPES_BLOCK);
   RECORD(TYPE_EXT_QUAL);
@@ -1058,38 +1059,65 @@
   Stream.ExitBlock();
 }
 
+/// \brief Prepares a path for being written to an AST file by converting it
+/// to an absolute path and removing nested './'s.
+///
+/// \return \c true if the path was changed.
+static bool cleanPathForOutput(FileManager &FileMgr,
+                               SmallVectorImpl<char> &Path) {
+  bool Changed = false;
+
+  if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
+    llvm::sys::fs::make_absolute(Path);
+    Changed = true;
+  }
+
+  return Changed | FileMgr.removeDotPaths(Path);
+}
+
 /// \brief Adjusts the given filename to only write out the portion of the
 /// filename that is not part of the system root directory.
 ///
 /// \param Filename the file name to adjust.
 ///
-/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
-/// the returned filename will be adjusted by this system root.
+/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
+/// the returned filename will be adjusted by this root directory.
 ///
 /// \returns either the original filename (if it needs no adjustment) or the
 /// adjusted filename (which points into the @p Filename parameter).
 static const char *
-adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
+adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
   assert(Filename && "No file name to adjust?");
 
-  if (isysroot.empty())
+  if (BaseDir.empty())
     return Filename;
 
   // Verify that the filename and the system root have the same prefix.
   unsigned Pos = 0;
-  for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
-    if (Filename[Pos] != isysroot[Pos])
+  for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
+    if (Filename[Pos] != BaseDir[Pos])
       return Filename; // Prefixes don't match.
 
   // We hit the end of the filename before we hit the end of the system root.
   if (!Filename[Pos])
     return Filename;
 
-  // If the file name has a '/' at the current position, skip over the '/'.
-  // We distinguish sysroot-based includes from absolute includes by the
-  // absence of '/' at the beginning of sysroot-based includes.
-  if (Filename[Pos] == '/')
+  // If there's not a path separator at the end of the base directory nor
+  // immediately after it, then this isn't within the base directory.
+  if (!llvm::sys::path::is_separator(Filename[Pos])) {
+    if (!llvm::sys::path::is_separator(BaseDir.back()))
+      return Filename;
+  } else {
+    // If the file name has a '/' at the current position, skip over the '/'.
+    // We distinguish relative paths from absolute paths by the
+    // absence of '/' at the beginning of relative paths.
+    //
+    // FIXME: This is wrong. We distinguish them by asking if the path is
+    // absolute, which isn't the same thing. And there might be multiple '/'s
+    // in a row. Use a better mechanism to indicate whether we have emitted an
+    // absolute or relative path.
     ++Pos;
+  }
 
   return Filename + Pos;
 }
@@ -1126,6 +1154,8 @@
   Record.push_back(VERSION_MINOR);
   Record.push_back(CLANG_VERSION_MAJOR);
   Record.push_back(CLANG_VERSION_MINOR);
+  assert((!WritingModule || isysroot.empty()) &&
+         "writing module as a relocatable PCH?");
   Record.push_back(!isysroot.empty());
   Record.push_back(ASTHasCompilerErrors);
   Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
@@ -1136,8 +1166,8 @@
   Record.push_back(getSignature());
   Stream.EmitRecord(SIGNATURE, Record);
 
-  // Module name
   if (WritingModule) {
+    // Module name
     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
@@ -1147,25 +1177,41 @@
     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
   }
 
+  if (WritingModule && WritingModule->Directory) {
+    // Module directory.
+    BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
+    Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
+    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
+    unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
+    RecordData Record;
+    Record.push_back(MODULE_DIRECTORY);
+
+    SmallString<128> BaseDir(WritingModule->Directory->getName());
+    cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
+    Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
+
+    // Write out all other paths relative to the base directory if possible.
+    BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
+  } else if (!isysroot.empty()) {
+    // Write out paths relative to the sysroot if possible.
+    BaseDirectory = isysroot;
+  }
+
   // Module map file
   if (WritingModule) {
     Record.clear();
-    auto addModMap = [&](const FileEntry *F) {
-      SmallString<128> ModuleMap(F->getName());
-      llvm::sys::fs::make_absolute(ModuleMap);
-      AddString(ModuleMap.str(), Record);
-    };
 
     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
 
     // Primary module map file.
-    addModMap(Map.getModuleMapFileForUniquing(WritingModule));
+    AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
 
     // Additional module map files.
-    if (auto *AdditionalModMaps = Map.getAdditionalModuleMapFiles(WritingModule)) {
+    if (auto *AdditionalModMaps =
+            Map.getAdditionalModuleMapFiles(WritingModule)) {
       Record.push_back(AdditionalModMaps->size());
       for (const FileEntry *F : *AdditionalModMaps)
-        addModMap(F);
+        AddPath(F->getName(), Record);
     } else {
       Record.push_back(0);
     }
@@ -1189,9 +1235,7 @@
       Record.push_back((*M)->File->getSize());
       Record.push_back((*M)->File->getModificationTime());
       Record.push_back((*M)->Signature);
-      const std::string &FileName = (*M)->FileName;
-      Record.push_back(FileName.size());
-      Record.append(FileName.begin(), FileName.end());
+      AddPath((*M)->FileName, Record);
     }
     Stream.EmitRecord(IMPORTS, Record);
   }
@@ -1299,6 +1343,8 @@
   Record.push_back(HSOpts.UseStandardSystemIncludes);
   Record.push_back(HSOpts.UseStandardCXXIncludes);
   Record.push_back(HSOpts.UseLibcxx);
+  // Write out the specific module cache path that contains the module files.
+  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
 
   // Preprocessor options.
@@ -1339,17 +1385,10 @@
     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
 
-    SmallString<128> MainFilePath(MainFile->getName());
-
-    llvm::sys::fs::make_absolute(MainFilePath);
-
-    const char *MainFileNameStr = MainFilePath.c_str();
-    MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
-                                                      isysroot);
     Record.clear();
     Record.push_back(ORIGINAL_FILE);
     Record.push_back(SM.getMainFileID().getOpaqueValue());
-    Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
+    EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
   }
 
   Record.clear();
@@ -1375,7 +1414,6 @@
 
   WriteInputFiles(Context.SourceMgr,
                   PP.getHeaderSearchInfo().getHeaderSearchOpts(),
-                  isysroot,
                   PP.getLangOpts().Modules);
   Stream.ExitBlock();
 }
@@ -1391,7 +1429,6 @@
 
 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
                                 HeaderSearchOptions &HSOpts,
-                                StringRef isysroot,
                                 bool Modules) {
   using namespace llvm;
   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
@@ -1434,7 +1471,7 @@
 
   unsigned UserFilesNum = 0;
   // Write out all of the input files.
-  std::vector<uint32_t> InputFileOffsets;
+  std::vector<uint64_t> InputFileOffsets;
   for (std::deque<InputFileEntry>::iterator
          I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
     const InputFileEntry &Entry = *I;
@@ -1462,23 +1499,8 @@
     // Whether this file was overridden.
     Record.push_back(Entry.BufferOverridden);
 
-    // Turn the file name into an absolute path, if it isn't already.
-    const char *Filename = Entry.File->getName();
-    SmallString<128> FilePath(Filename);
-    
-    // Ask the file manager to fixup the relative path for us. This will 
-    // honor the working directory.
-    SourceMgr.getFileManager().FixupRelativePath(FilePath);
-    
-    // FIXME: This call to make_absolute shouldn't be necessary, the
-    // call to FixupRelativePath should always return an absolute path.
-    llvm::sys::fs::make_absolute(FilePath);
-    Filename = FilePath.c_str();
-    
-    Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
-
-    Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
-  }  
+    EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
+  }
 
   Stream.ExitBlock();
 
@@ -1588,6 +1610,9 @@
       // The hash is based only on size/time of the file, so that the reader can
       // match even when symlinking or excess path elements ("foo/../", "../")
       // change the form of the name. However, complete path is still the key.
+      //
+      // FIXME: Using the mtime here will cause problems for explicit module
+      // imports.
       return llvm::hash_combine(key.FE->getSize(),
                                 key.FE->getModificationTime());
     }
@@ -1668,7 +1693,7 @@
 /// \brief Write the header search block for the list of files that 
 ///
 /// \param HS The header search structure to save.
-void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
+void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
   SmallVector<const FileEntry *, 16> FilesByUID;
   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
   
@@ -1692,17 +1717,16 @@
         (HFI.isModuleHeader && !HFI.isCompilingModuleHeader))
       continue;
 
-    // Turn the file name into an absolute path, if it isn't already.
+    // Massage the file path into an appropriate form.
     const char *Filename = File->getName();
-    Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
-      
-    // If we performed any translation on the file name at all, we need to
-    // save this string, since the generator will refer to it later.
-    if (Filename != File->getName()) {
-      Filename = strdup(Filename);
+    SmallString<128> FilenameTmp(Filename);
+    if (PreparePathForOutput(FilenameTmp)) {
+      // If we performed any translation on the file name at all, we need to
+      // save this string, since the generator will refer to it later.
+      Filename = strdup(FilenameTmp.c_str());
       SavedStrings.push_back(Filename);
     }
-    
+
     HeaderFileInfoTrait::key_type key = { File, Filename };
     Generator.insert(key, HFI, GeneratorTrait);
     ++NumHeaderSearchEntries;
@@ -1752,8 +1776,7 @@
 /// errors), we probably won't have to create file entries for any of
 /// the files in the AST.
 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
-                                        const Preprocessor &PP,
-                                        StringRef isysroot) {
+                                        const Preprocessor &PP) {
   RecordData Record;
 
   // Enter the source manager block.
@@ -1902,17 +1925,10 @@
     LineTableInfo &LineTable = SourceMgr.getLineTable();
 
     Record.clear();
-    // Emit the file names
+    // Emit the file names.
     Record.push_back(LineTable.getNumFilenames());
-    for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
-      // Emit the file name
-      const char *Filename = LineTable.getFilename(I);
-      Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
-      unsigned FilenameLen = Filename? strlen(Filename) : 0;
-      Record.push_back(FilenameLen);
-      if (FilenameLen)
-        Record.insert(Record.end(), Filename, Filename + FilenameLen);
-    }
+    for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I)
+      AddPath(LineTable.getFilename(I), Record);
 
     // Emit the line entries
     for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
@@ -2093,8 +2109,7 @@
       if (MD->isImported()) {
         auto Overrides = MD->getOverriddenModules();
         Record.push_back(Overrides.size());
-        for (auto Override : Overrides)
-          Record.push_back(Override);
+        Record.append(Overrides.begin(), Overrides.end());
       }
     }
     if (Record.empty())
@@ -2511,24 +2526,31 @@
 
     // Emit the headers.
     struct {
-      unsigned Kind;
+      unsigned RecordKind;
       unsigned Abbrev;
-      ArrayRef<const FileEntry*> Headers;
+      Module::HeaderKind HeaderKind;
     } HeaderLists[] = {
-      {SUBMODULE_HEADER, HeaderAbbrev, Mod->NormalHeaders},
-      {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Mod->TextualHeaders},
-      {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Mod->PrivateHeaders},
+      {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
+      {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
+      {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
       {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
-       Mod->PrivateTextualHeaders},
-      {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Mod->ExcludedHeaders},
-      {SUBMODULE_TOPHEADER, TopHeaderAbbrev,
-       Mod->getTopHeaders(PP->getFileManager())}
+        Module::HK_PrivateTextual},
+      {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
     };
     for (auto &HL : HeaderLists) {
       Record.clear();
-      Record.push_back(HL.Kind);
-      for (auto *H : HL.Headers)
-        Stream.EmitRecordWithBlob(HL.Abbrev, Record, H->getName());
+      Record.push_back(HL.RecordKind);
+      for (auto &H : Mod->Headers[HL.HeaderKind])
+        Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
+    }
+
+    // Emit the top headers.
+    {
+      auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
+      Record.clear();
+      Record.push_back(SUBMODULE_TOPHEADER);
+      for (auto *H : TopHeaders)
+        Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
     }
 
     // Emit the imports. 
@@ -2536,7 +2558,7 @@
       Record.clear();
       for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
         unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
-        assert(ImportedID && "Unknown submodule!");                                           
+        assert(ImportedID && "Unknown submodule!");
         Record.push_back(ImportedID);
       }
       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
@@ -2876,11 +2898,11 @@
     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
     for (const ObjCMethodList *Method = &Methods.Instance; Method;
          Method = Method->getNext())
-      if (Method->Method)
+      if (Method->getMethod())
         DataLen += 4;
     for (const ObjCMethodList *Method = &Methods.Factory; Method;
          Method = Method->getNext())
-      if (Method->Method)
+      if (Method->getMethod())
         DataLen += 4;
     LE.write<uint16_t>(DataLen);
     return std::make_pair(KeyLen, DataLen);
@@ -2910,32 +2932,39 @@
     unsigned NumInstanceMethods = 0;
     for (const ObjCMethodList *Method = &Methods.Instance; Method;
          Method = Method->getNext())
-      if (Method->Method)
+      if (Method->getMethod())
         ++NumInstanceMethods;
 
     unsigned NumFactoryMethods = 0;
     for (const ObjCMethodList *Method = &Methods.Factory; Method;
          Method = Method->getNext())
-      if (Method->Method)
+      if (Method->getMethod())
         ++NumFactoryMethods;
 
     unsigned InstanceBits = Methods.Instance.getBits();
     assert(InstanceBits < 4);
-    unsigned NumInstanceMethodsAndBits =
-        (NumInstanceMethods << 2) | InstanceBits;
+    unsigned InstanceHasMoreThanOneDeclBit =
+        Methods.Instance.hasMoreThanOneDecl();
+    unsigned FullInstanceBits = (NumInstanceMethods << 3) |
+                                (InstanceHasMoreThanOneDeclBit << 2) |
+                                InstanceBits;
     unsigned FactoryBits = Methods.Factory.getBits();
     assert(FactoryBits < 4);
-    unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits;
-    LE.write<uint16_t>(NumInstanceMethodsAndBits);
-    LE.write<uint16_t>(NumFactoryMethodsAndBits);
+    unsigned FactoryHasMoreThanOneDeclBit =
+        Methods.Factory.hasMoreThanOneDecl();
+    unsigned FullFactoryBits = (NumFactoryMethods << 3) |
+                               (FactoryHasMoreThanOneDeclBit << 2) |
+                               FactoryBits;
+    LE.write<uint16_t>(FullInstanceBits);
+    LE.write<uint16_t>(FullFactoryBits);
     for (const ObjCMethodList *Method = &Methods.Instance; Method;
          Method = Method->getNext())
-      if (Method->Method)
-        LE.write<uint32_t>(Writer.getDeclID(Method->Method));
+      if (Method->getMethod())
+        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
     for (const ObjCMethodList *Method = &Methods.Factory; Method;
          Method = Method->getNext())
-      if (Method->Method)
-        LE.write<uint32_t>(Writer.getDeclID(Method->Method));
+      if (Method->getMethod())
+        LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
 
     assert(Out.tell() - Start == DataLen && "Data length is wrong");
   }
@@ -2981,19 +3010,19 @@
       if (Chain && I->second < FirstSelectorID) {
         // Selector already exists. Did it change?
         bool changed = false;
-        for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
-             M = M->getNext()) {
-          if (!M->Method->isFromASTFile())
+        for (ObjCMethodList *M = &Data.Instance;
+             !changed && M && M->getMethod(); M = M->getNext()) {
+          if (!M->getMethod()->isFromASTFile())
             changed = true;
         }
-        for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
+        for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
              M = M->getNext()) {
-          if (!M->Method->isFromASTFile())
+          if (!M->getMethod()->isFromASTFile())
             changed = true;
         }
         if (!changed)
           continue;
-      } else if (Data.Instance.Method || Data.Factory.Method) {
+      } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
         // A new method pool entry.
         ++NumTableEntries;
       }
@@ -3071,6 +3100,37 @@
 // Identifier Table Serialization
 //===----------------------------------------------------------------------===//
 
+/// Determine the declaration that should be put into the name lookup table to
+/// represent the given declaration in this module. This is usually D itself,
+/// but if D was imported and merged into a local declaration, we want the most
+/// recent local declaration instead. The chosen declaration will be the most
+/// recent declaration in any module that imports this one.
+static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
+                                        NamedDecl *D) {
+  if (!LangOpts.Modules || !D->isFromASTFile())
+    return D;
+
+  if (Decl *Redecl = D->getPreviousDecl()) {
+    // For Redeclarable decls, a prior declaration might be local.
+    for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
+      if (!Redecl->isFromASTFile())
+        return cast<NamedDecl>(Redecl);
+      // If we come up a decl from a (chained-)PCH stop since we won't find a
+      // local one.
+      if (D->getOwningModuleID() == 0)
+        break;
+    }
+  } else if (Decl *First = D->getCanonicalDecl()) {
+    // For Mergeable decls, the first decl might be local.
+    if (!First->isFromASTFile())
+      return cast<NamedDecl>(First);
+  }
+
+  // All declarations are imported. Our most recent declaration will also be
+  // the most recent one in anyone who imports us.
+  return D;
+}
+
 namespace {
 class ASTIdentifierTableTrait {
   ASTWriter &Writer;
@@ -3374,36 +3434,15 @@
     // Emit the declaration IDs in reverse order, because the
     // IdentifierResolver provides the declarations as they would be
     // visible (e.g., the function "stat" would come before the struct
-    // "stat"), but the ASTReader adds declarations to the end of the list 
-    // (so we need to see the struct "status" before the function "status").
+    // "stat"), but the ASTReader adds declarations to the end of the list
+    // (so we need to see the struct "stat" before the function "stat").
     // Only emit declarations that aren't from a chained PCH, though.
-    SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
-                                  IdResolver.end());
-    for (SmallVectorImpl<Decl *>::reverse_iterator D = Decls.rbegin(),
-                                                DEnd = Decls.rend();
+    SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), IdResolver.end());
+    for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
+                                                        DEnd = Decls.rend();
          D != DEnd; ++D)
-      LE.write<uint32_t>(Writer.getDeclID(getMostRecentLocalDecl(*D)));
-  }
-
-  /// \brief Returns the most recent local decl or the given decl if there are
-  /// no local ones. The given decl is assumed to be the most recent one.
-  Decl *getMostRecentLocalDecl(Decl *Orig) {
-    // The only way a "from AST file" decl would be more recent from a local one
-    // is if it came from a module.
-    if (!PP.getLangOpts().Modules)
-      return Orig;
-
-    // Look for a local in the decl chain.
-    for (Decl *D = Orig; D; D = D->getPreviousDecl()) {
-      if (!D->isFromASTFile())
-        return D;
-      // If we come up a decl from a (chained-)PCH stop since we won't find a
-      // local one.
-      if (D->getOwningModuleID() == 0)
-        break;
-    }
-
-    return Orig;
+      LE.write<uint32_t>(
+          Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
   }
 };
 } // end anonymous namespace
@@ -3498,31 +3537,6 @@
 // DeclContext's Name Lookup Table Serialization
 //===----------------------------------------------------------------------===//
 
-/// Determine the declaration that should be put into the name lookup table to
-/// represent the given declaration in this module. This is usually D itself,
-/// but if D was imported and merged into a local declaration, we want the most
-/// recent local declaration instead. The chosen declaration will be the most
-/// recent declaration in any module that imports this one.
-static NamedDecl *getDeclForLocalLookup(NamedDecl *D) {
-  if (!D->isFromASTFile())
-    return D;
-
-  if (Decl *Redecl = D->getPreviousDecl()) {
-    // For Redeclarable decls, a prior declaration might be local.
-    for (; Redecl; Redecl = Redecl->getPreviousDecl())
-      if (!Redecl->isFromASTFile())
-        return cast<NamedDecl>(Redecl);
-  } else if (Decl *First = D->getCanonicalDecl()) {
-    // For Mergeable decls, the first decl might be local.
-    if (!First->isFromASTFile())
-      return cast<NamedDecl>(First);
-  }
-
-  // All declarations are imported. Our most recent declaration will also be
-  // the most recent one in anyone who imports us.
-  return D;
-}
-
 namespace {
 // Trait used for the on-disk hash table used in the method pool.
 class ASTDeclContextNameLookupTrait {
@@ -3640,7 +3654,8 @@
     LE.write<uint16_t>(Lookup.size());
     for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
          I != E; ++I)
-      LE.write<uint32_t>(Writer.GetDeclRef(getDeclForLocalLookup(*I)));
+      LE.write<uint32_t>(
+          Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), *I)));
 
     assert(Out.tell() - Start == DataLen && "Data length is wrong");
   }
@@ -3684,9 +3699,9 @@
     // Ensure we emit all the visible declarations.
     visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
                             [&](DeclarationName Name,
-                                DeclContext::lookup_const_result Result) {
+                                DeclContext::lookup_result Result) {
       for (auto *Decl : Result)
-        GetDeclRef(getDeclForLocalLookup(Decl));
+        GetDeclRef(getDeclForLocalLookup(getLangOpts(), Decl));
     });
   }
 }
@@ -3741,16 +3756,14 @@
   // Add the constructors.
   if (!ConstructorDecls.empty()) {
     Generator.insert(ConstructorName,
-                     DeclContext::lookup_result(ConstructorDecls.begin(),
-                                                ConstructorDecls.end()),
+                     DeclContext::lookup_result(ConstructorDecls),
                      Trait);
   }
 
   // Add the conversion functions.
   if (!ConversionDecls.empty()) {
     Generator.insert(ConversionName,
-                     DeclContext::lookup_result(ConversionDecls.begin(),
-                                                ConversionDecls.end()),
+                     DeclContext::lookup_result(ConversionDecls),
                      Trait);
   }
 
@@ -4070,6 +4083,37 @@
   Record.insert(Record.end(), Str.begin(), Str.end());
 }
 
+bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
+  assert(Context && "should have context when outputting path");
+
+  bool Changed =
+      cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
+
+  // Remove a prefix to make the path relative, if relevant.
+  const char *PathBegin = Path.data();
+  const char *PathPtr =
+      adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
+  if (PathPtr != PathBegin) {
+    Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
+    Changed = true;
+  }
+
+  return Changed;
+}
+
+void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
+  SmallString<128> FilePath(Path);
+  PreparePathForOutput(FilePath);
+  AddString(FilePath, Record);
+}
+
+void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
+                                   StringRef Path) {
+  SmallString<128> FilePath(Path);
+  PreparePathForOutput(FilePath);
+  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
+}
+
 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
                                 RecordDataImpl &Record) {
   Record.push_back(Version.getMajor());
@@ -4131,6 +4175,11 @@
   llvm::DeleteContainerSeconds(FileDeclIDs);
 }
 
+const LangOptions &ASTWriter::getLangOpts() const {
+  assert(WritingAST && "can't determine lang opts when not writing AST");
+  return Context->getLangOpts();
+}
+
 void ASTWriter::WriteAST(Sema &SemaRef,
                          const std::string &OutputFile,
                          Module *WritingModule, StringRef isysroot,
@@ -4154,6 +4203,7 @@
   Context = nullptr;
   PP = nullptr;
   this->WritingModule = nullptr;
+  this->BaseDirectory.clear();
 
   WritingAST = false;
 }
@@ -4216,23 +4266,6 @@
       getIdentifierRef(&Table.get(BuiltinNames[I]));
   }
 
-  // If there are any out-of-date identifiers, bring them up to date.
-  if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
-    // Find out-of-date identifiers.
-    SmallVector<IdentifierInfo *, 4> OutOfDate;
-    for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
-                                IDEnd = PP.getIdentifierTable().end();
-         ID != IDEnd; ++ID) {
-      if (ID->second->isOutOfDate())
-        OutOfDate.push_back(ID->second);
-    }
-
-    // Update the out-of-date identifiers.
-    for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
-      ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
-    }
-  }
-
   // If we saw any DeclContext updates before we started writing the AST file,
   // make sure all visible decls in those DeclContexts are written out.
   if (!UpdatedDeclContexts.empty()) {
@@ -4544,11 +4577,11 @@
     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
   WriteCXXBaseSpecifiersOffsets();
   WriteFileDeclIDsMap();
-  WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
+  WriteSourceManagerBlock(Context.getSourceManager(), PP);
 
   WriteComments();
   WritePreprocessor(PP, isModule);
-  WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
+  WriteHeaderSearch(PP.getHeaderSearchInfo());
   WriteSelectors(SemaRef);
   WriteReferencedSelectorsPool(SemaRef);
   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
@@ -5176,13 +5209,10 @@
   // already done so.
   auto It = AnonymousDeclarationNumbers.find(D);
   if (It == AnonymousDeclarationNumbers.end()) {
-    unsigned Index = 0;
-    for (Decl *LexicalD : D->getLexicalDeclContext()->decls()) {
-      auto *ND = dyn_cast<NamedDecl>(LexicalD);
-      if (!ND || !needsAnonymousDeclarationNumber(ND))
-        continue;
-      AnonymousDeclarationNumbers[ND] = Index++;
-    }
+    auto *DC = D->getLexicalDeclContext();
+    numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
+      AnonymousDeclarationNumbers[ND] = Number;
+    });
 
     It = AnonymousDeclarationNumbers.find(D);
     assert(It != AnonymousDeclarationNumbers.end() &&
diff --git a/lib/Serialization/ASTWriterDecl.cpp b/lib/Serialization/ASTWriterDecl.cpp
index 4899968..7f2e805 100644
--- a/lib/Serialization/ASTWriterDecl.cpp
+++ b/lib/Serialization/ASTWriterDecl.cpp
@@ -203,8 +203,9 @@
 void ASTDeclWriter::VisitNamedDecl(NamedDecl *D) {
   VisitDecl(D);
   Writer.AddDeclarationName(D->getDeclName(), Record);
-  if (needsAnonymousDeclarationNumber(D))
-    Record.push_back(Writer.getAnonymousDeclarationNumber(D));
+  Record.push_back(needsAnonymousDeclarationNumber(D)
+                       ? Writer.getAnonymousDeclarationNumber(D)
+                       : 0);
 }
 
 void ASTDeclWriter::VisitTypeDecl(TypeDecl *D) {
@@ -370,21 +371,21 @@
   // FunctionDecl's body is handled last at ASTWriterDecl::Visit,
   // after everything else is written.
   
-  Record.push_back(D->getStorageClass()); // FIXME: stable encoding
+  Record.push_back((int)D->SClass); // FIXME: stable encoding
   Record.push_back(D->IsInline);
-  Record.push_back(D->isInlineSpecified());
-  Record.push_back(D->isVirtualAsWritten());
-  Record.push_back(D->isPure());
-  Record.push_back(D->hasInheritedPrototype());
-  Record.push_back(D->hasWrittenPrototype());
-  Record.push_back(D->isDeletedAsWritten());
-  Record.push_back(D->isTrivial());
-  Record.push_back(D->isDefaulted());
-  Record.push_back(D->isExplicitlyDefaulted());
-  Record.push_back(D->hasImplicitReturnZero());
-  Record.push_back(D->isConstexpr());
+  Record.push_back(D->IsInlineSpecified);
+  Record.push_back(D->IsVirtualAsWritten);
+  Record.push_back(D->IsPure);
+  Record.push_back(D->HasInheritedPrototype);
+  Record.push_back(D->HasWrittenPrototype);
+  Record.push_back(D->IsDeleted);
+  Record.push_back(D->IsTrivial);
+  Record.push_back(D->IsDefaulted);
+  Record.push_back(D->IsExplicitlyDefaulted);
+  Record.push_back(D->HasImplicitReturnZero);
+  Record.push_back(D->IsConstexpr);
   Record.push_back(D->HasSkippedBody);
-  Record.push_back(D->isLateTemplateParsed());
+  Record.push_back(D->IsLateTemplateParsed);
   Record.push_back(D->getLinkageInternal());
   Writer.AddSourceLocation(D->getLocEnd(), Record);
 
@@ -1448,25 +1449,42 @@
 template <typename T>
 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
   T *First = D->getFirstDecl();
-  if (First->getMostRecentDecl() != First) {
+  T *MostRecent = First->getMostRecentDecl();
+  if (MostRecent != First) {
     assert(isRedeclarableDeclKind(static_cast<T *>(D)->getKind()) &&
            "Not considered redeclarable?");
-    
+
+    auto *Previous = D->getPreviousDecl();
+    auto *FirstToEmit = First;
+    if (Context.getLangOpts().Modules && Writer.Chain && !Previous) {
+      // In a modules build, we can have imported declarations after a local
+      // canonical declaration. If we do, we want to treat the first imported
+      // declaration as our canonical declaration on reload, in order to
+      // rebuild the redecl chain in the right order.
+      for (auto *Redecl = MostRecent; Redecl;
+           Redecl = Redecl->getPreviousDecl())
+        if (Redecl->isFromASTFile())
+          FirstToEmit = Redecl;
+    }
+
     // There is more than one declaration of this entity, so we will need to
     // write a redeclaration chain.
-    Writer.AddDeclRef(First, Record);
+    Writer.AddDeclRef(FirstToEmit, Record);
+    Record.push_back(FirstToEmit != First);
     Writer.Redeclarations.insert(First);
 
     // Make sure that we serialize both the previous and the most-recent 
     // declarations, which (transitively) ensures that all declarations in the
     // chain get serialized.
-    (void)Writer.GetDeclRef(D->getPreviousDecl());
-    (void)Writer.GetDeclRef(First->getMostRecentDecl());
+    //
+    // FIXME: This is not correct; when we reach an imported declaration we
+    // won't emit its previous declaration.
+    (void)Writer.GetDeclRef(Previous);
+    (void)Writer.GetDeclRef(MostRecent);
   } else {
     // We use the sentinel value 0 to indicate an only declaration.
     Record.push_back(0);
   }
-  
 }
 
 void ASTDeclWriter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
@@ -1504,6 +1522,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // ValueDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
   // DeclaratorDecl
@@ -1536,6 +1555,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // ValueDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
   // DeclaratorDecl
@@ -1573,6 +1593,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // TypeDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
@@ -1620,6 +1641,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // TypeDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
@@ -1662,6 +1684,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // ValueDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
   // DeclaratorDecl
@@ -1715,6 +1738,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // TypeDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
@@ -1743,6 +1767,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
+  Abv->Add(BitCodeAbbrevOp(0));                       // AnonDeclNumber
   // ValueDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
   // DeclaratorDecl
@@ -1788,6 +1813,7 @@
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(DeclarationName::Identifier)); // NameKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Identifier
+  Abv->Add(BitCodeAbbrevOp(0));                         // AnonDeclNumber
   // ValueDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
   // DeclaratorDecl
@@ -1802,7 +1828,7 @@
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Pure
   Abv->Add(BitCodeAbbrevOp(0));                         // HasInheritedProto
   Abv->Add(BitCodeAbbrevOp(1));                         // HasWrittenProto
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // DeletedAsWritten
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Deleted
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Trivial
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Defaulted
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ExplicitlyDefaulted
@@ -1842,7 +1868,8 @@
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //GetDeclFound
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ExplicitTemplateArgs
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //HadMultipleCandidates
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //RefersToEnclosingLocal
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
+                           1)); // RefersToEnclosingVariableOrCapture
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclRef
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
   DeclRefExprAbbrev = Stream.EmitAbbrev(Abv);
@@ -1947,9 +1974,10 @@
 
   // Determine the ID for this declaration.
   serialization::DeclID ID;
-  if (D->isFromASTFile())
+  if (D->isFromASTFile()) {
+    assert(isRewritten(D) && "should not be emitting imported decl");
     ID = getDeclID(D);
-  else {
+  } else {
     serialization::DeclID &IDR = DeclIDs[D];
     if (IDR == 0)
       IDR = NextDeclID++;
diff --git a/lib/Serialization/ASTWriterStmt.cpp b/lib/Serialization/ASTWriterStmt.cpp
index 38996dd..e980ce7 100644
--- a/lib/Serialization/ASTWriterStmt.cpp
+++ b/lib/Serialization/ASTWriterStmt.cpp
@@ -344,7 +344,7 @@
   Record.push_back(E->getDecl() != E->getFoundDecl());
   Record.push_back(E->hasTemplateKWAndArgsInfo());
   Record.push_back(E->hadMultipleCandidates());
-  Record.push_back(E->refersToEnclosingLocal());
+  Record.push_back(E->refersToEnclosingVariableOrCapture());
 
   if (E->hasTemplateKWAndArgsInfo()) {
     unsigned NumTemplateArgs = E->getNumTemplateArgs();
@@ -1882,6 +1882,15 @@
   Writer.AddStmt(D->getCond(/* SeparateIter */ true));
   Writer.AddStmt(D->getInit());
   Writer.AddStmt(D->getInc());
+  if (isOpenMPWorksharingDirective(D->getDirectiveKind())) {
+    Writer.AddStmt(D->getIsLastIterVariable());
+    Writer.AddStmt(D->getLowerBoundVariable());
+    Writer.AddStmt(D->getUpperBoundVariable());
+    Writer.AddStmt(D->getStrideVariable());
+    Writer.AddStmt(D->getEnsureUpperBound());
+    Writer.AddStmt(D->getNextLowerBound());
+    Writer.AddStmt(D->getNextUpperBound());
+  }
   for (auto I : D->counters()) {
     Writer.AddStmt(I);
   }
diff --git a/lib/Serialization/ModuleManager.cpp b/lib/Serialization/ModuleManager.cpp
index b5ee414..ac98ca0 100644
--- a/lib/Serialization/ModuleManager.cpp
+++ b/lib/Serialization/ModuleManager.cpp
@@ -67,6 +67,13 @@
   // Look for the file entry. This only fails if the expected size or
   // modification time differ.
   const FileEntry *Entry;
+  if (Type == MK_ExplicitModule) {
+    // If we're not expecting to pull this file out of the module cache, it
+    // might have a different mtime due to being moved across filesystems in
+    // a distributed build. The size must still match, though. (As must the
+    // contents, but we can't check that.)
+    ExpectedModTime = 0;
+  }
   if (lookupModuleFile(FileName, ExpectedSize, ExpectedModTime, Entry)) {
     ErrorStr = "module file out of date";
     return OutOfDate;
diff --git a/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp b/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
index 13ea4d3..0d73160 100644
--- a/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
+++ b/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
@@ -292,7 +292,11 @@
   // If it is a call to an allocator function, it could be a double allocation.
   idx = getTrackedFunctionIndex(funName, true);
   if (idx != InvalidIdx) {
-    const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
+    unsigned paramIdx = FunctionsToTrack[idx].Param;
+    if (CE->getNumArgs() <= paramIdx)
+      return;
+
+    const Expr *ArgExpr = CE->getArg(paramIdx);
     if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
       if (const AllocationState *AS = State->get<AllocatedData>(V)) {
         if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
@@ -325,8 +329,12 @@
   if (idx == InvalidIdx)
     return;
 
+  unsigned paramIdx = FunctionsToTrack[idx].Param;
+  if (CE->getNumArgs() <= paramIdx)
+    return;
+
   // Check the argument to the deallocator.
-  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
+  const Expr *ArgExpr = CE->getArg(paramIdx);
   SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
 
   // Undef is reported by another checker.
@@ -499,9 +507,11 @@
   while (N) {
     if (!N->getState()->get<AllocatedData>(Sym))
       break;
-    // Allocation node, is the last node in the current context in which the
-    // symbol was tracked.
-    if (N->getLocationContext() == LeakContext)
+    // Allocation node, is the last node in the current or parent context in
+    // which the symbol was tracked.
+    const LocationContext *NContext = N->getLocationContext();
+    if (NContext == LeakContext ||
+        NContext->isParentOf(LeakContext))
       AllocNode = N;
     N = N->pred_empty() ? nullptr : *(N->pred_begin());
   }
diff --git a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index aee5a43..0930808 100644
--- a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -43,7 +43,8 @@
   AF_Malloc,
   AF_CXXNew,
   AF_CXXNewArray,
-  AF_IfNameIndex
+  AF_IfNameIndex,
+  AF_Alloca
 };
 
 class RefState {
@@ -160,10 +161,11 @@
 {
 public:
   MallocChecker()
-      : II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr),
-        II_calloc(nullptr), II_valloc(nullptr), II_reallocf(nullptr),
-        II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr),
-        II_if_nameindex(nullptr), II_if_freenameindex(nullptr) {}
+      : II_alloca(nullptr), II_alloca_builtin(nullptr), II_malloc(nullptr),
+        II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
+        II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
+        II_strdup(nullptr), II_kmalloc(nullptr), II_if_nameindex(nullptr),
+        II_if_freenameindex(nullptr) {}
 
   /// In pessimistic mode, the checker assumes that it does not know which
   /// functions might free the memory.
@@ -184,6 +186,7 @@
 
   DefaultBool ChecksEnabled[CK_NumCheckKinds];
   CheckName CheckNames[CK_NumCheckKinds];
+  typedef llvm::SmallVector<CheckKind, CK_NumCheckKinds> CKVecTy;
 
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
@@ -216,11 +219,13 @@
   mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
   mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
   mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
+  mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
   mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
   mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
-  mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
-                         *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
-                         *II_kmalloc, *II_if_nameindex, *II_if_freenameindex;
+  mutable IdentifierInfo *II_alloca, *II_alloca_builtin, *II_malloc, *II_free,
+                         *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
+                         *II_strndup, *II_strdup, *II_kmalloc, *II_if_nameindex,
+                         *II_if_freenameindex;
   mutable Optional<uint64_t> KernelZeroFlagVal;
 
   void initIdentifierInfo(ASTContext &C) const;
@@ -254,20 +259,16 @@
   ///@}
   ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
                                        const CallExpr *CE,
-                                       const OwnershipAttr* Att) const;
+                                       const OwnershipAttr* Att,
+                                       ProgramStateRef State) const;
   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
-                                     const Expr *SizeEx, SVal Init,
-                                     ProgramStateRef State,
-                                     AllocationFamily Family = AF_Malloc) {
-    return MallocMemAux(C, CE,
-                        State->getSVal(SizeEx, C.getLocationContext()),
-                        Init, State, Family);
-  }
-
+                                      const Expr *SizeEx, SVal Init,
+                                      ProgramStateRef State,
+                                      AllocationFamily Family = AF_Malloc);
   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
-                                     SVal SizeEx, SVal Init,
-                                     ProgramStateRef State,
-                                     AllocationFamily Family = AF_Malloc);
+                                      SVal SizeEx, SVal Init,
+                                      ProgramStateRef State,
+                                      AllocationFamily Family = AF_Malloc);
 
   // Check if this malloc() for special flags. At present that means M_ZERO or
   // __GFP_ZERO (in which case, treat it like calloc).
@@ -281,7 +282,8 @@
                        AllocationFamily Family = AF_Malloc);
 
   ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
-                              const OwnershipAttr* Att) const;
+                              const OwnershipAttr* Att,
+                              ProgramStateRef State) const;
   ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
                              ProgramStateRef state, unsigned Num,
                              bool Hold,
@@ -295,8 +297,10 @@
                              bool ReturnsNullOnFailure = false) const;
 
   ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
-                             bool FreesMemOnFailure) const;
-  static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
+                             bool FreesMemOnFailure, 
+                             ProgramStateRef State) const;
+  static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
+                                   ProgramStateRef State);
   
   ///\brief Check if the memory associated with this symbol was released.
   bool isReleased(SymbolRef Sym, CheckerContext &C) const;
@@ -328,17 +332,23 @@
 
   ///@{
   /// Tells if a given family/call/symbol is tracked by the current checker.
-  /// Sets CheckKind to the kind of the checker responsible for this
-  /// family/call/symbol.
-  Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
-  Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
+  /// Looks through incoming CheckKind(s) and returns the kind of the checker 
+  /// responsible for this family/call/symbol.
+  Optional<CheckKind> getCheckIfTracked(CheckKind CK,
+                                        AllocationFamily Family) const;
+  Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, 
+                                        AllocationFamily Family) const;
+  Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
                                         const Stmt *AllocDeallocStmt) const;
-  Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
+  Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
+                                        SymbolRef Sym) const;
   ///@}
   static bool SummarizeValue(raw_ostream &os, SVal V);
   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
   void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range, 
                      const Expr *DeallocExpr) const;
+  void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
+                        SourceRange Range) const;
   void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
                                const Expr *DeallocExpr, const RefState *RS,
                                SymbolRef Sym, bool OwnershipTransferred) const;
@@ -497,6 +507,8 @@
 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
   if (II_malloc)
     return;
+  II_alloca = &Ctx.Idents.get("alloca");
+  II_alloca_builtin = &Ctx.Idents.get("__builtin_alloca");
   II_malloc = &Ctx.Idents.get("malloc");
   II_free = &Ctx.Idents.get("free");
   II_realloc = &Ctx.Idents.get("realloc");
@@ -517,6 +529,9 @@
   if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
     return true;
 
+  if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
+    return true;
+
   if (isStandardNewDelete(FD, C))
     return true;
 
@@ -560,6 +575,11 @@
       if (FunI == II_if_nameindex)
         return true;
     }
+
+    if (Family == AF_Alloca && CheckAlloc) {
+      if (FunI == II_alloca || FunI == II_alloca_builtin)
+        return true;
+    }
   }
 
   if (Family != AF_Malloc)
@@ -732,19 +752,21 @@
         return;
       State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
     } else if (FunI == II_realloc) {
-      State = ReallocMem(C, CE, false);
+      State = ReallocMem(C, CE, false, State);
     } else if (FunI == II_reallocf) {
-      State = ReallocMem(C, CE, true);
+      State = ReallocMem(C, CE, true, State);
     } else if (FunI == II_calloc) {
-      State = CallocMem(C, CE);
+      State = CallocMem(C, CE, State);
     } else if (FunI == II_free) {
       State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
     } else if (FunI == II_strdup) {
       State = MallocUpdateRefState(C, CE, State);
     } else if (FunI == II_strndup) {
       State = MallocUpdateRefState(C, CE, State);
-    }
-    else if (isStandardNewDelete(FD, C.getASTContext())) {
+    } else if (FunI == II_alloca || FunI == II_alloca_builtin) {
+      State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
+                           AF_Alloca);
+    } else if (isStandardNewDelete(FD, C.getASTContext())) {
       // Process direct calls to operator new/new[]/delete/delete[] functions
       // as distinct from new/new[]/delete/delete[] expressions that are 
       // processed by the checkPostStmt callbacks for CXXNewExpr and 
@@ -778,11 +800,11 @@
       for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
         switch (I->getOwnKind()) {
         case OwnershipAttr::Returns:
-          State = MallocMemReturnsAttr(C, CE, I);
+          State = MallocMemReturnsAttr(C, CE, I, State);
           break;
         case OwnershipAttr::Takes:
         case OwnershipAttr::Holds:
-          State = FreeMemAttr(C, CE, I);
+          State = FreeMemAttr(C, CE, I, State);
           break;
         }
       }
@@ -919,15 +941,31 @@
 
 ProgramStateRef
 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
-                                    const OwnershipAttr *Att) const {
+                                    const OwnershipAttr *Att, 
+                                    ProgramStateRef State) const {
+  if (!State)
+    return nullptr;
+
   if (Att->getModule() != II_malloc)
     return nullptr;
 
   OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
   if (I != E) {
-    return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
+    return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
   }
-  return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
+  return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
+}
+
+ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
+                                            const CallExpr *CE,
+                                            const Expr *SizeEx, SVal Init,
+                                            ProgramStateRef State,
+                                            AllocationFamily Family) {
+  if (!State)
+    return nullptr;
+
+  return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
+                      Init, State, Family);
 }
 
 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
@@ -935,6 +973,8 @@
                                            SVal Size, SVal Init,
                                            ProgramStateRef State,
                                            AllocationFamily Family) {
+  if (!State)
+    return nullptr;
 
   // We expect the malloc functions to return a pointer.
   if (!Loc::isLocType(CE->getType()))
@@ -976,6 +1016,9 @@
                                                     const Expr *E,
                                                     ProgramStateRef State,
                                                     AllocationFamily Family) {
+  if (!State)
+    return nullptr;
+
   // Get the return value.
   SVal retVal = State->getSVal(E, C.getLocationContext());
 
@@ -992,11 +1035,14 @@
 
 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
                                            const CallExpr *CE,
-                                           const OwnershipAttr *Att) const {
+                                           const OwnershipAttr *Att, 
+                                           ProgramStateRef State) const {
+  if (!State)
+    return nullptr;
+
   if (Att->getModule() != II_malloc)
     return nullptr;
 
-  ProgramStateRef State = C.getState();
   bool ReleasedAllocated = false;
 
   for (const auto &Arg : Att->args()) {
@@ -1011,15 +1057,18 @@
 
 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
                                           const CallExpr *CE,
-                                          ProgramStateRef state,
+                                          ProgramStateRef State,
                                           unsigned Num,
                                           bool Hold,
                                           bool &ReleasedAllocated,
                                           bool ReturnsNullOnFailure) const {
+  if (!State)
+    return nullptr;
+
   if (CE->getNumArgs() < (Num + 1))
     return nullptr;
 
-  return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
+  return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
                     ReleasedAllocated, ReturnsNullOnFailure);
 }
 
@@ -1065,6 +1114,9 @@
     if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
       return AF_IfNameIndex;
 
+    if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
+      return AF_Alloca;
+
     return AF_None;
   }
 
@@ -1129,6 +1181,7 @@
     case AF_CXXNew: os << "'new'"; return;
     case AF_CXXNewArray: os << "'new[]'"; return;
     case AF_IfNameIndex: os << "'if_nameindex()'"; return;
+    case AF_Alloca:
     case AF_None: llvm_unreachable("not a deallocation expression");
   }
 }
@@ -1140,7 +1193,8 @@
     case AF_CXXNew: os << "'delete'"; return;
     case AF_CXXNewArray: os << "'delete[]'"; return;
     case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
-    case AF_None: llvm_unreachable("suspicious AF_None argument");
+    case AF_Alloca:
+    case AF_None: llvm_unreachable("suspicious argument");
   }
 }
 
@@ -1152,6 +1206,9 @@
                                           bool &ReleasedAllocated,
                                           bool ReturnsNullOnFailure) const {
 
+  if (!State)
+    return nullptr;
+
   SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
   if (!ArgVal.getAs<DefinedOrUnknownSVal>())
     return nullptr;
@@ -1191,8 +1248,7 @@
   
   const MemSpaceRegion *MS = R->getMemorySpace();
   
-  // Parameters, locals, statics, globals, and memory returned by alloca() 
-  // shouldn't be freed.
+  // Parameters, locals, statics and globals shouldn't be freed.
   if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
     // FIXME: at the time this code was written, malloc() regions were
     // represented by conjured symbols, which are all in UnknownSpaceRegion.
@@ -1218,6 +1274,12 @@
 
   if (RsBase) {
 
+    // Memory returned by alloca() shouldn't be freed.
+    if (RsBase->getAllocationFamily() == AF_Alloca) {
+      ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
+      return nullptr;
+    }
+
     // Check for double free first.
     if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
         !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
@@ -1281,21 +1343,33 @@
 }
 
 Optional<MallocChecker::CheckKind>
-MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
+MallocChecker::getCheckIfTracked(MallocChecker::CheckKind CK,
+                                 AllocationFamily Family) const {
+
+  if (CK == CK_NumCheckKinds || !ChecksEnabled[CK])
+    return Optional<MallocChecker::CheckKind>();
+
+  // C/C++ checkers.
+  if (CK == CK_MismatchedDeallocatorChecker)
+    return CK;
+
   switch (Family) {
   case AF_Malloc:
-  case AF_IfNameIndex: {
-    if (ChecksEnabled[CK_MallocOptimistic]) {
-      return CK_MallocOptimistic;
-    } else if (ChecksEnabled[CK_MallocPessimistic]) {
-      return CK_MallocPessimistic;
+  case AF_IfNameIndex:
+  case AF_Alloca: {
+    // C checkers.
+    if (CK == CK_MallocOptimistic ||
+        CK == CK_MallocPessimistic) {
+      return CK;
     }
     return Optional<MallocChecker::CheckKind>();
   }
   case AF_CXXNew:
   case AF_CXXNewArray: {
-    if (ChecksEnabled[CK_NewDeleteChecker]) {
-      return CK_NewDeleteChecker;
+    // C++ checkers.
+    if (CK == CK_NewDeleteChecker ||
+        CK == CK_NewDeleteLeaksChecker) {
+      return CK;
     }
     return Optional<MallocChecker::CheckKind>();
   }
@@ -1306,18 +1380,45 @@
   llvm_unreachable("unhandled family");
 }
 
-Optional<MallocChecker::CheckKind>
-MallocChecker::getCheckIfTracked(CheckerContext &C,
-                                 const Stmt *AllocDeallocStmt) const {
-  return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
+static MallocChecker::CKVecTy MakeVecFromCK(MallocChecker::CheckKind CK1,
+               MallocChecker::CheckKind CK2 = MallocChecker::CK_NumCheckKinds,
+               MallocChecker::CheckKind CK3 = MallocChecker::CK_NumCheckKinds,
+               MallocChecker::CheckKind CK4 = MallocChecker::CK_NumCheckKinds) {
+  MallocChecker::CKVecTy CKVec;
+  CKVec.push_back(CK1);
+  if (CK2 != MallocChecker::CK_NumCheckKinds) {
+    CKVec.push_back(CK2);
+    if (CK3 != MallocChecker::CK_NumCheckKinds) {
+      CKVec.push_back(CK3);
+      if (CK4 != MallocChecker::CK_NumCheckKinds)
+        CKVec.push_back(CK4);
+    }
+  }
+  return CKVec;
 }
 
 Optional<MallocChecker::CheckKind>
-MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
+MallocChecker::getCheckIfTracked(CKVecTy CKVec, AllocationFamily Family) const {
+  for (auto CK: CKVec) {
+    auto RetCK = getCheckIfTracked(CK, Family);
+    if (RetCK.hasValue())
+      return RetCK;
+  }
+  return Optional<MallocChecker::CheckKind>();
+}
 
+Optional<MallocChecker::CheckKind>
+MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
+                                 const Stmt *AllocDeallocStmt) const {
+  return getCheckIfTracked(CKVec, getAllocationFamily(C, AllocDeallocStmt));
+}
+
+Optional<MallocChecker::CheckKind>
+MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
+                                 SymbolRef Sym) const {
   const RefState *RS = C.getState()->get<RegionState>(Sym);
   assert(RS);
-  return getCheckIfTracked(RS->getAllocationFamily());
+  return getCheckIfTracked(CKVec, RS->getAllocationFamily());
 }
 
 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
@@ -1411,13 +1512,10 @@
                                   SourceRange Range, 
                                   const Expr *DeallocExpr) const {
 
-  if (!ChecksEnabled[CK_MallocOptimistic] &&
-      !ChecksEnabled[CK_MallocPessimistic] &&
-      !ChecksEnabled[CK_NewDeleteChecker])
-    return;
-
-  Optional<MallocChecker::CheckKind> CheckKind =
-      getCheckIfTracked(C, DeallocExpr);
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                                   CK_MallocPessimistic,
+                                                   CK_NewDeleteChecker),
+                                     C, DeallocExpr);
   if (!CheckKind.hasValue())
     return;
 
@@ -1433,23 +1531,19 @@
     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
       MR = ER->getSuperRegion();
 
-    if (MR && isa<AllocaRegion>(MR))
-      os << "Memory allocated by alloca() should not be deallocated";
-    else {
-      os << "Argument to ";
-      if (!printAllocDeallocName(os, C, DeallocExpr))
-        os << "deallocator";
+    os << "Argument to ";
+    if (!printAllocDeallocName(os, C, DeallocExpr))
+      os << "deallocator";
 
-      os << " is ";
-      bool Summarized = MR ? SummarizeRegion(os, MR) 
-                           : SummarizeValue(os, ArgVal);
-      if (Summarized)
-        os << ", which is not memory allocated by ";
-      else
-        os << "not memory allocated by ";
+    os << " is ";
+    bool Summarized = MR ? SummarizeRegion(os, MR) 
+                         : SummarizeValue(os, ArgVal);
+    if (Summarized)
+      os << ", which is not memory allocated by ";
+    else
+      os << "not memory allocated by ";
 
-      printExpectedAllocName(os, C, DeallocExpr);
-    }
+    printExpectedAllocName(os, C, DeallocExpr);
 
     BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
     R->markInteresting(MR);
@@ -1458,6 +1552,29 @@
   }
 }
 
+void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal, 
+                                     SourceRange Range) const {
+
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                               CK_MallocPessimistic,
+                                               CK_MismatchedDeallocatorChecker),
+                                     AF_Alloca);
+  if (!CheckKind.hasValue())
+    return;
+
+  if (ExplodedNode *N = C.generateSink()) {
+    if (!BT_FreeAlloca[*CheckKind])
+      BT_FreeAlloca[*CheckKind].reset(
+          new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
+
+    BugReport *R = new BugReport(*BT_FreeAlloca[*CheckKind], 
+                 "Memory allocated by alloca() should not be deallocated", N);
+    R->markInteresting(ArgVal.getAsRegion());
+    R->addRange(Range);
+    C.emitReport(R);
+  }
+}
+
 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C, 
                                             SourceRange Range,
                                             const Expr *DeallocExpr, 
@@ -1517,13 +1634,11 @@
                                      SourceRange Range, const Expr *DeallocExpr,
                                      const Expr *AllocExpr) const {
 
-  if (!ChecksEnabled[CK_MallocOptimistic] &&
-      !ChecksEnabled[CK_MallocPessimistic] &&
-      !ChecksEnabled[CK_NewDeleteChecker])
-    return;
 
-  Optional<MallocChecker::CheckKind> CheckKind =
-      getCheckIfTracked(C, AllocExpr);
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                                   CK_MallocPessimistic,
+                                                   CK_NewDeleteChecker),
+                                     C, AllocExpr);
   if (!CheckKind.hasValue())
     return;
 
@@ -1573,12 +1688,10 @@
 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
                                        SymbolRef Sym) const {
 
-  if (!ChecksEnabled[CK_MallocOptimistic] &&
-      !ChecksEnabled[CK_MallocPessimistic] &&
-      !ChecksEnabled[CK_NewDeleteChecker])
-    return;
-
-  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                                   CK_MallocPessimistic,
+                                                   CK_NewDeleteChecker),
+                                     C, Sym);
   if (!CheckKind.hasValue())
     return;
 
@@ -1601,12 +1714,10 @@
                                      bool Released, SymbolRef Sym, 
                                      SymbolRef PrevSym) const {
 
-  if (!ChecksEnabled[CK_MallocOptimistic] &&
-      !ChecksEnabled[CK_MallocPessimistic] &&
-      !ChecksEnabled[CK_NewDeleteChecker])
-    return;
-
-  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                                   CK_MallocPessimistic,
+                                                   CK_NewDeleteChecker),
+                                     C, Sym);
   if (!CheckKind.hasValue())
     return;
 
@@ -1631,13 +1742,10 @@
 
 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
 
-  if (!ChecksEnabled[CK_NewDeleteChecker])
-    return;
-
-  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_NewDeleteChecker),
+                                     C, Sym);
   if (!CheckKind.hasValue())
     return;
-  assert(*CheckKind == CK_NewDeleteChecker && "invalid check kind");
 
   if (ExplodedNode *N = C.generateSink()) {
     if (!BT_DoubleDelete)
@@ -1655,14 +1763,17 @@
 
 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
                                           const CallExpr *CE,
-                                          bool FreesOnFail) const {
+                                          bool FreesOnFail,
+                                          ProgramStateRef State) const {
+  if (!State)
+    return nullptr;
+
   if (CE->getNumArgs() < 2)
     return nullptr;
 
-  ProgramStateRef state = C.getState();
   const Expr *arg0Expr = CE->getArg(0);
   const LocationContext *LCtx = C.getLocationContext();
-  SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
+  SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
   if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
     return nullptr;
   DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
@@ -1670,7 +1781,7 @@
   SValBuilder &svalBuilder = C.getSValBuilder();
 
   DefinedOrUnknownSVal PtrEQ =
-    svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
+    svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
 
   // Get the size argument. If there is no size arg then give up.
   const Expr *Arg1 = CE->getArg(1);
@@ -1678,20 +1789,20 @@
     return nullptr;
 
   // Get the value of the size argument.
-  SVal Arg1ValG = state->getSVal(Arg1, LCtx);
+  SVal Arg1ValG = State->getSVal(Arg1, LCtx);
   if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
     return nullptr;
   DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
 
   // Compare the size argument to 0.
   DefinedOrUnknownSVal SizeZero =
-    svalBuilder.evalEQ(state, Arg1Val,
+    svalBuilder.evalEQ(State, Arg1Val,
                        svalBuilder.makeIntValWithPtrWidth(0, false));
 
   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
-  std::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
+  std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
-  std::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
+  std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
   // We only assume exceptional states if they are definitely true; if the
   // state is under-constrained, assume regular realloc behavior.
   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
@@ -1711,7 +1822,7 @@
   // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
   assert(!PrtIsNull);
   SymbolRef FromPtr = arg0Val.getAsSymbol();
-  SVal RetVal = state->getSVal(CE, LCtx);
+  SVal RetVal = State->getSVal(CE, LCtx);
   SymbolRef ToPtr = RetVal.getAsSymbol();
   if (!FromPtr || !ToPtr)
     return nullptr;
@@ -1731,7 +1842,7 @@
 
   // Default behavior.
   if (ProgramStateRef stateFree =
-        FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
+        FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
 
     ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
                                                 UnknownVal(), stateFree);
@@ -1755,20 +1866,23 @@
   return nullptr;
 }
 
-ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
+ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE, 
+                                         ProgramStateRef State) {
+  if (!State)
+    return nullptr;
+
   if (CE->getNumArgs() < 2)
     return nullptr;
 
-  ProgramStateRef state = C.getState();
   SValBuilder &svalBuilder = C.getSValBuilder();
   const LocationContext *LCtx = C.getLocationContext();
-  SVal count = state->getSVal(CE->getArg(0), LCtx);
-  SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
-  SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
+  SVal count = State->getSVal(CE->getArg(0), LCtx);
+  SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
+  SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
                                         svalBuilder.getContext().getSizeType());  
   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
 
-  return MallocMemAux(C, CE, TotalSize, zeroVal, state);
+  return MallocMemAux(C, CE, TotalSize, zeroVal, State);
 }
 
 LeakInfo
@@ -1801,9 +1915,11 @@
         }
       }
 
-    // Allocation node, is the last node in the current context in which the
-    // symbol was tracked.
-    if (N->getLocationContext() == LeakContext)
+    // Allocation node, is the last node in the current or parent context in
+    // which the symbol was tracked.
+    const LocationContext *NContext = N->getLocationContext();
+    if (NContext == LeakContext ||
+        NContext->isParentOf(LeakContext))
       AllocNode = N;
     N = N->pred_empty() ? nullptr : *(N->pred_begin());
   }
@@ -1814,24 +1930,13 @@
 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
                                CheckerContext &C) const {
 
-  if (!ChecksEnabled[CK_MallocOptimistic] &&
-      !ChecksEnabled[CK_MallocPessimistic] &&
-      !ChecksEnabled[CK_NewDeleteLeaksChecker])
-    return;
-
-  const RefState *RS = C.getState()->get<RegionState>(Sym);
-  assert(RS && "cannot leak an untracked symbol");
-  AllocationFamily Family = RS->getAllocationFamily();
-  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
+  auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                                   CK_MallocPessimistic,
+                                                   CK_NewDeleteLeaksChecker),
+                                     C, Sym);
   if (!CheckKind.hasValue())
     return;
 
-  // Special case for new and new[]; these are controlled by a separate checker
-  // flag so that they can be selectively disabled.
-  if (Family == AF_CXXNew || Family == AF_CXXNewArray)
-    if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
-      return;
-
   assert(N);
   if (!BT_Leak[*CheckKind]) {
     BT_Leak[*CheckKind].reset(
@@ -2442,8 +2547,10 @@
     for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
       const RefState *RefS = State->get<RegionState>(I.getKey());
       AllocationFamily Family = RefS->getAllocationFamily();
-      Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
-
+      auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
+                                                       CK_MallocPessimistic,
+                                                       CK_NewDeleteChecker),
+                                         Family);
       I.getKey()->dumpToStream(Out);
       Out << " : ";
       I.getData().dump(Out);
diff --git a/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp b/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
index 447e66d..55c7a65 100644
--- a/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ b/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -94,6 +94,16 @@
     ErrorReturnedNotOwned
   };
 
+  /// Tracks how an object referenced by an ivar has been used.
+  ///
+  /// This accounts for us not knowing if an arbitrary ivar is supposed to be
+  /// stored at +0 or +1.
+  enum class IvarAccessHistory {
+    None,
+    AccessedDirectly,
+    ReleasedAfterDirectAccess
+  };
+
 private:
   /// The number of outstanding retains.
   unsigned Cnt;
@@ -121,14 +131,16 @@
   /// This setting should not be propagated to state derived from this state.
   /// Once we start deriving new states, it would be inconsistent to override
   /// them.
-  unsigned IsOverridable : 1;
+  unsigned RawIvarAccessHistory : 2;
 
   RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
-         bool Overridable = false)
+         IvarAccessHistory IvarAccess)
     : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
-      RawObjectKind(static_cast<unsigned>(o)), IsOverridable(Overridable) {
+      RawObjectKind(static_cast<unsigned>(o)),
+      RawIvarAccessHistory(static_cast<unsigned>(IvarAccess)) {
     assert(getKind() == k && "not enough bits for the kind");
     assert(getObjKind() == o && "not enough bits for the object kind");
+    assert(getIvarAccessHistory() == IvarAccess && "not enough bits");
   }
 
 public:
@@ -144,20 +156,24 @@
   void clearCounts() {
     Cnt = 0;
     ACnt = 0;
-    IsOverridable = false;
   }
   void setCount(unsigned i) {
     Cnt = i;
-    IsOverridable = false;
   }
   void setAutoreleaseCount(unsigned i) {
     ACnt = i;
-    IsOverridable = false;
   }
 
   QualType getType() const { return T; }
 
-  bool isOverridable() const { return IsOverridable; }
+  /// Returns what the analyzer knows about direct accesses to a particular
+  /// instance variable.
+  ///
+  /// If the object with this refcount wasn't originally from an Objective-C
+  /// ivar region, this should always return IvarAccessHistory::None.
+  IvarAccessHistory getIvarAccessHistory() const {
+    return static_cast<IvarAccessHistory>(RawIvarAccessHistory);
+  }
 
   bool isOwned() const {
     return getKind() == Owned;
@@ -181,7 +197,7 @@
   /// Most commonly, this is an owned object with a retain count of +1.
   static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
                           unsigned Count = 1) {
-    return RefVal(Owned, o, Count, 0, t);
+    return RefVal(Owned, o, Count, 0, t, IvarAccessHistory::None);
   }
 
   /// Create a state for an object whose lifetime is not the responsibility of
@@ -190,47 +206,49 @@
   /// Most commonly, this is an unowned object with a retain count of +0.
   static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
                              unsigned Count = 0) {
-    return RefVal(NotOwned, o, Count, 0, t);
-  }
-
-  /// Create an "overridable" state for an unowned object at +0.
-  ///
-  /// An overridable state is one that provides a good approximation of the
-  /// reference counting state now, but which may be discarded later if the
-  /// checker sees the object being used in new ways.
-  static RefVal makeOverridableNotOwned(RetEffect::ObjKind o, QualType t) {
-    return RefVal(NotOwned, o, 0, 0, t, /*Overridable=*/true);
+    return RefVal(NotOwned, o, Count, 0, t, IvarAccessHistory::None);
   }
 
   RefVal operator-(size_t i) const {
     return RefVal(getKind(), getObjKind(), getCount() - i,
-                  getAutoreleaseCount(), getType());
+                  getAutoreleaseCount(), getType(), getIvarAccessHistory());
   }
 
   RefVal operator+(size_t i) const {
     return RefVal(getKind(), getObjKind(), getCount() + i,
-                  getAutoreleaseCount(), getType());
+                  getAutoreleaseCount(), getType(), getIvarAccessHistory());
   }
 
   RefVal operator^(Kind k) const {
     return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
-                  getType());
+                  getType(), getIvarAccessHistory());
   }
 
   RefVal autorelease() const {
     return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
-                  getType());
+                  getType(), getIvarAccessHistory());
+  }
+
+  RefVal withIvarAccess() const {
+    assert(getIvarAccessHistory() == IvarAccessHistory::None);
+    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
+                  getType(), IvarAccessHistory::AccessedDirectly);
+  }
+  RefVal releaseViaIvar() const {
+    assert(getIvarAccessHistory() == IvarAccessHistory::AccessedDirectly);
+    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
+                  getType(), IvarAccessHistory::ReleasedAfterDirectAccess);
   }
 
   // Comparison, profiling, and pretty-printing.
 
   bool hasSameState(const RefVal &X) const {
-    return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt;
+    return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
+           getIvarAccessHistory() == X.getIvarAccessHistory();
   }
 
   bool operator==(const RefVal& X) const {
-    return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind() &&
-           IsOverridable == X.IsOverridable;
+    return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind();
   }
   
   void Profile(llvm::FoldingSetNodeID& ID) const {
@@ -239,7 +257,7 @@
     ID.AddInteger(Cnt);
     ID.AddInteger(ACnt);
     ID.AddInteger(RawObjectKind);
-    ID.AddBoolean(IsOverridable);
+    ID.AddInteger(RawIvarAccessHistory);
   }
 
   void print(raw_ostream &Out) const;
@@ -249,9 +267,6 @@
   if (!T.isNull())
     Out << "Tracked " << T.getAsString() << '/';
 
-  if (isOverridable())
-    Out << "(overridable) ";
-
   switch (getKind()) {
     default: llvm_unreachable("Invalid RefVal kind");
     case Owned: {
@@ -323,8 +338,18 @@
       break;
   }
 
+  switch (getIvarAccessHistory()) {
+  case IvarAccessHistory::None:
+    break;
+  case IvarAccessHistory::AccessedDirectly:
+    Out << " [direct ivar access]";
+    break;
+  case IvarAccessHistory::ReleasedAfterDirectAccess:
+    Out << " [released after direct ivar access]";
+  }
+
   if (ACnt) {
-    Out << " [ARC +" << ACnt << ']';
+    Out << " [autorelease -" << ACnt << ']';
   }
 }
 } //end anonymous namespace
@@ -1580,19 +1605,19 @@
 
   // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
   addInstMethSummary("QCRenderer", AllocSumm,
-                     "createSnapshotImageOfType", NULL);
+                     "createSnapshotImageOfType", nullptr);
   addInstMethSummary("QCView", AllocSumm,
-                     "createSnapshotImageOfType", NULL);
+                     "createSnapshotImageOfType", nullptr);
 
   // Create summaries for CIContext, 'createCGImage' and
   // 'createCGLayerWithSize'.  These objects are CF objects, and are not
   // automatically garbage collected.
   addInstMethSummary("CIContext", CFAllocSumm,
-                     "createCGImage", "fromRect", NULL);
-  addInstMethSummary("CIContext", CFAllocSumm,
-                     "createCGImage", "fromRect", "format", "colorSpace", NULL);
-  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
-           "info", NULL);
+                     "createCGImage", "fromRect", nullptr);
+  addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
+                     "format", "colorSpace", nullptr);
+  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info",
+                     nullptr);
 }
 
 //===----------------------------------------------------------------------===//
@@ -1763,12 +1788,11 @@
       addGCModeDescription(LOpts, GCEnabled);
     }
 
-    std::pair<ranges_iterator, ranges_iterator> getRanges() override {
+    llvm::iterator_range<ranges_iterator> getRanges() override {
       const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
       if (!BugTy.isLeak())
         return BugReport::getRanges();
-      else
-        return std::make_pair(ranges_iterator(), ranges_iterator());
+      return llvm::make_range(ranges_iterator(), ranges_iterator());
     }
   };
 
@@ -1829,6 +1853,16 @@
          isa<CXXBoolLiteralExpr>(E);
 }
 
+/// Returns true if this stack frame is for an Objective-C method that is a
+/// property getter or setter whose body has been synthesized by the analyzer.
+static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
+  auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
+  if (!Method || !Method->isPropertyAccessor())
+    return false;
+
+  return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
+}
+
 PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
                                                    const ExplodedNode *PrevN,
                                                    BugReporterContext &BRC,
@@ -1859,6 +1893,11 @@
   if (!PrevT) {
     const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
 
+    if (isa<ObjCIvarRefExpr>(S) &&
+        isSynthesizedAccessor(LCtx->getCurrentStackFrame())) {
+      S = LCtx->getCurrentStackFrame()->getCallSite();
+    }
+
     if (isa<ObjCArrayLiteral>(S)) {
       os << "NSArray literal is an object with a +0 retain count";
     }
@@ -1883,6 +1922,9 @@
         os << "oxed expression produces an object with a +0 retain count";
       }
     }
+    else if (isa<ObjCIvarRefExpr>(S)) {
+      os << "Object loaded from instance variable";
+    }
     else {      
       if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
         // Get the name of the callee (if it is available).
@@ -2034,7 +2076,6 @@
       switch (CurrV.getKind()) {
         case RefVal::Owned:
         case RefVal::NotOwned:
-
           if (PrevV.getCount() == CurrV.getCount()) {
             // Did an autorelease message get sent?
             if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
@@ -2062,6 +2103,11 @@
           break;
 
         case RefVal::Released:
+          if (CurrV.getIvarAccessHistory() ==
+                RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
+              CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
+            os << "Strong instance variable relinquished. ";
+          }
           os << "Object released.";
           break;
 
@@ -2143,7 +2189,7 @@
 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
                   SymbolRef Sym) {
   const ExplodedNode *AllocationNode = N;
-  const ExplodedNode *AllocationNodeInCurrentContext = N;
+  const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
   const MemRegion *FirstBinding = nullptr;
   const LocationContext *LeakContext = N->getLocationContext();
 
@@ -2173,10 +2219,15 @@
     // AllocationNode is the last node in which the symbol was tracked.
     AllocationNode = N;
 
-    // AllocationNodeInCurrentContext, is the last node in the current context
-    // in which the symbol was tracked.
-    if (NContext == LeakContext)
-      AllocationNodeInCurrentContext = N;
+    // AllocationNodeInCurrentContext, is the last node in the current or
+    // parent context in which the symbol was tracked.
+    //
+    // Note that the allocation site might be in the parent conext. For example,
+    // the case where an allocation happens in a block that captures a reference
+    // to it and that reference is overwritten/dropped by another call to
+    // the block.
+    if (NContext == LeakContext || NContext->isParentOf(LeakContext))
+      AllocationNodeInCurrentOrParentContext = N;
 
     // Find the last init that was called on the given symbol and store the
     // init method's location context.
@@ -2214,7 +2265,7 @@
     FirstBinding = nullptr;
   }
 
-  return AllocationInfo(AllocationNodeInCurrentContext,
+  return AllocationInfo(AllocationNodeInCurrentOrParentContext,
                         FirstBinding,
                         InterestingMethodContext);
 }
@@ -2345,20 +2396,8 @@
   ProgramPoint P = AllocNode->getLocation();
   if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
     AllocStmt = Exit->getCalleeContext()->getCallSite();
-  else {
-    // We are going to get a BlockEdge when the leak and allocation happen in
-    // different, non-nested frames (contexts). For example, the case where an
-    // allocation happens in a block that captures a reference to it and
-    // that reference is overwritten/dropped by another call to the block.
-    if (Optional<BlockEdge> Edge = P.getAs<BlockEdge>()) {
-      if (Optional<CFGStmt> St = Edge->getDst()->front().getAs<CFGStmt>()) {
-        AllocStmt = St->getStmt();
-      }
-    }
-    else {
-      AllocStmt = P.castAs<PostStmt>().getStmt();
-    }
-  }
+  else
+    AllocStmt = P.castAs<PostStmt>().getStmt();
   assert(AllocStmt && "Cannot find allocation statement");
 
   PathDiagnosticLocation AllocLocation =
@@ -2774,17 +2813,100 @@
   C.addTransition(State);
 }
 
+static bool wasLoadedFromIvar(SymbolRef Sym) {
+  if (auto DerivedVal = dyn_cast<SymbolDerived>(Sym))
+    return isa<ObjCIvarRegion>(DerivedVal->getRegion());
+  if (auto RegionVal = dyn_cast<SymbolRegionValue>(Sym))
+    return isa<ObjCIvarRegion>(RegionVal->getRegion());
+  return false;
+}
+
+/// Returns the property that claims this instance variable, if any.
+static const ObjCPropertyDecl *findPropForIvar(const ObjCIvarDecl *Ivar) {
+  auto IsPropertyForIvar = [Ivar](const ObjCPropertyDecl *Prop) -> bool {
+    return Prop->getPropertyIvarDecl() == Ivar;
+  };
+
+  const ObjCInterfaceDecl *Interface = Ivar->getContainingInterface();
+  auto PropIter = std::find_if(Interface->prop_begin(), Interface->prop_end(),
+                               IsPropertyForIvar);
+  if (PropIter != Interface->prop_end()) {
+    return *PropIter;
+  }
+  
+  for (auto Extension : Interface->visible_extensions()) {
+    PropIter = std::find_if(Extension->prop_begin(), Extension->prop_end(),
+                            IsPropertyForIvar);
+    if (PropIter != Extension->prop_end())
+      return *PropIter;
+  }
+
+  return nullptr;
+}
+
 void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
                                        CheckerContext &C) const {
+  Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
+  if (!IVarLoc)
+    return;
+
   ProgramStateRef State = C.getState();
-  // If an instance variable was previously accessed through a property,
-  // it may have a synthesized refcount of +0. Override right now that we're
-  // doing direct access.
-  if (Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>())
-    if (SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol())
-      if (const RefVal *RV = getRefBinding(State, Sym))
-        if (RV->isOverridable())
-          State = removeRefBinding(State, Sym);
+  SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
+  if (!Sym || !wasLoadedFromIvar(Sym))
+    return;
+
+  // Accessing an ivar directly is unusual. If we've done that, be more
+  // forgiving about what the surrounding code is allowed to do.
+
+  QualType Ty = Sym->getType();
+  RetEffect::ObjKind Kind;
+  if (Ty->isObjCRetainableType())
+    Kind = RetEffect::ObjC;
+  else if (coreFoundation::isCFObjectRef(Ty))
+    Kind = RetEffect::CF;
+  else
+    return;
+
+  // If the value is already known to be nil, don't bother tracking it.
+  ConstraintManager &CMgr = State->getConstraintManager();
+  if (CMgr.isNull(State, Sym).isConstrainedTrue())
+    return;
+
+  if (const RefVal *RV = getRefBinding(State, Sym)) {
+    // If we've seen this symbol before, or we're only seeing it now because
+    // of something the analyzer has synthesized, don't do anything.
+    if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
+        isSynthesizedAccessor(C.getStackFrame())) {
+      return;
+    }
+
+    // Also don't do anything if the ivar is unretained. If so, we know that
+    // there's no outstanding retain count for the value.
+    if (const ObjCPropertyDecl *Prop = findPropForIvar(IRE->getDecl()))
+      if (!Prop->isRetaining())
+        return;
+
+    // Note that this value has been loaded from an ivar.
+    C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
+    return;
+  }
+
+  RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
+
+  // In a synthesized accessor, the effective retain count is +0.
+  if (isSynthesizedAccessor(C.getStackFrame())) {
+    C.addTransition(setRefBinding(State, Sym, PlusZero));
+    return;
+  }
+
+  // Try to find the property associated with this ivar.
+  const ObjCPropertyDecl *Prop = findPropForIvar(IRE->getDecl());
+
+  if (Prop && !Prop->isRetaining())
+    State = setRefBinding(State, Sym, PlusZero);
+  else
+    State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
+
   C.addTransition(State);
 }
 
@@ -2828,16 +2950,6 @@
   return RetTy;
 }
 
-static bool wasSynthesizedProperty(const ObjCMethodCall *Call,
-                                   ExplodedNode *N) {
-  if (!Call || !Call->getDecl()->isPropertyAccessor())
-    return false;
-
-  CallExitEnd PP = N->getLocation().castAs<CallExitEnd>();
-  const StackFrameContext *Frame = PP.getCalleeContext();
-  return Frame->getAnalysisDeclContext()->isBodyAutosynthesized();
-}
-
 // We don't always get the exact modeling of the function with regards to the
 // retain count checker even when the function is inlined. For example, we need
 // to stop tracking the symbols which were marked with StopTrackingHard.
@@ -2872,19 +2984,6 @@
     SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
     if (Sym)
       state = removeRefBinding(state, Sym);
-  } else if (RE.getKind() == RetEffect::NotOwnedSymbol) {
-    if (wasSynthesizedProperty(MsgInvocation, C.getPredecessor())) {
-      // Believe the summary if we synthesized the body of a property getter
-      // and the return value is currently untracked. If the corresponding
-      // instance variable is later accessed directly, however, we're going to
-      // want to override this state, so that the owning object can perform
-      // reference counting operations on its own ivars.
-      SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
-      if (Sym && !getRefBinding(state, Sym))
-        state = setRefBinding(state, Sym,
-                              RefVal::makeOverridableNotOwned(RE.getObjKind(),
-                                                              Sym->getType()));
-    }
   }
   
   C.addTransition(state);
@@ -3125,11 +3224,16 @@
 
         case RefVal::Owned:
           assert(V.getCount() > 0);
-          if (V.getCount() == 1)
-            V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
-                                                   : RefVal::Released);
-          else if (E == DecRefAndStopTrackingHard)
+          if (V.getCount() == 1) {
+            if (E == DecRefBridgedTransferred ||
+                V.getIvarAccessHistory() ==
+                  RefVal::IvarAccessHistory::AccessedDirectly)
+              V = V ^ RefVal::NotOwned;
+            else
+              V = V ^ RefVal::Released;
+          } else if (E == DecRefAndStopTrackingHard) {
             return removeRefBinding(state, sym);
+          }
 
           V = V - 1;
           break;
@@ -3139,6 +3243,13 @@
             if (E == DecRefAndStopTrackingHard)
               return removeRefBinding(state, sym);
             V = V - 1;
+          } else if (V.getIvarAccessHistory() ==
+                       RefVal::IvarAccessHistory::AccessedDirectly) {
+            // Assume that the instance variable was holding on the object at
+            // +1, and we just didn't know.
+            if (E == DecRefAndStopTrackingHard)
+              return removeRefBinding(state, sym);
+            V = V.releaseViaIvar() ^ RefVal::Released;
           } else {
             V = V ^ RefVal::ErrorReleaseNotOwned;
             hasErr = V.getKind();
@@ -3229,7 +3340,7 @@
   // See if it's one of the specific functions we know how to eval.
   bool canEval = false;
 
-  QualType ResultTy = CE->getCallReturnType();
+  QualType ResultTy = CE->getCallReturnType(C.getASTContext());
   if (ResultTy->isObjCIdType()) {
     // Handle: id NSMakeCollectable(CFTypeRef)
     canEval = II->isStr("NSMakeCollectable");
@@ -3428,22 +3539,31 @@
     }
   } else if (X.isReturnedNotOwned()) {
     if (RE.isOwned()) {
-      // Trying to return a not owned object to a caller expecting an
-      // owned object.
-      state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
+      if (X.getIvarAccessHistory() ==
+            RefVal::IvarAccessHistory::AccessedDirectly) {
+        // Assume the method was trying to transfer a +1 reference from a
+        // strong ivar to the caller.
+        state = setRefBinding(state, Sym,
+                              X.releaseViaIvar() ^ RefVal::ReturnedOwned);
+      } else {
+        // Trying to return a not owned object to a caller expecting an
+        // owned object.
+        state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
 
-      static CheckerProgramPointTag ReturnNotOwnedTag(this, 
-                                                      "ReturnNotOwnedForOwned");
-      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
-      if (N) {
-        if (!returnNotOwnedForOwned)
-          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
+        static CheckerProgramPointTag
+            ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
 
-        CFRefReport *report =
-            new CFRefReport(*returnNotOwnedForOwned,
-                            C.getASTContext().getLangOpts(), 
-                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
-        C.emitReport(report);
+        ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
+        if (N) {
+          if (!returnNotOwnedForOwned)
+            returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
+
+          CFRefReport *report =
+              new CFRefReport(*returnNotOwnedForOwned,
+                              C.getASTContext().getLangOpts(), 
+                              C.isObjCGCEnabled(), SummaryLog, N, Sym);
+          C.emitReport(report);
+        }
       }
     }
   }
@@ -3594,6 +3714,14 @@
   if (V.getKind() == RefVal::ReturnedOwned)
     ++Cnt;
 
+  // If we would over-release here, but we know the value came from an ivar,
+  // assume it was a strong ivar that's just been relinquished.
+  if (ACnt > Cnt &&
+      V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
+    V = V.releaseViaIvar();
+    --ACnt;
+  }
+
   if (ACnt <= Cnt) {
     if (ACnt == Cnt) {
       V.clearCounts();
diff --git a/lib/StaticAnalyzer/Core/BugReporter.cpp b/lib/StaticAnalyzer/Core/BugReporter.cpp
index dff81e3..97e97ef 100644
--- a/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ b/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -2702,22 +2702,22 @@
   return S;
 }
 
-std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
-BugReport::getRanges() {
-    // If no custom ranges, add the range of the statement corresponding to
-    // the error node.
-    if (Ranges.empty()) {
-      if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
-        addRange(E->getSourceRange());
-      else
-        return std::make_pair(ranges_iterator(), ranges_iterator());
-    }
+llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
+  // If no custom ranges, add the range of the statement corresponding to
+  // the error node.
+  if (Ranges.empty()) {
+    if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
+      addRange(E->getSourceRange());
+    else
+      return llvm::make_range(ranges_iterator(), ranges_iterator());
+  }
 
-    // User-specified absence of range info.
-    if (Ranges.size() == 1 && !Ranges.begin()->isValid())
-      return std::make_pair(ranges_iterator(), ranges_iterator());
+  // User-specified absence of range info.
+  if (Ranges.size() == 1 && !Ranges.begin()->isValid())
+    return llvm::make_range(ranges_iterator(), ranges_iterator());
 
-    return std::make_pair(Ranges.begin(), Ranges.end());
+  return llvm::iterator_range<BugReport::ranges_iterator>(Ranges.begin(),
+                                                          Ranges.end());
 }
 
 PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
@@ -2763,9 +2763,7 @@
   // warnings and new BugTypes.
   // FIXME: Only NSErrorChecker needs BugType's FlushReports.
   // Turn NSErrorChecker into a proper checker and remove this.
-  SmallVector<const BugType*, 16> bugTypes;
-  for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
-    bugTypes.push_back(*I);
+  SmallVector<const BugType *, 16> bugTypes(BugTypes.begin(), BugTypes.end());
   for (SmallVectorImpl<const BugType *>::iterator
          I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
     const_cast<BugType*>(*I)->FlushReports(*this);
@@ -3055,8 +3053,7 @@
   // Now take the pieces and construct a new PathDiagnostic.
   path.clear();
 
-  for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
-    path.push_back(*I);
+  path.insert(path.end(), Pieces.begin(), Pieces.end());
 }
 
 bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
@@ -3434,10 +3431,8 @@
     PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
     auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
         L, exampleReport->getDescription());
-    BugReport::ranges_iterator Beg, End;
-    std::tie(Beg, End) = exampleReport->getRanges();
-    for ( ; Beg != End; ++Beg)
-      piece->addRange(*Beg);
+    for (const SourceRange &Range : exampleReport->getRanges())
+      piece->addRange(Range);
     D->setEndOfPath(std::move(piece));
   }
 
diff --git a/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 2d56bd0..b906cc9 100644
--- a/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -111,15 +111,14 @@
   PathDiagnosticLocation L =
     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
 
-  BugReport::ranges_iterator Beg, End;
-  std::tie(Beg, End) = BR.getRanges();
+  const auto &Ranges = BR.getRanges();
 
   // Only add the statement itself as a range if we didn't specify any
   // special ranges for this report.
-  auto P = llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
-                                                       Beg == End);
-  for (; Beg != End; ++Beg)
-    P->addRange(*Beg);
+  auto P = llvm::make_unique<PathDiagnosticEventPiece>(
+      L, BR.getDescription(), Ranges.begin() == Ranges.end());
+  for (const SourceRange &Range : Ranges)
+    P->addRange(Range);
 
   return std::move(P);
 }
diff --git a/lib/StaticAnalyzer/Core/Checker.cpp b/lib/StaticAnalyzer/Core/Checker.cpp
index 1a3965a..2235211 100644
--- a/lib/StaticAnalyzer/Core/Checker.cpp
+++ b/lib/StaticAnalyzer/Core/Checker.cpp
@@ -36,11 +36,3 @@
   Out << Checker.getCheckName().getName();
   return Out;
 }
-
-void Checker<check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
-             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
-             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
-             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
-             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
-             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck
-             >::anchor() { }
diff --git a/lib/StaticAnalyzer/Core/ExprEngine.cpp b/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 4699df8..5cdb7eb 100644
--- a/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1901,6 +1901,9 @@
   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
 
   StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
+  assert(A->isGLValue() ||
+          (!AMgr.getLangOpts().CPlusPlus &&
+           A->getType().isCForbiddenLValueType()));
 
   for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
                                  ei = checkerPreStmt.end(); it != ei; ++it) {
@@ -1909,7 +1912,6 @@
     SVal V = state->getLValue(A->getType(),
                               state->getSVal(Idx, LCtx),
                               state->getSVal(Base, LCtx));
-    assert(A->isGLValue());
     Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), nullptr,
                       ProgramPoint::PostLValueKind);
   }
diff --git a/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/lib/StaticAnalyzer/Core/ExprEngineC.cpp
index ffda527..1777ea9 100644
--- a/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ b/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -31,7 +31,7 @@
   ExplodedNodeSet Tmp2;
   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
     
-  // With both the LHS and RHS evaluated, process the operation itself.    
+  // With both the LHS and RHS evaluated, process the operation itself.
   for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
          it != ei; ++it) {
       
diff --git a/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp b/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
index b1e9f06..88b5464 100644
--- a/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
+++ b/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
@@ -20,8 +20,8 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Rewrite/Core/HTMLRewrite.h"
 #include "clang/Rewrite/Core/Rewriter.h"
-#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
diff --git a/lib/StaticAnalyzer/Core/MemRegion.cpp b/lib/StaticAnalyzer/Core/MemRegion.cpp
index 76cead6..1fa6754 100644
--- a/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -1372,10 +1372,11 @@
     return;
 
   AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
-  AnalysisDeclContext::referenced_decls_iterator I, E;
-  std::tie(I, E) = AC->getReferencedBlockVars(BC->getDecl());
+  const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
+  auto NumBlockVars =
+      std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
 
-  if (I == E) {
+  if (NumBlockVars == 0) {
     ReferencedVars = (void*) 0x1;
     return;
   }
@@ -1386,14 +1387,14 @@
 
   typedef BumpVector<const MemRegion*> VarVec;
   VarVec *BV = (VarVec*) A.Allocate<VarVec>();
-  new (BV) VarVec(BC, E - I);
+  new (BV) VarVec(BC, NumBlockVars);
   VarVec *BVOriginal = (VarVec*) A.Allocate<VarVec>();
-  new (BVOriginal) VarVec(BC, E - I);
+  new (BVOriginal) VarVec(BC, NumBlockVars);
 
-  for ( ; I != E; ++I) {
+  for (const VarDecl *VD : ReferencedBlockVars) {
     const VarRegion *VR = nullptr;
     const VarRegion *OriginalVR = nullptr;
-    std::tie(VR, OriginalVR) = getCaptureRegions(*I);
+    std::tie(VR, OriginalVR) = getCaptureRegions(VD);
     assert(VR);
     assert(OriginalVR);
     BV->push_back(VR, BC);
diff --git a/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
index a2c66f8..76026aa 100644
--- a/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ b/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -106,13 +106,14 @@
     // by forcing to use only the beginning of the range.  This simplifies the layout
     // logic for clients.
     Indent(o, indent) << "<key>start</key>\n";
-    SourceLocation StartEdge = I->getStart().asRange().getBegin();
-    EmitRange(o, SM, LangOpts, CharSourceRange::getTokenRange(StartEdge), FM,
+    SourceRange StartEdge(
+        SM.getExpansionLoc(I->getStart().asRange().getBegin()));
+    EmitRange(o, SM, Lexer::getAsCharRange(StartEdge, SM, LangOpts), FM,
               indent + 1);
 
     Indent(o, indent) << "<key>end</key>\n";
-    SourceLocation EndEdge = I->getEnd().asRange().getBegin();
-    EmitRange(o, SM, LangOpts, CharSourceRange::getTokenRange(EndEdge), FM,
+    SourceRange EndEdge(SM.getExpansionLoc(I->getEnd().asRange().getBegin()));
+    EmitRange(o, SM, Lexer::getAsCharRange(EndEdge, SM, LangOpts), FM,
               indent + 1);
 
     --indent;
@@ -154,7 +155,7 @@
   FullSourceLoc L = P.getLocation().asLocation();
 
   Indent(o, indent) << "<key>location</key>\n";
-  EmitLocation(o, SM, LangOpts, L, FM, indent);
+  EmitLocation(o, SM, L, FM, indent);
 
   // Output the ranges (if any).
   ArrayRef<SourceRange> Ranges = P.getRanges();
@@ -163,11 +164,10 @@
     Indent(o, indent) << "<key>ranges</key>\n";
     Indent(o, indent) << "<array>\n";
     ++indent;
-    for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
-         I != E; ++I) {
-      EmitRange(o, SM, LangOpts, CharSourceRange::getTokenRange(*I), FM,
-                indent + 1);
-    }
+    for (auto &R : Ranges)
+      EmitRange(o, SM,
+                Lexer::getAsCharRange(SM.getExpansionRange(R), SM, LangOpts),
+                FM, indent + 1);
     --indent;
     Indent(o, indent) << "</array>\n";
   }
@@ -387,7 +387,9 @@
     EmitString(o, D->getCategory()) << '\n';
     o << "   <key>type</key>";
     EmitString(o, D->getBugType()) << '\n';
-    
+    o << "   <key>check_name</key>";
+    EmitString(o, D->getCheckName()) << '\n';
+ 
     // Output information about the semantic context where
     // the issue occurred.
     if (const Decl *DeclWithIssue = D->getDeclWithIssue()) {
@@ -453,7 +455,7 @@
 
     // Output the location of the bug.
     o << "  <key>location</key>\n";
-    EmitLocation(o, *SM, LangOpts, D->getLocation().asLocation(), FM, 2);
+    EmitLocation(o, *SM, D->getLocation().asLocation(), FM, 2);
 
     // Output the diagnostic to the sub-diagnostic client, if any.
     if (!filesMade->empty()) {
diff --git a/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp b/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
index 7e4a7b5..6812b11 100644
--- a/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ b/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -12,18 +12,20 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
+#include "ModelInjector.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/DataRecursiveASTVisitor.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ParentMap.h"
-#include "clang/Analysis/CodeInjector.h"
 #include "clang/Analysis/Analyses/LiveVariables.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CallGraph.h"
+#include "clang/Analysis/CodeInjector.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
@@ -34,7 +36,6 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
-#include "clang/Frontend/CompilerInstance.h"
 #include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -44,7 +45,6 @@
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/raw_ostream.h"
-#include "ModelInjector.h"
 #include <memory>
 #include <queue>
 
@@ -590,7 +590,7 @@
   // - System headers: don't run any checks.
   SourceManager &SM = Ctx->getSourceManager();
   SourceLocation SL = SM.getExpansionLoc(D->getLocation());
-  if (!Opts->AnalyzeAll && !SM.isInMainFile(SL)) {
+  if (!Opts->AnalyzeAll && !SM.isWrittenInMainFile(SL)) {
     if (SL.isInvalid() || SM.isInSystemHeader(SL))
       return AM_None;
     return Mode & ~AM_Path;
diff --git a/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp b/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp
index 36565cb..b3ff797 100644
--- a/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp
+++ b/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp
@@ -125,7 +125,7 @@
 
   }
 
-  return std::move(checkerMgr);
+  return checkerMgr;
 }
 
 void ento::printCheckerHelp(raw_ostream &out, ArrayRef<std::string> plugins) {
diff --git a/lib/StaticAnalyzer/Frontend/ModelInjector.cpp b/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
index d5b623c..63bb1e2 100644
--- a/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
+++ b/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
@@ -8,21 +8,19 @@
 //===----------------------------------------------------------------------===//
 
 #include "ModelInjector.h"
-
-#include <string>
-#include <utility>
-
+#include "clang/AST/Decl.h"
+#include "clang/Basic/IdentifierTable.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendAction.h"
-#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
-#include "clang/Serialization/ASTReader.h"
-#include "clang/Basic/IdentifierTable.h"
-#include "clang/AST/Decl.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Serialization/ASTReader.h"
+#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/FileSystem.h"
-#include "llvm/ADT/STLExtras.h"
+#include <string>
+#include <utility>
 
 using namespace clang;
 using namespace ento;
diff --git a/lib/StaticAnalyzer/Frontend/ModelInjector.h b/lib/StaticAnalyzer/Frontend/ModelInjector.h
index 448dd0c..fd24e32 100644
--- a/lib/StaticAnalyzer/Frontend/ModelInjector.h
+++ b/lib/StaticAnalyzer/Frontend/ModelInjector.h
@@ -24,13 +24,12 @@
 #ifndef LLVM_CLANG_SA_FRONTEND_MODELINJECTOR_H
 #define LLVM_CLANG_SA_FRONTEND_MODELINJECTOR_H
 
-#include <map>
-#include <vector>
-#include <memory>
-
 #include "clang/Analysis/CodeInjector.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/StringMap.h"
+#include <map>
+#include <memory>
+#include <vector>
 
 namespace clang {
 
diff --git a/lib/Tooling/ArgumentsAdjusters.cpp b/lib/Tooling/ArgumentsAdjusters.cpp
index 36ac34e..1722ede 100644
--- a/lib/Tooling/ArgumentsAdjusters.cpp
+++ b/lib/Tooling/ArgumentsAdjusters.cpp
@@ -19,55 +19,68 @@
 namespace clang {
 namespace tooling {
 
-void ArgumentsAdjuster::anchor() {
-}
-
 /// Add -fsyntax-only option to the commnand line arguments.
-CommandLineArguments
-ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) {
-  CommandLineArguments AdjustedArgs;
-  for (size_t i = 0, e = Args.size(); i != e; ++i) {
-    StringRef Arg = Args[i];
-    // FIXME: Remove options that generate output.
-    if (!Arg.startswith("-fcolor-diagnostics") &&
-        !Arg.startswith("-fdiagnostics-color"))
-      AdjustedArgs.push_back(Args[i]);
-  }
-  AdjustedArgs.push_back("-fsyntax-only");
-  return AdjustedArgs;
-}
-
-CommandLineArguments
-ClangStripOutputAdjuster::Adjust(const CommandLineArguments &Args) {
-  CommandLineArguments AdjustedArgs;
-  for (size_t i = 0, e = Args.size(); i < e; ++i) {
-    StringRef Arg = Args[i];
-    if(!Arg.startswith("-o"))
-      AdjustedArgs.push_back(Args[i]);
-
-    if(Arg == "-o") {
-      // Output is specified as -o foo. Skip the next argument also.
-      ++i;
+ArgumentsAdjuster getClangSyntaxOnlyAdjuster() {
+  return [](const CommandLineArguments &Args) {
+    CommandLineArguments AdjustedArgs;
+    for (size_t i = 0, e = Args.size(); i != e; ++i) {
+      StringRef Arg = Args[i];
+      // FIXME: Remove options that generate output.
+      if (!Arg.startswith("-fcolor-diagnostics") &&
+          !Arg.startswith("-fdiagnostics-color"))
+        AdjustedArgs.push_back(Args[i]);
     }
-    // Else, the output is specified as -ofoo. Just do nothing.
-  }
-  return AdjustedArgs;
+    AdjustedArgs.push_back("-fsyntax-only");
+    return AdjustedArgs;
+  };
 }
 
-CommandLineArguments
-InsertArgumentAdjuster::Adjust(const CommandLineArguments &Args) {
-  CommandLineArguments Return(Args);
+ArgumentsAdjuster getClangStripOutputAdjuster() {
+  return [](const CommandLineArguments &Args) {
+    CommandLineArguments AdjustedArgs;
+    for (size_t i = 0, e = Args.size(); i < e; ++i) {
+      StringRef Arg = Args[i];
+      if (!Arg.startswith("-o"))
+        AdjustedArgs.push_back(Args[i]);
 
-  CommandLineArguments::iterator I;
-  if (Pos == END) {
-    I = Return.end();
-  } else {
-    I = Return.begin();
-    ++I; // To leave the program name in place
-  }
+      if (Arg == "-o") {
+        // Output is specified as -o foo. Skip the next argument also.
+        ++i;
+      }
+      // Else, the output is specified as -ofoo. Just do nothing.
+    }
+    return AdjustedArgs;
+  };
+}
 
-  Return.insert(I, Extra.begin(), Extra.end());
-  return Return;
+ArgumentsAdjuster getInsertArgumentAdjuster(const CommandLineArguments &Extra,
+                                            ArgumentInsertPosition Pos) {
+  return [Extra, Pos](const CommandLineArguments &Args) {
+    CommandLineArguments Return(Args);
+
+    CommandLineArguments::iterator I;
+    if (Pos == ArgumentInsertPosition::END) {
+      I = Return.end();
+    } else {
+      I = Return.begin();
+      ++I; // To leave the program name in place
+    }
+
+    Return.insert(I, Extra.begin(), Extra.end());
+    return Return;
+  };
+}
+
+ArgumentsAdjuster getInsertArgumentAdjuster(const char *Extra,
+                                            ArgumentInsertPosition Pos) {
+  return getInsertArgumentAdjuster(CommandLineArguments(1, Extra), Pos);
+}
+
+ArgumentsAdjuster combineAdjusters(ArgumentsAdjuster First,
+                                   ArgumentsAdjuster Second) {
+  return [First, Second](const CommandLineArguments &Args) {
+    return Second(First(Args));
+  };
 }
 
 } // end namespace tooling
diff --git a/lib/Tooling/CommonOptionsParser.cpp b/lib/Tooling/CommonOptionsParser.cpp
index f16a6be..9a484c1 100644
--- a/lib/Tooling/CommonOptionsParser.cpp
+++ b/lib/Tooling/CommonOptionsParser.cpp
@@ -60,8 +60,8 @@
       std::unique_ptr<CompilationDatabase> Compilations)
       : Compilations(std::move(Compilations)) {}
 
-  void appendArgumentsAdjuster(std::unique_ptr<ArgumentsAdjuster> Adjuster) {
-    Adjusters.push_back(std::move(Adjuster));
+  void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
+    Adjusters.push_back(Adjuster);
   }
 
   std::vector<CompileCommand>
@@ -79,13 +79,13 @@
 
 private:
   std::unique_ptr<CompilationDatabase> Compilations;
-  std::vector<std::unique_ptr<ArgumentsAdjuster>> Adjusters;
+  std::vector<ArgumentsAdjuster> Adjusters;
 
   std::vector<CompileCommand>
   adjustCommands(std::vector<CompileCommand> Commands) const {
     for (CompileCommand &Command : Commands)
       for (const auto &Adjuster : Adjusters)
-        Command.CommandLine = Adjuster->Adjust(Command.CommandLine);
+        Command.CommandLine = Adjuster(Command.CommandLine);
     return Commands;
   }
 };
@@ -112,15 +112,7 @@
       cl::desc("Additional argument to prepend to the compiler command line"),
       cl::cat(Category));
 
-  // Hide unrelated options.
-  StringMap<cl::Option*> Options;
-  cl::getRegisteredOptions(Options);
-  for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
-       I != E; ++I) {
-    if (I->second->Category != &Category && I->first() != "help" &&
-        I->first() != "version")
-      I->second->setHiddenFlag(cl::ReallyHidden);
-  }
+  cl::HideUnrelatedOptions(Category);
 
   Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc,
                                                                    argv));
@@ -142,10 +134,8 @@
       llvm::make_unique<ArgumentsAdjustingCompilations>(
           std::move(Compilations));
   AdjustingCompilations->appendArgumentsAdjuster(
-      llvm::make_unique<InsertArgumentAdjuster>(ArgsBefore,
-                                                InsertArgumentAdjuster::BEGIN));
+      getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN));
   AdjustingCompilations->appendArgumentsAdjuster(
-      llvm::make_unique<InsertArgumentAdjuster>(ArgsAfter,
-                                                InsertArgumentAdjuster::END));
+      getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
   Compilations = std::move(AdjustingCompilations);
 }
diff --git a/lib/Tooling/Tooling.cpp b/lib/Tooling/Tooling.cpp
index 64613de..60371fb 100644
--- a/lib/Tooling/Tooling.cpp
+++ b/lib/Tooling/Tooling.cpp
@@ -123,17 +123,25 @@
 
 bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
                            const std::vector<std::string> &Args,
-                           const Twine &FileName) {
+                           const Twine &FileName,
+                           const FileContentMappings &VirtualMappedFiles) {
+
   SmallString<16> FileNameStorage;
   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
   llvm::IntrusiveRefCntPtr<FileManager> Files(
       new FileManager(FileSystemOptions()));
-  ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction,
-                            Files.get());
+  ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
+                            ToolAction, Files.get());
 
   SmallString<1024> CodeStorage;
   Invocation.mapVirtualFile(FileNameRef,
                             Code.toNullTerminatedStringRef(CodeStorage));
+
+  for (auto &FilenameWithContent : VirtualMappedFiles) {
+    Invocation.mapVirtualFile(FilenameWithContent.first,
+                              FilenameWithContent.second);
+  }
+
   return Invocation.run();
 }
 
@@ -271,8 +279,8 @@
                      ArrayRef<std::string> SourcePaths)
     : Compilations(Compilations), SourcePaths(SourcePaths),
       Files(new FileManager(FileSystemOptions())), DiagConsumer(nullptr) {
-  appendArgumentsAdjuster(new ClangStripOutputAdjuster());
-  appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster());
+  appendArgumentsAdjuster(getClangStripOutputAdjuster());
+  appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
 }
 
 ClangTool::~ClangTool() {}
@@ -281,12 +289,15 @@
   MappedFileContents.push_back(std::make_pair(FilePath, Content));
 }
 
-void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster *Adjuster) {
-  ArgsAdjusters.push_back(std::unique_ptr<ArgumentsAdjuster>(Adjuster));
+void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
+  if (ArgsAdjuster)
+    ArgsAdjuster = combineAdjusters(ArgsAdjuster, Adjuster);
+  else
+    ArgsAdjuster = Adjuster;
 }
 
 void ClangTool::clearArgumentsAdjusters() {
-  ArgsAdjusters.clear();
+  ArgsAdjuster = nullptr;
 }
 
 int ClangTool::run(ToolAction *Action) {
@@ -339,8 +350,8 @@
         llvm::report_fatal_error("Cannot chdir into \"" +
                                  Twine(CompileCommand.Directory) + "\n!");
       std::vector<std::string> CommandLine = CompileCommand.CommandLine;
-      for (const auto &Adjuster : ArgsAdjusters)
-        CommandLine = Adjuster->Adjust(CommandLine);
+      if (ArgsAdjuster)
+        CommandLine = ArgsAdjuster(CommandLine);
       assert(!CommandLine.empty());
       CommandLine[0] = MainExecutable;
       // FIXME: We need a callback mechanism for the tool writer to output a
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index dc14541..ad383f6 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -87,8 +87,8 @@
     FileCheck count not llvm-nm llvm-symbolizer)
 
   # Add top-level targets for various compiler-rt test suites.
-  set(COMPILER_RT_TEST_SUITES check-asan check-dfsan check-lsan check-msan
-    check-sanitizer check-tsan check-ubsan)
+  set(COMPILER_RT_TEST_SUITES check-asan check-asan-dynamic check-dfsan
+    check-lsan check-msan check-sanitizer check-tsan check-ubsan)
   foreach(test_suite ${COMPILER_RT_TEST_SUITES})
     get_ext_project_build_command(run_test_suite ${test_suite})
     add_custom_target(${test_suite}
diff --git a/runtime/compiler-rt/Makefile b/runtime/compiler-rt/Makefile
index f06ef99..c310453 100644
--- a/runtime/compiler-rt/Makefile
+++ b/runtime/compiler-rt/Makefile
@@ -122,8 +122,7 @@
 
 # We try to build 32-bit runtimes both on 32-bit hosts and 64-bit hosts.
 Runtime32BitConfigs = \
-	builtins-i386.a profile-i386.a san-i386.a asan-i386.a asan_cxx-i386.a \
-	ubsan-i386.a ubsan_cxx-i386.a
+	builtins-i386.a profile-i386.a
 
 # We currently only try to generate runtime libraries on x86.
 ifeq ($(ARCH),x86)
@@ -132,21 +131,15 @@
 
 ifeq ($(ARCH),x86_64)
 RuntimeLibrary.linux.Configs += \
-	builtins-x86_64.a profile-x86_64.a san-x86_64.a asan-x86_64.a \
-	asan_cxx-x86_64.a tsan-x86_64.a msan-x86_64.a ubsan-x86_64.a \
-	ubsan_cxx-x86_64.a dfsan-x86_64.a lsan-x86_64.a
-# We need to build 32-bit ASan/UBsan libraries on 64-bit platform, and add them
-# to the list of runtime libraries to make
-# "clang -fsanitize=(address|undefined) -m32" work.
+	builtins-x86_64.a profile-x86_64.a
+# We need to build 32-bit libraries on 64-bit platform, and add them
+# to the list of runtime libraries to make "clang -m32" work.
 # We check that Clang can produce working 32-bit binaries by compiling a simple
 # executable.
 test_source = $(LLVM_SRC_ROOT)/tools/clang/runtime/compiler-rt/clang_linux_test_input.c
 ifeq ($(call TryCompile,$(ToolDir)/clang,$(test_source),-m32),0)
 RuntimeLibrary.linux.Configs += $(Runtime32BitConfigs)
 endif
-ifneq ($(LLVM_ANDROID_TOOLCHAIN_DIR),)
-RuntimeLibrary.linux.Configs += asan-arm-android.so
-endif
 endif
 
 endif
@@ -166,7 +159,6 @@
 	  ProjObjRoot=$(PROJ_OBJ_DIR) \
 	  CC="$(ToolDir)/clang" \
 	  VERBOSE=$(VERBOSE) \
-	  LLVM_ANDROID_TOOLCHAIN_DIR="$(LLVM_ANDROID_TOOLCHAIN_DIR)" \
 	  $(RuntimeDirs:%=clang_%)
 .PHONY: BuildRuntimeLibraries
 CleanRuntimeLibraries:
diff --git a/test/ARCMT/nonobjc-to-objc-cast.m b/test/ARCMT/nonobjc-to-objc-cast.m
index b7d2a73..7913661 100644
--- a/test/ARCMT/nonobjc-to-objc-cast.m
+++ b/test/ARCMT/nonobjc-to-objc-cast.m
@@ -7,6 +7,7 @@
 typedef const struct __CFString * CFStringRef;
 extern const CFStringRef kUTTypePlainText;
 extern const CFStringRef kUTTypeRTF;
+extern CFStringRef kNonConst;
 
 typedef const struct __CFAllocator * CFAllocatorRef;
 typedef const struct __CFUUID * CFUUIDRef;
@@ -28,11 +29,15 @@
 @end
 
 void f(BOOL b, id p) {
-  NSString *str = (NSString *)kUTTypePlainText;
-  str = b ? kUTTypeRTF : kUTTypePlainText;
-  str = (NSString *)(b ? kUTTypeRTF : kUTTypePlainText);
+  NSString *str = (NSString *)kUTTypePlainText; // no change
+  str = b ? kUTTypeRTF : kUTTypePlainText; // no change
+  str = (NSString *)(b ? kUTTypeRTF : kUTTypePlainText); // no change
   str = (NSString *)p; // no change.
 
+  str = (NSString *)kNonConst;
+  str = b ? kUTTypeRTF : kNonConst;
+  str = (NSString *)(b ? kUTTypeRTF : kNonConst);
+
   CFUUIDRef   _uuid;
   NSString *_uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, _uuid);
   _uuidString = [(NSString *)CFUUIDCreateString(kCFAllocatorDefault, _uuid) autorelease];
diff --git a/test/ARCMT/nonobjc-to-objc-cast.m.result b/test/ARCMT/nonobjc-to-objc-cast.m.result
index ce827ba..8f3092f 100644
--- a/test/ARCMT/nonobjc-to-objc-cast.m.result
+++ b/test/ARCMT/nonobjc-to-objc-cast.m.result
@@ -7,6 +7,7 @@
 typedef const struct __CFString * CFStringRef;
 extern const CFStringRef kUTTypePlainText;
 extern const CFStringRef kUTTypeRTF;
+extern CFStringRef kNonConst;
 
 typedef const struct __CFAllocator * CFAllocatorRef;
 typedef const struct __CFUUID * CFUUIDRef;
@@ -28,11 +29,15 @@
 @end
 
 void f(BOOL b, id p) {
-  NSString *str = (__bridge NSString *)kUTTypePlainText;
-  str = (__bridge NSString *)(b ? kUTTypeRTF : kUTTypePlainText);
-  str = (__bridge NSString *)(b ? kUTTypeRTF : kUTTypePlainText);
+  NSString *str = (NSString *)kUTTypePlainText; // no change
+  str = b ? kUTTypeRTF : kUTTypePlainText; // no change
+  str = (NSString *)(b ? kUTTypeRTF : kUTTypePlainText); // no change
   str = (NSString *)p; // no change.
 
+  str = (__bridge NSString *)kNonConst;
+  str = (__bridge NSString *)(b ? kUTTypeRTF : kNonConst);
+  str = (__bridge NSString *)(b ? kUTTypeRTF : kNonConst);
+
   CFUUIDRef   _uuid;
   NSString *_uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, _uuid));
   _uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, _uuid));
diff --git a/test/ARCMT/objcmt-ns-macros.m b/test/ARCMT/objcmt-ns-macros.m
index 1d5583b..795b94a 100644
--- a/test/ARCMT/objcmt-ns-macros.m
+++ b/test/ARCMT/objcmt-ns-macros.m
@@ -363,3 +363,19 @@
         UIU8one = 1
 };
 typedef uint8_t UI8Type;
+
+// rdar://19352510
+typedef enum : NSInteger {zero} MyEnum;
+
+typedef enum : NSUInteger {two} MyEnumNSUInteger;
+
+typedef enum : int {three, four} MyEnumint;
+
+typedef enum : unsigned long {five} MyEnumlonglong;
+
+typedef enum : unsigned long long {
+  ll1,
+  ll2= 0xff,
+  ll3,
+  ll4
+} MyEnumunsignedlonglong;
diff --git a/test/ARCMT/objcmt-ns-macros.m.result b/test/ARCMT/objcmt-ns-macros.m.result
index 9087065..094c444 100644
--- a/test/ARCMT/objcmt-ns-macros.m.result
+++ b/test/ARCMT/objcmt-ns-macros.m.result
@@ -37,7 +37,7 @@
     UIViewAutoresizingFlexibleBottomMargin
 };
 
-typedef NS_ENUM(NSInteger, UIViewAnimationTransition) {
+typedef NS_ENUM(unsigned int, UIViewAnimationTransition) {
     UIViewAnimationTransitionNone,
     UIViewAnimationTransitionFlipFromLeft,
     UIViewAnimationTransitionFlipFromRight,
@@ -45,7 +45,7 @@
     UIViewAnimationTransitionCurlDown,
 };
 
-typedef NS_OPTIONS(NSUInteger, UITableView) {
+typedef NS_OPTIONS(unsigned int, UITableView) {
     UIViewOne   = 0,
     UIViewTwo   = 1 << 0,
     UIViewThree = 1 << 1,
@@ -62,7 +62,7 @@
   UIFour = 0x100
 };
 
-typedef NS_OPTIONS(NSUInteger, UIPOWER2) {
+typedef NS_OPTIONS(unsigned int, UIPOWER2) {
   UIP2One = 0,
   UIP2Two = 0x1,
   UIP2three = 0x8,
@@ -80,7 +80,7 @@
   UIKTwo = 2,
 };
 
-typedef NS_ENUM(NSInteger, NSTickMarkPosition)  {
+typedef NS_ENUM(unsigned int, NSTickMarkPosition)  {
     NSTickMarkBelow = 0,
     NSTickMarkAbove = 1,
     NSTickMarkLeft = NSTickMarkAbove,
@@ -150,7 +150,7 @@
     NSFCopyIn NS_ENUM_AVAILABLE(10_5, 6_0) = (1UL << 16),      
 };
 
-typedef NS_ENUM(NSInteger, UIP) {
+typedef NS_ENUM(unsigned int, UIP) {
   UIP0One = 0,
   UIP0Two = 1,
   UIP0Three = 2,
@@ -158,7 +158,7 @@
   UIP0Last = 0x100
 };
 
-typedef NS_OPTIONS(NSUInteger, UIP_3) {
+typedef NS_OPTIONS(unsigned int, UIP_3) {
   UIPZero = 0x0,
   UIPOne = 0x1,
   UIPTwo = 0x2,
@@ -166,7 +166,7 @@
   UIPHundred = 0x100
 };
 
-typedef NS_ENUM(NSInteger, UIP4_3) {
+typedef NS_ENUM(unsigned int, UIP4_3) {
   UIP4Zero = 0x0,
   UIP4One = 0x1,
   UIP4Two = 0x2,
@@ -174,14 +174,14 @@
   UIP4Hundred = 100
 };
 
-typedef NS_OPTIONS(NSUInteger, UIP5_3) {
+typedef NS_OPTIONS(unsigned int, UIP5_3) {
   UIP5Zero = 0x0,
   UIP5Two = 0x2,
   UIP510 = 0x3,
   UIP5Hundred = 0x4
 };
 
-typedef NS_ENUM(NSInteger, UIP6_3) {
+typedef NS_ENUM(unsigned int, UIP6_3) {
   UIP6Zero = 0x0,
   UIP6One = 0x1,
   UIP6Two = 0x2,
@@ -189,7 +189,7 @@
   UIP6Hundred = 0x100
 };
 
-typedef NS_ENUM(NSInteger, UIP7_3) {
+typedef NS_ENUM(unsigned int, UIP7_3) {
   UIP7Zero = 0x0,
   UIP7One = 1,
   UIP7Two = 0x2,
@@ -198,7 +198,7 @@
 };
 
 
-typedef NS_ENUM(NSInteger, UIP8_3) {
+typedef NS_ENUM(unsigned int, UIP8_3) {
   Random = 0,
   Random1 = 2,
   Random2 = 4,
@@ -291,26 +291,26 @@
 // standard window buttons
 
 // rdar://18262255
-typedef enum : NSUInteger {
+typedef NS_ENUM(NSUInteger, Thing) {
    ThingOne,
    ThingTwo,
    ThingThree,
-} Thing;
+};
 
 // rdar://18498539
-typedef NS_ENUM(NSInteger, NumericEnum) {
+typedef NS_ENUM(unsigned int, NumericEnum) {
     one = 1
 };
 
-typedef NS_ENUM(NSInteger, NumericEnum2) {
+typedef NS_ENUM(unsigned int, NumericEnum2) {
     Two = 2
 };
 
-typedef NS_ENUM(NSInteger, NumericEnum3) {
+typedef NS_ENUM(unsigned int, NumericEnum3) {
     Three = 3
 };
 
-typedef NS_OPTIONS(NSUInteger, NumericEnum4) {
+typedef NS_OPTIONS(unsigned int, NumericEnum4) {
     Four = 4
 };
 
@@ -342,3 +342,19 @@
 {
         UIU8one = 1
 };
+
+// rdar://19352510
+typedef NS_ENUM(NSInteger, MyEnum) {zero};
+
+typedef NS_ENUM(NSUInteger, MyEnumNSUInteger) {two};
+
+typedef NS_ENUM(int, MyEnumint) {three, four};
+
+typedef NS_ENUM(unsigned long, MyEnumlonglong) {five};
+
+typedef NS_ENUM(unsigned long long, MyEnumunsignedlonglong) {
+  ll1,
+  ll2= 0xff,
+  ll3,
+  ll4
+};
diff --git a/test/ARCMT/objcmt-property-dot-syntax.m b/test/ARCMT/objcmt-property-dot-syntax.m
index 42aade5..f1b9255 100644
--- a/test/ARCMT/objcmt-property-dot-syntax.m
+++ b/test/ARCMT/objcmt-property-dot-syntax.m
@@ -37,3 +37,77 @@
 
 - (P*) MethodReturnsPObj { return 0; }
 @end
+
+// rdar://19140267
+@interface Sub : P
+@end
+
+@implementation Sub
+- (int) Meth : (P*)array {
+  [super setCount : 100];
+
+  [super setCount : [array count]];
+
+  [[super PropertyReturnsPObj] setCount : [array count]];
+
+  [super setCount : (i1+i2*i3 - 100)];
+
+  return [super count] -
+         [(P*)0 count] + [array count] +
+         [fun() count] -
+         [[super PropertyReturnsPObj] count] +
+         [self->obj count];
+}
+@end
+
+
+@interface Rdar19038838
+@property id newItem; // should be marked objc_method_family(none), but isn't.
+@end
+
+id testRdar19038838(Rdar19038838 *obj) {
+  return [obj newItem];
+}
+
+// rdar://19381786
+@interface rdar19381786 : NSObject
+{
+  rdar19381786* obj;
+}
+@property int count;
+@end
+
+@protocol PR 
+@property int count;
+@end
+
+@implementation rdar19381786
+-(void)test:(id)some : (id<PR>)qsome : (SEL)selsome
+{
+  [obj setCount : 100];
+  [some setCount : [some count]];
+  [qsome setCount : [qsome count]];
+}
+@end
+
+// rdar://19140114
+int NSOnState;
+int ArrNSOnState[4];
+@interface rdar19140114 : NSObject
+{
+  rdar19140114* menuItem;
+}
+@property int state;
+@end
+
+@implementation rdar19140114
+- (void) Meth {
+  [menuItem setState:NSOnState];
+  [menuItem setState :NSOnState];
+  [menuItem setState     :ArrNSOnState[NSOnState]];
+  [menuItem setState : NSOnState];
+  [menuItem setState:    NSOnState];
+  [menuItem setState: NSOnState];
+  [menuItem setState     :    NSOnState];
+}
+@end
diff --git a/test/ARCMT/objcmt-property-dot-syntax.m.result b/test/ARCMT/objcmt-property-dot-syntax.m.result
index 88006e9..70c7e7a 100644
--- a/test/ARCMT/objcmt-property-dot-syntax.m.result
+++ b/test/ARCMT/objcmt-property-dot-syntax.m.result
@@ -37,3 +37,77 @@
 
 - (P*) MethodReturnsPObj { return 0; }
 @end
+
+// rdar://19140267
+@interface Sub : P
+@end
+
+@implementation Sub
+- (int) Meth : (P*)array {
+  super.count = 100;
+
+  super.count = array.count;
+
+  super.PropertyReturnsPObj.count = array.count;
+
+  super.count = (i1+i2*i3 - 100);
+
+  return super.count -
+         ((P*)0).count + array.count +
+         fun().count -
+         super.PropertyReturnsPObj.count +
+         self->obj.count;
+}
+@end
+
+
+@interface Rdar19038838
+@property id newItem; // should be marked objc_method_family(none), but isn't.
+@end
+
+id testRdar19038838(Rdar19038838 *obj) {
+  return obj.newItem;
+}
+
+// rdar://19381786
+@interface rdar19381786 : NSObject
+{
+  rdar19381786* obj;
+}
+@property int count;
+@end
+
+@protocol PR 
+@property int count;
+@end
+
+@implementation rdar19381786
+-(void)test:(id)some : (id<PR>)qsome : (SEL)selsome
+{
+  obj.count = 100;
+  [some setCount : [some count]];
+  [qsome setCount : [qsome count]];
+}
+@end
+
+// rdar://19140114
+int NSOnState;
+int ArrNSOnState[4];
+@interface rdar19140114 : NSObject
+{
+  rdar19140114* menuItem;
+}
+@property int state;
+@end
+
+@implementation rdar19140114
+- (void) Meth {
+  menuItem.state = NSOnState;
+  menuItem.state = NSOnState;
+  menuItem.state = ArrNSOnState[NSOnState];
+  menuItem.state = NSOnState;
+  menuItem.state = NSOnState;
+  menuItem.state = NSOnState;
+  menuItem.state = NSOnState;
+}
+@end
diff --git a/test/ARCMT/objcmt-undefined-ns-macros.m.result b/test/ARCMT/objcmt-undefined-ns-macros.m.result
index 866e4d0..30277ac 100644
--- a/test/ARCMT/objcmt-undefined-ns-macros.m.result
+++ b/test/ARCMT/objcmt-undefined-ns-macros.m.result
@@ -18,9 +18,9 @@
 
 
 typedef
-  NS_ENUM(NSInteger, NumericEnum2) { two = 1 };
+  NS_ENUM(unsigned int, NumericEnum2) { two = 1 };
 
-typedef NS_ENUM(NSInteger, NumericEnum3) { three = 1 };
+typedef NS_ENUM(unsigned int, NumericEnum3) { three = 1 };
 
-typedef NS_ENUM(NSInteger, NumericEnum4) { four = 1 };
+typedef NS_ENUM(unsigned int, NumericEnum4) { four = 1 };
 
diff --git a/test/Analysis/MismatchedDeallocator-checker-test.mm b/test/Analysis/MismatchedDeallocator-checker-test.mm
index 0df5db5..15815e8 100644
--- a/test/Analysis/MismatchedDeallocator-checker-test.mm
+++ b/test/Analysis/MismatchedDeallocator-checker-test.mm
@@ -59,6 +59,11 @@
   operator delete[](p); // expected-warning{{Memory allocated by malloc() should be deallocated by free(), not operator delete[]}}
 }
 
+void testAlloca() {
+  int *p = (int *)__builtin_alloca(sizeof(int));
+  delete p; // expected-warning{{Memory allocated by alloca() should not be deallocated}}
+}
+
 //--------------- test new family
 void testNew1() {
   int *p = new int;
diff --git a/test/Analysis/MismatchedDeallocator-path-notes.cpp b/test/Analysis/MismatchedDeallocator-path-notes.cpp
index 61ab4f1..686497c 100644
--- a/test/Analysis/MismatchedDeallocator-path-notes.cpp
+++ b/test/Analysis/MismatchedDeallocator-path-notes.cpp
@@ -146,6 +146,7 @@
 // CHECK-NEXT:   <key>description</key><string>Memory allocated by &apos;new[]&apos; should be deallocated by &apos;delete[]&apos;, not &apos;delete&apos;</string>
 // CHECK-NEXT:   <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:   <key>type</key><string>Bad deallocator</string>
+// CHECK-NEXT:   <key>check_name</key><string>unix.MismatchedDeallocator</string> 
 // CHECK-NEXT:  <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:  <key>issue_context</key><string>test</string>
 // CHECK-NEXT:  <key>issue_hash</key><string>4</string>
diff --git a/test/Analysis/NewDelete-checker-test.cpp b/test/Analysis/NewDelete-checker-test.cpp
index 84176c9..3f28c2e 100644
--- a/test/Analysis/NewDelete-checker-test.cpp
+++ b/test/Analysis/NewDelete-checker-test.cpp
@@ -144,11 +144,6 @@
   c->f(0); // expected-warning{{Use of memory after it is freed}}
 }
 
-void testDeleteAlloca() {
-  int *p = (int *)__builtin_alloca(sizeof(int));
-  delete p; // expected-warning{{Memory allocated by alloca() should not be deallocated}}
-}
-
 void testDoubleDelete() {
   int *p = new int;
   delete p;
diff --git a/test/Analysis/NewDelete-intersections.mm b/test/Analysis/NewDelete-intersections.mm
index 886df12..7b3fb6e 100644
--- a/test/Analysis/NewDelete-intersections.mm
+++ b/test/Analysis/NewDelete-intersections.mm
@@ -5,6 +5,7 @@
 
 typedef __typeof__(sizeof(int)) size_t;
 extern "C" void *malloc(size_t);
+extern "C" void *alloca(size_t);
 extern "C" void free(void *);
 
 //----------------------------------------------------------------------------
@@ -29,11 +30,17 @@
   int *p4 = (int *)malloc(sizeof(int));
   free(p4);
   int j = *p4; // no warn
+
+  int *p5 = (int *)alloca(sizeof(int));
+  free(p5); // no warn
 }
 
 void testDeleteMalloced() {
-  int *p = (int *)malloc(sizeof(int));
-  delete p; // no warn
+  int *p1 = (int *)malloc(sizeof(int));
+  delete p1; // no warn
+
+  int *p2 = (int *)__builtin_alloca(sizeof(int));
+  delete p2; // no warn
 } 
 
 //----- Test free standard new
diff --git a/test/Analysis/NewDelete-path-notes.cpp b/test/Analysis/NewDelete-path-notes.cpp
index b420551..f55df00 100644
--- a/test/Analysis/NewDelete-path-notes.cpp
+++ b/test/Analysis/NewDelete-path-notes.cpp
@@ -259,6 +259,7 @@
 // CHECK-NEXT:    <key>description</key><string>Attempt to free released memory</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Double free</string>
+// CHECK-NEXT:    <key>check_name</key><string>cplusplus.NewDelete</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -474,6 +475,7 @@
 // CHECK-NEXT:    <key>description</key><string>Attempt to free released memory</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Double free</string>
+// CHECK-NEXT:    <key>check_name</key><string>cplusplus.NewDelete</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
diff --git a/test/Analysis/array-struct.c b/test/Analysis/array-struct.c
index c22f979..28e09ad 100644
--- a/test/Analysis/array-struct.c
+++ b/test/Analysis/array-struct.c
@@ -183,3 +183,19 @@
   return ((char *)&(((struct s*)0)->data_array)) - ((char *)0); // no-warning
 }
 
+int testPointerArithmeticOnVoid(void *bytes) {
+  int p = 0;
+  if (&bytes[0] == &bytes[1])
+    return 6/p; // no-warning
+  return 0;
+}
+
+int testRValueArraySubscriptExpr(void *bytes) {
+  int *p = (int*)&bytes[0];
+  *p = 0;
+  if (*(int*)&bytes[0] == 0)
+    return 0;
+  return 5/(*p); // no-warning
+}
+
+
diff --git a/test/Analysis/conditional-path-notes.c b/test/Analysis/conditional-path-notes.c
index 2378497..9583a4e 100644
--- a/test/Analysis/conditional-path-notes.c
+++ b/test/Analysis/conditional-path-notes.c
@@ -313,6 +313,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;x&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testCondOp</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -456,6 +457,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testCondProblem</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -599,6 +601,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testLHSProblem</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -742,6 +745,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testRHSProblem</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -953,6 +957,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;x&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testBinaryCondOp</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1096,6 +1101,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testBinaryLHSProblem</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -1273,6 +1279,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testDiagnosableBranch</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1455,6 +1462,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testNonDiagnosableBranchLogical</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1569,6 +1577,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testNonDiagnosableBranchArithmetic</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
diff --git a/test/Analysis/crash-trace.c b/test/Analysis/crash-trace.c
index a2f318d..bac7447 100644
--- a/test/Analysis/crash-trace.c
+++ b/test/Analysis/crash-trace.c
@@ -1,6 +1,10 @@
 // RUN: not --crash %clang_cc1 -analyze -analyzer-checker=debug.ExprInspection %s 2>&1 | FileCheck %s
 // REQUIRES: crash-recovery
 
+// FIXME: CHECKs might be incompatible to win32.
+// Stack traces also require back traces.
+// REQUIRES: shell, backtrace
+
 void clang_analyzer_crash(void);
 
 void inlined() {
diff --git a/test/Analysis/cxx-for-range.cpp b/test/Analysis/cxx-for-range.cpp
index fe73e51..6278ba5 100644
--- a/test/Analysis/cxx-for-range.cpp
+++ b/test/Analysis/cxx-for-range.cpp
@@ -596,6 +596,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testLoop</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -821,6 +822,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>get</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1095,6 +1097,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testLoopOpaqueCollection</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -1238,6 +1241,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testLoopOpaqueCollection</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
@@ -1512,6 +1516,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testLoopOpaqueIterator</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -1655,6 +1660,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testLoopOpaqueIterator</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
diff --git a/test/Analysis/debug-CallGraph.c b/test/Analysis/debug-CallGraph.c
index 4523c78..64259e2 100644
--- a/test/Analysis/debug-CallGraph.c
+++ b/test/Analysis/debug-CallGraph.c
@@ -23,11 +23,22 @@
       foo(x, y);
   }();
 }
+void ccc();
+void ddd() { ccc(); }
+void ccc() {}
+
+void eee();
+void eee() {}
+void fff() { eee(); }
 
 // CHECK:--- Call graph Dump ---
-// CHECK: Function: < root > calls: mmm foo aaa < > bbb
-// CHECK: Function: bbb calls: < >
-// CHECK: Function: < > calls: foo
-// CHECK: Function: aaa calls: foo
-// CHECK: Function: foo calls: mmm
-// CHECK: Function: mmm calls:
+// CHECK-NEXT: {{Function: < root > calls: mmm foo aaa < > bbb ccc ddd eee fff $}}
+// CHECK-NEXT: {{Function: fff calls: eee $}}
+// CHECK-NEXT: {{Function: eee calls: $}}
+// CHECK-NEXT: {{Function: ddd calls: ccc $}}
+// CHECK-NEXT: {{Function: ccc calls: $}}
+// CHECK-NEXT: {{Function: bbb calls: < > $}}
+// CHECK-NEXT: {{Function: < > calls: foo $}}
+// CHECK-NEXT: {{Function: aaa calls: foo $}}
+// CHECK-NEXT: {{Function: foo calls: mmm $}}
+// CHECK-NEXT: {{Function: mmm calls: $}}
diff --git a/test/Analysis/diagnostics/deref-track-symbolic-region.c b/test/Analysis/diagnostics/deref-track-symbolic-region.c
index 36d56f1..47d4c60 100644
--- a/test/Analysis/diagnostics/deref-track-symbolic-region.c
+++ b/test/Analysis/diagnostics/deref-track-symbolic-region.c
@@ -305,6 +305,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;x&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
@@ -642,6 +643,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testTrackConstraintBRVisitorIsTrackingTurnedOn</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
diff --git a/test/Analysis/diagnostics/report-issues-within-main-file.cpp b/test/Analysis/diagnostics/report-issues-within-main-file.cpp
index ec8106f..e10c706 100644
--- a/test/Analysis/diagnostics/report-issues-within-main-file.cpp
+++ b/test/Analysis/diagnostics/report-issues-within-main-file.cpp
@@ -248,6 +248,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>cause_div_by_zero_in_header2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -511,6 +512,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>cause_div_by_zero_in_header3</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -542,7 +544,7 @@
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:         <dict>
 // CHECK-NEXT:          <key>line</key><integer>69</integer>
-// CHECK-NEXT:          <key>col</key><integer>18</integer>
+// CHECK-NEXT:          <key>col</key><integer>51</integer>
 // CHECK-NEXT:          <key>file</key><integer>0</integer>
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:        </array>
@@ -697,6 +699,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>cause_div_by_zero_in_header4</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -937,6 +940,7 @@
 // CHECK-NEXT:    <key>description</key><string>Memory allocated by &apos;new[]&apos; should be deallocated by &apos;delete[]&apos;, not &apos;delete&apos; (within a call to &apos;~auto_ptr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Bad deallocator</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.MismatchedDeallocator</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>mainPlusHeader</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1269,6 +1273,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero (within a call to &apos;cause_div_by_zero_in_header&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>auxInMain</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1489,6 +1494,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>causeDivByZeroInMain</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1743,6 +1749,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>causeDivByZeroInMain2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
diff --git a/test/Analysis/diagnostics/undef-value-caller.c b/test/Analysis/diagnostics/undef-value-caller.c
index da3a13c..c811017 100644
--- a/test/Analysis/diagnostics/undef-value-caller.c
+++ b/test/Analysis/diagnostics/undef-value-caller.c
@@ -146,6 +146,7 @@
 // CHECK-NEXT:    <key>description</key><string>Undefined or garbage value returned to caller</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Garbage return value</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.uninitialized.UndefReturn</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_calling_unimportant_callee</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
diff --git a/test/Analysis/diagnostics/undef-value-param.c b/test/Analysis/diagnostics/undef-value-param.c
index dec0a5a..f418b19 100644
--- a/test/Analysis/diagnostics/undef-value-param.c
+++ b/test/Analysis/diagnostics/undef-value-param.c
@@ -435,6 +435,7 @@
 // CHECK-NEXT:    <key>description</key><string>The left operand of &apos;+&apos; is a garbage value</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Result of operation is garbage or undefined</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.UndefinedBinaryOperatorResult</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>use</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -752,6 +753,7 @@
 // CHECK-NEXT:    <key>description</key><string>The right operand of &apos;*&apos; is a garbage value</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Result of operation is garbage or undefined</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.UndefinedBinaryOperatorResult</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testPassingParentRegionArray</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1166,6 +1168,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;f1&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testPassingParentRegionStruct</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
diff --git a/test/Analysis/diagnostics/undef-value-param.m b/test/Analysis/diagnostics/undef-value-param.m
index b0ce56c..5ca08a5 100644
--- a/test/Analysis/diagnostics/undef-value-param.m
+++ b/test/Analysis/diagnostics/undef-value-param.m
@@ -543,6 +543,7 @@
 // CHECK-NEXT:    <key>description</key><string>Null pointer argument in call to CFRelease</string>
 // CHECK-NEXT:    <key>category</key><string>API Misuse (Apple)</string>
 // CHECK-NEXT:    <key>type</key><string>null passed to CF memory management function</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.coreFoundation.CFRetainRelease</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -923,6 +924,7 @@
 // CHECK-NEXT:    <key>description</key><string>Function call argument is an uninitialized value</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Uninitialized argument value</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
diff --git a/test/Analysis/dtor.cpp b/test/Analysis/dtor.cpp
index 8d6e30a..bb1e625 100644
--- a/test/Analysis/dtor.cpp
+++ b/test/Analysis/dtor.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -analyze -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=destructors,cfg-temporary-dtors=true -Wno-null-dereference -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=destructors,cfg-temporary-dtors=true -Wno-null-dereference -Wno-inaccessible-base -verify %s
 
 void clang_analyzer_eval(bool);
 void clang_analyzer_checkInlined(bool);
diff --git a/test/Analysis/edges-new.mm b/test/Analysis/edges-new.mm
index 8019c15..2c39dfd 100644
--- a/test/Analysis/edges-new.mm
+++ b/test/Analysis/edges-new.mm
@@ -725,6 +725,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_init</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -902,6 +903,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_assign</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1142,6 +1144,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;q&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_assign_transitive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1319,6 +1322,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_cond</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1559,6 +1563,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_cond_transitive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1736,6 +1741,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_field</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -2073,6 +2079,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_assumptions</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -2342,6 +2349,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_cond_assign</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -2601,6 +2609,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;value&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar8331641</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -2778,6 +2787,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_objc_fast_enumeration</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -2824,6 +2834,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;x&apos; is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead increment</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_objc_fast_enumeration_2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -3030,6 +3041,7 @@
 // CHECK-NEXT:    <key>description</key><string>The left expression of the compound assignment is an uninitialized value. The computed value will also be garbage</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Assigned value is garbage or undefined</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.uninitialized.Assign</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_objc_fast_enumeration_2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -3464,6 +3476,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar12280665</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -3767,6 +3780,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>radar12322528_for</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -4036,6 +4050,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>radar12322528_while</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -4538,6 +4553,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>radar12322528_foo_2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
@@ -5035,6 +5051,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_diagnostics</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -5600,6 +5617,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_diagnostics_2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
@@ -6165,6 +6183,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_diagnostics_3</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>10</string>
@@ -6609,6 +6628,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_do_while</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>12</string>
@@ -6854,6 +6874,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_logical_and</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -7099,6 +7120,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_logical_or</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -7378,6 +7400,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_logical_or_call</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -7657,6 +7680,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_nested_logicals</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -8072,6 +8096,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_nested_logicals</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -8555,6 +8580,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_deeply_nested_logicals</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -8965,6 +8991,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_ternary</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -9239,6 +9266,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testUseless</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -9445,6 +9473,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testFoo</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -9617,6 +9646,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test1_IPA_X</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -10012,6 +10042,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_IPA_Y</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -10232,6 +10263,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>causeDivByZeroInMain</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -10375,6 +10407,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from ivar &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -10484,6 +10517,7 @@
 // CHECK-NEXT:    <key>description</key><string>Null pointer passed as an argument to a &apos;nonnull&apos; parameter</string>
 // CHECK-NEXT:    <key>category</key><string>API</string>
 // CHECK-NEXT:    <key>type</key><string>Argument with &apos;nonnull&apos; attribute passed null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NonNullParamChecker</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>RDar13295437</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -10695,6 +10729,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testCast</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -10872,6 +10907,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -10930,6 +10966,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;foo&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -11058,6 +11095,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;foo&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -11235,6 +11273,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
@@ -11679,6 +11718,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>20</string>
@@ -12089,6 +12129,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>26</string>
@@ -12562,6 +12603,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>34</string>
@@ -13816,6 +13858,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>62</string>
@@ -15133,6 +15176,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>67</string>
@@ -16547,6 +16591,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>74</string>
@@ -18058,6 +18103,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>variousLoops</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>83</string>
@@ -18341,6 +18387,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;buf&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>reallocDiagnostics</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -18580,6 +18627,7 @@
 // CHECK-NEXT:    <key>description</key><string>Memory allocated by &apos;new[]&apos; should be deallocated by &apos;delete[]&apos;, not &apos;delete&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Bad deallocator</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.MismatchedDeallocator</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>0</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
@@ -19292,6 +19340,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;foo&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>longLines</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -19435,6 +19484,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testMacroInFunctionDecl</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -19617,6 +19667,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
diff --git a/test/Analysis/free.c b/test/Analysis/free.c
index 1dfc108..6f33732 100644
--- a/test/Analysis/free.c
+++ b/test/Analysis/free.c
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 -analyze -analyzer-store=region -analyzer-checker=core,unix.Malloc -fblocks -verify %s
 // RUN: %clang_cc1 -analyze -analyzer-store=region -analyzer-checker=core,alpha.unix.MallocWithAnnotations -fblocks -verify %s
+typedef __typeof(sizeof(int)) size_t;
 void free(void *);
+void *alloca(size_t);
 
 void t1 () {
   int a[] = { 1 };
@@ -49,24 +51,29 @@
 }
 
 void t11 () {
-  char *p = (char*)__builtin_alloca(2);
+  char *p = (char*)alloca(2);
   free(p); // expected-warning {{Memory allocated by alloca() should not be deallocated}}
 }
 
 void t12 () {
+  char *p = (char*)__builtin_alloca(2);
+  free(p); // expected-warning {{Memory allocated by alloca() should not be deallocated}}
+}
+
+void t13 () {
   free(^{return;}); // expected-warning {{Argument to free() is a block, which is not memory allocated by malloc()}}
 }
 
-void t13 (char a) {
+void t14 (char a) {
   free(&a); // expected-warning {{Argument to free() is the address of the parameter 'a', which is not memory allocated by malloc()}}
 }
 
 static int someGlobal[2];
-void t14 () {
+void t15 () {
   free(someGlobal); // expected-warning {{Argument to free() is the address of the global variable 'someGlobal', which is not memory allocated by malloc()}}
 }
 
-void t15 (char **x, int offset) {
+void t16 (char **x, int offset) {
   // Unknown value
   free(x[offset]); // no-warning
 }
diff --git a/test/Analysis/inline-plist.c b/test/Analysis/inline-plist.c
index bcf15b3..8558e8f 100644
--- a/test/Analysis/inline-plist.c
+++ b/test/Analysis/inline-plist.c
@@ -289,6 +289,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>foo</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -509,6 +510,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>has_bug</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -860,6 +862,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>triggers_bug</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1080,6 +1083,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
 // CHECK-NEXT:    <key>line</key><integer>60</integer>
@@ -1452,6 +1456,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_block_ret</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -1701,6 +1706,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_block_blockvar</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -1950,6 +1956,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_block_arg</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
diff --git a/test/Analysis/inline-unique-reports.c b/test/Analysis/inline-unique-reports.c
index 9f33bd4..89cff09 100644
--- a/test/Analysis/inline-unique-reports.c
+++ b/test/Analysis/inline-unique-reports.c
@@ -291,6 +291,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>bug</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
diff --git a/test/Analysis/inlining/eager-reclamation-path-notes.c b/test/Analysis/inlining/eager-reclamation-path-notes.c
index d14aba3..f57a3bb 100644
--- a/test/Analysis/inlining/eager-reclamation-path-notes.c
+++ b/test/Analysis/inlining/eager-reclamation-path-notes.c
@@ -318,6 +318,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;ptr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>use</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -775,6 +776,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;ptr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>use2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
diff --git a/test/Analysis/inlining/eager-reclamation-path-notes.cpp b/test/Analysis/inlining/eager-reclamation-path-notes.cpp
index 672b3b8..b02e796 100644
--- a/test/Analysis/inlining/eager-reclamation-path-notes.cpp
+++ b/test/Analysis/inlining/eager-reclamation-path-notes.cpp
@@ -372,6 +372,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>memberCallBaseDisappears</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>19</string>
diff --git a/test/Analysis/inlining/path-notes.c b/test/Analysis/inlining/path-notes.c
index deb2efe..9b625c8 100644
--- a/test/Analysis/inlining/path-notes.c
+++ b/test/Analysis/inlining/path-notes.c
@@ -347,6 +347,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testZero</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -524,6 +525,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testCheck</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -764,6 +766,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testInitCheck</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -1004,6 +1007,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testStoreCheck</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -1316,6 +1320,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testReturnZero</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1628,6 +1633,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testReturnZero2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -2003,6 +2009,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testInitZero</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -2378,6 +2385,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testStoreZero</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -2796,6 +2804,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>usePointer</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3045,6 +3054,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testSetFieldToNull</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -3154,6 +3164,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -3331,6 +3342,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test4</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
diff --git a/test/Analysis/inlining/path-notes.cpp b/test/Analysis/inlining/path-notes.cpp
index 1e23074..30ce8c8 100644
--- a/test/Analysis/inlining/path-notes.cpp
+++ b/test/Analysis/inlining/path-notes.cpp
@@ -877,6 +877,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>C++ method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>use</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1165,6 +1166,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>C++ method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>method</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1414,6 +1416,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;globalPtr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
@@ -1661,6 +1664,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;globalPtr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
@@ -1942,6 +1946,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;globalPtr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
@@ -2257,6 +2262,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;globalPtr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>C++ method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>operator=</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -2608,6 +2614,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;globalPtr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>C++ method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>operator=</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -2895,6 +2902,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;globalPtr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
@@ -3142,6 +3150,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3488,6 +3497,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testRef</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3597,6 +3607,7 @@
 // CHECK-NEXT:    <key>description</key><string>Returning null reference</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Returning null reference</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.uninitialized.UndefReturn</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>returnNullReference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -3962,6 +3973,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;ptr&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
@@ -4166,6 +4178,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;y&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testNonPrintableAssignment</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -4275,6 +4288,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;x&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -4452,6 +4466,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>C++ method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testGetDerefExprOnMemberExprWithADot</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -4561,6 +4576,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of undefined pointer value</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of undefined pointer value</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testGetDerefExprOnMemberExprWithADot</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -4767,6 +4783,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testDeclRefExprToReferenceInGetDerefExpr</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -4987,6 +5004,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>generateNoteOnDefaultArgument</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -5221,6 +5239,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
diff --git a/test/Analysis/inlining/path-notes.m b/test/Analysis/inlining/path-notes.m
index 2304038..4a5d2ae 100644
--- a/test/Analysis/inlining/path-notes.m
+++ b/test/Analysis/inlining/path-notes.m
@@ -575,6 +575,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testReturnZeroIfNil</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -882,6 +883,7 @@
 // CHECK-NEXT:    <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testDispatchSyncInlining</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>14</string>
@@ -1131,6 +1133,7 @@
 // CHECK-NEXT:    <key>description</key><string>Variable &apos;x&apos; is uninitialized when captured by block</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>uninitialized variable captured by block</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.uninitialized.CapturedBlockVariable</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
 // CHECK-NEXT:    <key>line</key><integer>118</integer>
@@ -1445,6 +1448,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;x&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testNilReceiverHelper</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1622,6 +1626,7 @@
 // CHECK-NEXT:    <key>description</key><string>Array element cannot be nil</string>
 // CHECK-NEXT:    <key>category</key><string>API Misuse (Apple)</string>
 // CHECK-NEXT:    <key>type</key><string>nil argument</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.NilArg</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testCreateArrayLiteral</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -2017,6 +2022,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testAutoreleaseTakesEffectInDispatch</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
diff --git a/test/Analysis/malloc-plist.c b/test/Analysis/malloc-plist.c
index 0cbf972..4ac6cec 100644
--- a/test/Analysis/malloc-plist.c
+++ b/test/Analysis/malloc-plist.c
@@ -408,6 +408,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;p&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>diagnosticTest</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -570,6 +571,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;A&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>myArrayAllocation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -955,6 +957,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;buf&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>reallocDiagnostics</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1354,6 +1357,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;buf&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_wrapper</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1874,6 +1878,7 @@
 // CHECK-NEXT:    <key>description</key><string>Use of memory after it is freed</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Use-after-free</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_double_action_call</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -2433,6 +2438,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;buf&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>reallocIntra</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -2701,6 +2707,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;v&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>use_ret</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -2863,6 +2870,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;m&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>LeakedSymbol</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -3068,6 +3076,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>function_with_leak1</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3273,6 +3282,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>function_with_leak2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3575,6 +3585,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>function_with_leak3</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3877,6 +3888,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>function_with_leak4</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -4082,6 +4094,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>function_with_leak5</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -4287,6 +4300,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>function_with_leak6</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -4521,6 +4535,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential memory leak</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>use_function_with_leak7</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -4755,6 +4770,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential memory leak</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testOnlyRefferToVisibleVariables</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -5023,6 +5039,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential memory leak</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testMyMalloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
diff --git a/test/Analysis/method-call-path-notes.cpp b/test/Analysis/method-call-path-notes.cpp
index 20348d5..bb6964d 100644
--- a/test/Analysis/method-call-path-notes.cpp
+++ b/test/Analysis/method-call-path-notes.cpp
@@ -143,6 +143,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is uninitialized</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is uninitialized</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_ic</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -252,6 +253,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_ic_null</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -395,6 +397,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_ic_set_to_null</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -538,6 +541,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_ic_null</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -647,6 +651,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_ic_member_ptr</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -790,6 +795,7 @@
 // CHECK-NEXT:    <key>description</key><string>Called C++ object pointer is null</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Called C++ object pointer is null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.CallAndMessage</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_cast</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
diff --git a/test/Analysis/model-file.cpp b/test/Analysis/model-file.cpp
index 24d6e93..2ad84ea 100644
--- a/test/Analysis/model-file.cpp
+++ b/test/Analysis/model-file.cpp
@@ -275,6 +275,7 @@
 // CHECK-NEXT:   <key>description</key><string>Division by zero</string>
 // CHECK-NEXT:   <key>category</key><string>Logic error</string>
 // CHECK-NEXT:   <key>type</key><string>Division by zero</string>
+// CHECK-NEXT:   <key>check_name</key><string>core.DivideZero</string>
 // CHECK-NEXT:  <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:  <key>issue_context</key><string>main</string>
 // CHECK-NEXT:  <key>issue_hash</key><string>15</string>
diff --git a/test/Analysis/null-deref-path-notes.m b/test/Analysis/null-deref-path-notes.m
index 6057694..da49eaa 100644
--- a/test/Analysis/null-deref-path-notes.m
+++ b/test/Analysis/null-deref-path-notes.m
@@ -283,6 +283,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;x&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testNull</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -508,6 +509,7 @@
 // CHECK-NEXT:    <key>description</key><string>Access to instance variable &apos;uniqueID&apos; results in a dereference of a null pointer (loaded from variable &apos;self&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>initWithID:</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -782,6 +784,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>repeatedStores</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>11</string>
diff --git a/test/Analysis/objc-arc.m b/test/Analysis/objc-arc.m
index 92432b1..e4a4e46 100644
--- a/test/Analysis/objc-arc.m
+++ b/test/Analysis/objc-arc.m
@@ -366,6 +366,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_working</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -528,6 +529,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;date&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_cf_leak</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -586,6 +588,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;x&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar9424882</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -644,6 +647,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;obj1&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>from_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -702,6 +706,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;obj4&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>from_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -760,6 +765,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;obj5&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>from_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -818,6 +824,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;obj6&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>from_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -995,6 +1002,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;obj5&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>from_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -1123,6 +1131,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;obj6&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>from_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -1181,6 +1190,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;cf1&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>to_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1239,6 +1249,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;cf2&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>to_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1297,6 +1308,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;cf3&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>to_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1355,6 +1367,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;cf4&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>to_cf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1498,6 +1511,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;date&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_objc_unretainedObject</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1796,6 +1810,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_objc_arrays</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>24</string>
@@ -1965,6 +1980,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;o&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar11059275_positive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -2079,6 +2095,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar14061675</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
diff --git a/test/Analysis/objc-radar17039661.m b/test/Analysis/objc-radar17039661.m
index ec4f19d..fc55ab1 100644
--- a/test/Analysis/objc-radar17039661.m
+++ b/test/Analysis/objc-radar17039661.m
@@ -1,5 +1,6 @@
-// RUN: %clang_cc1 -analyze -analyzer-checker=core,osx.cocoa.RetainCount -verify -fblocks %s
-
+// RUN: %clang_cc1 -analyze -analyzer-checker=core,osx.cocoa.RetainCount -fblocks -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-checker=core,osx.cocoa.RetainCount -fblocks -analyzer-output=plist-multi-file -analyzer-config path-diagnostics-alternate=false %s -o %t
+// RUN: FileCheck --input-file=%t %s
 @class NSString;
 typedef long NSInteger;
 typedef unsigned char BOOL;
@@ -13,14 +14,13 @@
 @interface NSNumber : NSObject
 + (NSNumber *)numberWithInteger:(NSInteger)value __attribute__((availability(ios,introduced=2.0)));
 @end
-
 NSInteger *inoutIntegerValueGlobal;
 NSInteger *inoutIntegerValueGlobal2;
 NSString *traitNameGlobal;
 static BOOL cond;
 
 static inline void reallyPerformAction(void (^integerHandler)(NSInteger *inoutIntegerValue, NSString *traitName)) {
-  integerHandler(inoutIntegerValueGlobal, traitNameGlobal);
+  integerHandler(inoutIntegerValueGlobal, traitNameGlobal); // expected-warning {{Potential leak of an object}}
   integerHandler(inoutIntegerValueGlobal2,traitNameGlobal);
 }
 
@@ -47,7 +47,7 @@
 void runTest() {
   __attribute__((__blocks__(byref))) NSNumber *builtinResult = ((NSNumber *)0);
   BOOL wasBuiltinTrait = performAction(^(NSNumber *traitValue) {
-    builtinResult = [traitValue retain]; // expected-warning {{Potential leak of an object}}
+    builtinResult = [traitValue retain];
 
     return traitValue;
   });
@@ -58,3 +58,1176 @@
     return;
   }
 }
+
+// CHECK: <key>diagnostics</key>
+// CHECK: <array>
+// CHECK:  <dict>
+// CHECK:   <key>path</key>
+// CHECK:   <array>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>48</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>48</integer>
+// CHECK:           <key>col</key><integer>15</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>49</integer>
+// CHECK:           <key>col</key><integer>26</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>49</integer>
+// CHECK:           <key>col</key><integer>38</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>49</integer>
+// CHECK:      <key>col</key><integer>26</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>49</integer>
+// CHECK:         <key>col</key><integer>26</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>53</integer>
+// CHECK:         <key>col</key><integer>4</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>0</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Calling &apos;performAction&apos;</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Calling &apos;performAction&apos;</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>27</integer>
+// CHECK:      <key>col</key><integer>1</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>depth</key><integer>1</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Entered call from &apos;runTest&apos;</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Entered call from &apos;runTest&apos;</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>27</integer>
+// CHECK:           <key>col</key><integer>1</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>27</integer>
+// CHECK:           <key>col</key><integer>6</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>28</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>28</integer>
+// CHECK:           <key>col</key><integer>15</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>28</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>28</integer>
+// CHECK:           <key>col</key><integer>15</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>29</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>29</integer>
+// CHECK:           <key>col</key><integer>21</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>29</integer>
+// CHECK:      <key>col</key><integer>3</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>29</integer>
+// CHECK:         <key>col</key><integer>3</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>43</integer>
+// CHECK:         <key>col</key><integer>4</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>1</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Calling &apos;reallyPerformAction&apos;</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Calling &apos;reallyPerformAction&apos;</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>22</integer>
+// CHECK:      <key>col</key><integer>1</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>depth</key><integer>2</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Entered call from &apos;performAction&apos;</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Entered call from &apos;performAction&apos;</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>22</integer>
+// CHECK:           <key>col</key><integer>1</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>22</integer>
+// CHECK:           <key>col</key><integer>6</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>23</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>23</integer>
+// CHECK:           <key>col</key><integer>16</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>23</integer>
+// CHECK:      <key>col</key><integer>3</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>23</integer>
+// CHECK:         <key>col</key><integer>3</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>23</integer>
+// CHECK:         <key>col</key><integer>58</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>2</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>29</integer>
+// CHECK:      <key>col</key><integer>23</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Entered call from &apos;reallyPerformAction&apos;</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Entered call from &apos;reallyPerformAction&apos;</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>29</integer>
+// CHECK:           <key>col</key><integer>23</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>29</integer>
+// CHECK:           <key>col</key><integer>23</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>6</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>6</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>9</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>12</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>31</integer>
+// CHECK:      <key>col</key><integer>9</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>31</integer>
+// CHECK:         <key>col</key><integer>9</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>31</integer>
+// CHECK:         <key>col</key><integer>12</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Assuming &apos;cond&apos; is not equal to 0</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Assuming &apos;cond&apos; is not equal to 0</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>9</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>12</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>14</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>14</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>30</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>30</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>33</integer>
+// CHECK:      <key>col</key><integer>30</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>33</integer>
+// CHECK:         <key>col</key><integer>30</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>33</integer>
+// CHECK:         <key>col</key><integer>50</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>NSNumber boxed expression produces an object with a +0 retain count</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>NSNumber boxed expression produces an object with a +0 retain count</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>30</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>30</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>35</integer>
+// CHECK:           <key>col</key><integer>33</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>35</integer>
+// CHECK:           <key>col</key><integer>38</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>35</integer>
+// CHECK:      <key>col</key><integer>33</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>35</integer>
+// CHECK:         <key>col</key><integer>33</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>35</integer>
+// CHECK:         <key>col</key><integer>50</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>49</integer>
+// CHECK:      <key>col</key><integer>40</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>depth</key><integer>4</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Entered call</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Entered call</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>49</integer>
+// CHECK:           <key>col</key><integer>40</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>49</integer>
+// CHECK:           <key>col</key><integer>40</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>17</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>17</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>21</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>21</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>50</integer>
+// CHECK:      <key>col</key><integer>21</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>50</integer>
+// CHECK:         <key>col</key><integer>21</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>50</integer>
+// CHECK:         <key>col</key><integer>39</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>50</integer>
+// CHECK:         <key>col</key><integer>22</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>50</integer>
+// CHECK:         <key>col</key><integer>31</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>4</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>35</integer>
+// CHECK:      <key>col</key><integer>33</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>35</integer>
+// CHECK:         <key>col</key><integer>33</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>35</integer>
+// CHECK:         <key>col</key><integer>50</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Returning to caller</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Returning to caller</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>35</integer>
+// CHECK:           <key>col</key><integer>33</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>35</integer>
+// CHECK:           <key>col</key><integer>38</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>37</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>37</integer>
+// CHECK:           <key>col</key><integer>8</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>37</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>37</integer>
+// CHECK:           <key>col</key><integer>8</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>40</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>40</integer>
+// CHECK:           <key>col</key><integer>18</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>23</integer>
+// CHECK:      <key>col</key><integer>3</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>23</integer>
+// CHECK:         <key>col</key><integer>3</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>23</integer>
+// CHECK:         <key>col</key><integer>58</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>2</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Returning to caller</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Returning to caller</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>23</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>23</integer>
+// CHECK:           <key>col</key><integer>16</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>24</integer>
+// CHECK:           <key>col</key><integer>3</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>24</integer>
+// CHECK:           <key>col</key><integer>16</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>24</integer>
+// CHECK:      <key>col</key><integer>3</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>24</integer>
+// CHECK:         <key>col</key><integer>3</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>24</integer>
+// CHECK:         <key>col</key><integer>58</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>2</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>29</integer>
+// CHECK:      <key>col</key><integer>23</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Entered call from &apos;reallyPerformAction&apos;</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Entered call from &apos;reallyPerformAction&apos;</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>29</integer>
+// CHECK:           <key>col</key><integer>23</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>29</integer>
+// CHECK:           <key>col</key><integer>23</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>6</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>6</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>9</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>12</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>31</integer>
+// CHECK:      <key>col</key><integer>9</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>31</integer>
+// CHECK:         <key>col</key><integer>9</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>31</integer>
+// CHECK:         <key>col</key><integer>12</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Assuming &apos;cond&apos; is not equal to 0</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Assuming &apos;cond&apos; is not equal to 0</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>9</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>31</integer>
+// CHECK:           <key>col</key><integer>12</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>14</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>7</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>33</integer>
+// CHECK:           <key>col</key><integer>14</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>35</integer>
+// CHECK:           <key>col</key><integer>33</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>35</integer>
+// CHECK:           <key>col</key><integer>38</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>35</integer>
+// CHECK:      <key>col</key><integer>33</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>35</integer>
+// CHECK:         <key>col</key><integer>33</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>35</integer>
+// CHECK:         <key>col</key><integer>50</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>3</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Calling anonymous block</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>49</integer>
+// CHECK:      <key>col</key><integer>40</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>depth</key><integer>4</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Entered call</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Entered call</string>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>49</integer>
+// CHECK:           <key>col</key><integer>40</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>49</integer>
+// CHECK:           <key>col</key><integer>40</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>17</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>control</string>
+// CHECK:     <key>edges</key>
+// CHECK:      <array>
+// CHECK:       <dict>
+// CHECK:        <key>start</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>50</integer>
+// CHECK:           <key>col</key><integer>17</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:        <key>end</key>
+// CHECK:         <array>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>52</integer>
+// CHECK:           <key>col</key><integer>5</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:          <dict>
+// CHECK:           <key>line</key><integer>52</integer>
+// CHECK:           <key>col</key><integer>10</integer>
+// CHECK:           <key>file</key><integer>0</integer>
+// CHECK:          </dict>
+// CHECK:         </array>
+// CHECK:       </dict>
+// CHECK:      </array>
+// CHECK:    </dict>
+// CHECK:    <dict>
+// CHECK:     <key>kind</key><string>event</string>
+// CHECK:     <key>location</key>
+// CHECK:     <dict>
+// CHECK:      <key>line</key><integer>52</integer>
+// CHECK:      <key>col</key><integer>5</integer>
+// CHECK:      <key>file</key><integer>0</integer>
+// CHECK:     </dict>
+// CHECK:     <key>ranges</key>
+// CHECK:     <array>
+// CHECK:       <array>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>52</integer>
+// CHECK:         <key>col</key><integer>5</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:        <dict>
+// CHECK:         <key>line</key><integer>52</integer>
+// CHECK:         <key>col</key><integer>21</integer>
+// CHECK:         <key>file</key><integer>0</integer>
+// CHECK:        </dict>
+// CHECK:       </array>
+// CHECK:     </array>
+// CHECK:     <key>depth</key><integer>4</integer>
+// CHECK:     <key>extended_message</key>
+// CHECK:     <string>Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1</string>
+// CHECK:     <key>message</key>
+// CHECK:     <string>Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1</string>
+// CHECK:    </dict>
+// CHECK:   </array>
+// CHECK:   <key>description</key><string>Potential leak of an object</string>
+// CHECK:   <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
+// CHECK:   <key>type</key><string>Leak</string>
+// CHECK:  <key>location</key>
+// CHECK:  <dict>
+// CHECK:   <key>line</key><integer>52</integer>
+// CHECK:   <key>col</key><integer>5</integer>
+// CHECK:   <key>file</key><integer>0</integer>
+// CHECK:  </dict>
+// CHECK:  </dict>
+// CHECK: </array>
+// CHECK:</dict>
+// CHECK:</plist>
diff --git a/test/Analysis/plist-macros.cpp b/test/Analysis/plist-macros.cpp
index 0e8518a..64cef25 100644
--- a/test/Analysis/plist-macros.cpp
+++ b/test/Analysis/plist-macros.cpp
@@ -220,6 +220,7 @@
 // CHECK-NEXT:    <key>description</key><string>Memory allocated by malloc() should be deallocated by free(), not &apos;delete&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Bad deallocator</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.MismatchedDeallocator</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>noteOnMacro</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -314,6 +315,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of memory pointed to by &apos;x&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory Error</string>
 // CHECK-NEXT:    <key>type</key><string>Memory leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.Malloc</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>macroIsFirstInFunction</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -559,6 +561,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>macroInExpression</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -804,6 +807,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>macroInExpressionNoNote</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -903,7 +907,7 @@
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:         <dict>
 // CHECK-NEXT:          <key>line</key><integer>45</integer>
-// CHECK-NEXT:          <key>col</key><integer>18</integer>
+// CHECK-NEXT:          <key>col</key><integer>21</integer>
 // CHECK-NEXT:          <key>file</key><integer>0</integer>
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:        </array>
@@ -1015,6 +1019,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>macroWithArgInExpression</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1158,6 +1163,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>useMultiNoteMacroWithError</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1364,6 +1370,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>useMultiNote</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1395,7 +1402,7 @@
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:         <dict>
 // CHECK-NEXT:          <key>line</key><integer>82</integer>
-// CHECK-NEXT:          <key>col</key><integer>9</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
 // CHECK-NEXT:          <key>file</key><integer>0</integer>
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:        </array>
@@ -1424,7 +1431,7 @@
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:         <dict>
 // CHECK-NEXT:          <key>line</key><integer>82</integer>
-// CHECK-NEXT:          <key>col</key><integer>9</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
 // CHECK-NEXT:          <key>file</key><integer>0</integer>
 // CHECK-NEXT:         </dict>
 // CHECK-NEXT:        </array>
@@ -1584,6 +1591,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;a&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>null_deref</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
diff --git a/test/Analysis/plist-output-alternate.m b/test/Analysis/plist-output-alternate.m
index ea5ace6..45f0feb 100644
--- a/test/Analysis/plist-output-alternate.m
+++ b/test/Analysis/plist-output-alternate.m
@@ -158,6 +158,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_init</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -301,6 +302,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_assign</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -507,6 +509,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;q&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_assign_transitive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -684,6 +687,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_cond</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -890,6 +894,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_cond_transitive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1067,6 +1072,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_field</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1360,6 +1366,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;value&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar8331641</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
diff --git a/test/Analysis/plist-output.m b/test/Analysis/plist-output.m
index f2823a0..4b4b800 100644
--- a/test/Analysis/plist-output.m
+++ b/test/Analysis/plist-output.m
@@ -295,6 +295,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_init</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -438,6 +439,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_assign</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -644,6 +646,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;q&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_assign_transitive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -821,6 +824,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_cond</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1027,6 +1031,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_cond_transitive</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1204,6 +1209,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from field &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_null_field</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1507,6 +1513,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_assumptions</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -1776,6 +1783,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_cond_assign</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -1919,6 +1927,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1977,6 +1986,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;foo&apos; during its initialization is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead initialization</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -2139,6 +2149,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;foo&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -2447,6 +2458,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>rdar12280665</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -2750,6 +2762,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>radar12322528_for</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -3053,6 +3066,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>radar12322528_while</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -3429,6 +3443,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>radar12322528_foo_2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -3868,6 +3883,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_diagnostics</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -4341,6 +4357,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_diagnostics_2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -4814,6 +4831,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_diagnostics_3</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>7</string>
@@ -4860,6 +4878,7 @@
 // CHECK-NEXT:    <key>description</key><string>Value stored to &apos;x&apos; is never read</string>
 // CHECK-NEXT:    <key>category</key><string>Dead store</string>
 // CHECK-NEXT:    <key>type</key><string>Dead increment</string>
+// CHECK-NEXT:    <key>check_name</key><string>deadcode.DeadStores</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_fast_enumeration</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -5066,6 +5085,7 @@
 // CHECK-NEXT:    <key>description</key><string>The left expression of the compound assignment is an uninitialized value. The computed value will also be garbage</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Assigned value is garbage or undefined</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.uninitialized.Assign</string> 
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_loop_fast_enumeration</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -5175,6 +5195,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from ivar &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -5284,6 +5305,7 @@
 // CHECK-NEXT:    <key>description</key><string>Null pointer passed as an argument to a &apos;nonnull&apos; parameter</string>
 // CHECK-NEXT:    <key>category</key><string>API</string>
 // CHECK-NEXT:    <key>type</key><string>Argument with &apos;nonnull&apos; attribute passed null</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NonNullParamChecker</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>RDar13295437</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -5524,6 +5546,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testFoo</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
diff --git a/test/Analysis/properties.m b/test/Analysis/properties.m
index f5b5d92..ea8d195 100644
--- a/test/Analysis/properties.m
+++ b/test/Analysis/properties.m
@@ -233,7 +233,7 @@
   self->_name = 0;
 
   doSomethingWithName(other->_name);
-  [other.name release]; // expected-warning{{not owned}}
+  [other.name release]; // no-warning
 }
 
 - (void)deliberateReleaseFalseNegative {
@@ -254,7 +254,7 @@
 - (void)testRetainAndReleaseIVar {
   [self.name retain];
   [_name release];
-  [_name release]; // expected-warning{{not owned}}
+  [_name release];
 }
 
 @end
@@ -344,3 +344,190 @@
   clang_analyzer_eval(w.value == w.value); // expected-warning{{UNKNOWN}}
 }
 
+
+#if !__has_feature(objc_arc)
+// Test quite a few cases of retain/release issues.
+
+@interface RetainCountTesting
+@property (strong) id ownedProp;
+@property (unsafe_unretained) id unownedProp;
+@property (nonatomic, strong) id manualProp;
+@end
+
+@implementation RetainCountTesting {
+  id _ivarOnly;
+}
+
+- (id)manualProp {
+  return _manualProp;
+}
+
+- (void)testOverreleaseOwnedIvar {
+  [_ownedProp retain];
+  [_ownedProp release];
+  [_ownedProp release];
+  [_ownedProp release]; // expected-warning{{used after it is released}}
+}
+
+- (void)testOverreleaseUnownedIvar {
+  [_unownedProp retain];
+  [_unownedProp release];
+  [_unownedProp release]; // expected-warning{{not owned at this point by the caller}}
+}
+
+- (void)testOverreleaseIvarOnly {
+  [_ivarOnly retain];
+  [_ivarOnly release];
+  [_ivarOnly release];
+  [_ivarOnly release]; // expected-warning{{used after it is released}}
+}
+
+- (void)testOverreleaseOwnedIvarUse {
+  [_ownedProp retain];
+  [_ownedProp release];
+  [_ownedProp release];
+  [_ownedProp myMethod]; // expected-warning{{used after it is released}}
+}
+
+- (void)testOverreleaseIvarOnlyUse {
+  [_ivarOnly retain];
+  [_ivarOnly release];
+  [_ivarOnly release];
+  [_ivarOnly myMethod]; // expected-warning{{used after it is released}}
+}
+
+- (void)testOverreleaseOwnedIvarAutoreleaseOkay {
+  [_ownedProp retain];
+  [_ownedProp release];
+  [_ownedProp autorelease];
+} // no-warning
+
+- (void)testOverreleaseIvarOnlyAutoreleaseOkay {
+  [_ivarOnly retain];
+  [_ivarOnly release];
+  [_ivarOnly autorelease];
+} // no-warning
+
+- (void)testOverreleaseOwnedIvarAutorelease {
+  [_ownedProp retain];
+  [_ownedProp release];
+  [_ownedProp autorelease];
+  [_ownedProp autorelease];
+} // expected-warning{{Object autoreleased too many times}}
+
+- (void)testOverreleaseIvarOnlyAutorelease {
+  [_ivarOnly retain];
+  [_ivarOnly release];
+  [_ivarOnly autorelease];
+  [_ivarOnly autorelease];
+} // expected-warning{{Object autoreleased too many times}}
+
+- (void)testPropertyAccessThenReleaseOwned {
+  id owned = [self.ownedProp retain];
+  [owned release];
+  [_ownedProp release];
+  clang_analyzer_eval(owned == _ownedProp); // expected-warning{{TRUE}}
+}
+
+- (void)testPropertyAccessThenReleaseOwned2 {
+  id fromIvar = _ownedProp;
+  id owned = [self.ownedProp retain];
+  [owned release];
+  [fromIvar release];
+  clang_analyzer_eval(owned == fromIvar); // expected-warning{{TRUE}}
+}
+
+- (void)testPropertyAccessThenReleaseUnowned {
+  id unowned = [self.unownedProp retain];
+  [unowned release];
+  [_unownedProp release]; // expected-warning{{not owned}}
+}
+
+- (void)testPropertyAccessThenReleaseUnowned2 {
+  id fromIvar = _unownedProp;
+  id unowned = [self.unownedProp retain];
+  [unowned release];
+  clang_analyzer_eval(unowned == fromIvar); // expected-warning{{TRUE}}
+  [fromIvar release]; // expected-warning{{not owned}}
+}
+
+- (void)testPropertyAccessThenReleaseManual {
+  id prop = [self.manualProp retain];
+  [prop release];
+  [_manualProp release]; // no-warning
+}
+
+- (void)testPropertyAccessThenReleaseManual2 {
+  id fromIvar = _manualProp;
+  id prop = [self.manualProp retain];
+  [prop release];
+  clang_analyzer_eval(prop == fromIvar); // expected-warning{{TRUE}}
+  [fromIvar release]; // no-warning
+}
+
+- (id)getUnownedFromProperty {
+  [_ownedProp retain];
+  [_ownedProp autorelease];
+  return _ownedProp; // no-warning
+}
+
+- (id)transferUnownedFromProperty {
+  [_ownedProp retain];
+  [_ownedProp autorelease];
+  return [_ownedProp autorelease]; // no-warning
+}
+
+- (id)transferOwnedFromProperty __attribute__((ns_returns_retained)) {
+  [_ownedProp retain];
+  [_ownedProp autorelease];
+  return _ownedProp; // no-warning
+}
+
+- (void)testAssignOwned:(id)newValue {
+  _ownedProp = newValue;
+  [_ownedProp release]; // FIXME: no-warning{{not owned}}
+}
+
+- (void)testAssignUnowned:(id)newValue {
+  _unownedProp = newValue;
+  [_unownedProp release]; // FIXME: no-warning{{not owned}}
+}
+
+- (void)testAssignIvarOnly:(id)newValue {
+  _ivarOnly = newValue;
+  [_ivarOnly release]; // FIXME: no-warning{{not owned}}
+}
+
+- (void)testAssignOwnedOkay:(id)newValue {
+  _ownedProp = [newValue retain];
+  [_ownedProp release]; // no-warning
+}
+
+- (void)testAssignUnownedOkay:(id)newValue {
+  _unownedProp = [newValue retain];
+  [_unownedProp release]; // no-warning
+}
+
+- (void)testAssignIvarOnlyOkay:(id)newValue {
+  _ivarOnly = [newValue retain];
+  [_ivarOnly release]; // no-warning
+}
+
+// rdar://problem/19862648
+- (void)establishIvarIsNilDuringLoops {
+  extern id getRandomObject();
+
+  int i = 4; // Must be at least 4 to trigger the bug.
+  while (--i) {
+    id x = 0;
+    if (getRandomObject())
+      x = _ivarOnly;
+    if (!x)
+      x = getRandomObject();
+    [x myMethod];
+  }
+}
+
+@end
+#endif // non-ARC
+
diff --git a/test/Analysis/redefined_system.c b/test/Analysis/redefined_system.c
index ae5bf26..16f03ab 100644
--- a/test/Analysis/redefined_system.c
+++ b/test/Analysis/redefined_system.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -analyze -analyzer-checker=unix,core,alpha.security.taint -w -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-checker=osx,unix,core,alpha.security.taint -w -verify %s
 // expected-no-diagnostics
 
 // Make sure we don't crash when someone redefines a system function we reason about.
diff --git a/test/Analysis/retain-release-path-notes-gc.m b/test/Analysis/retain-release-path-notes-gc.m
index 40592f0..aa783b5 100644
--- a/test/Analysis/retain-release-path-notes-gc.m
+++ b/test/Analysis/retain-release-path-notes-gc.m
@@ -208,6 +208,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak (when using garbage collection) of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak of object when using garbage collection</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>creationViaCFCreate</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -651,6 +652,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak (when using garbage collection) of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak of object when using garbage collection</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>makeCollectable</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1019,6 +1021,7 @@
 // CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>retainReleaseIgnored</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>5</string>
@@ -1203,6 +1206,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak (when using garbage collection) of an object stored into &apos;object&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak of returned object when using garbage collection</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>getViolation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1387,6 +1391,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak (when using garbage collection) of an object stored into &apos;object&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak of returned object when using garbage collection</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>copyViolation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
diff --git a/test/Analysis/retain-release-path-notes.m b/test/Analysis/retain-release-path-notes.m
index 4b16c71..23935b9 100644
--- a/test/Analysis/retain-release-path-notes.m
+++ b/test/Analysis/retain-release-path-notes.m
@@ -263,6 +263,71 @@
   return; // expected-warning{{Object autoreleased too many times}} expected-note{{Object was autoreleased 2 times but the object has a +0 retain count}}
 }
 
+@interface PropertiesAndIvars : NSObject
+@property (strong) id ownedProp;
+@property (unsafe_unretained) id unownedProp;
+@property (nonatomic, strong) id manualProp;
+@end
+
+@interface NSObject (PropertiesAndIvarsHelper)
+- (void)myMethod;
+@end
+
+@implementation PropertiesAndIvars {
+  id _ivarOnly;
+}
+
+- (id)manualProp {
+  return _manualProp;
+}
+
+- (void)testOverreleaseUnownedIvar {
+  [_unownedProp retain]; // expected-note {{Object loaded from instance variable}}
+  // expected-note@-1 {{Reference count incremented. The object now has a +1 retain count}}
+  [_unownedProp release]; // expected-note {{Reference count decremented}}
+  [_unownedProp release]; // expected-note {{Incorrect decrement of the reference count of an object that is not owned at this point by the caller}}
+  // expected-warning@-1 {{not owned at this point by the caller}}
+}
+
+- (void)testOverreleaseOwnedIvarUse {
+  [_ownedProp retain]; // expected-note {{Object loaded from instance variable}}
+  // expected-note@-1 {{Reference count incremented. The object now has a +1 retain count}}
+  [_ownedProp release]; // expected-note {{Reference count decremented}}
+  [_ownedProp release]; // expected-note {{Strong instance variable relinquished. Object released}}
+  [_ownedProp myMethod]; // expected-note {{Reference-counted object is used after it is released}}
+  // expected-warning@-1 {{used after it is released}}
+}
+
+- (void)testOverreleaseIvarOnlyUse {
+  [_ivarOnly retain]; // expected-note {{Object loaded from instance variable}}
+  // expected-note@-1 {{Reference count incremented. The object now has a +1 retain count}}
+  [_ivarOnly release]; // expected-note {{Reference count decremented}}
+  [_ivarOnly release]; // expected-note {{Strong instance variable relinquished. Object released}}
+  [_ivarOnly myMethod]; // expected-note {{Reference-counted object is used after it is released}}
+  // expected-warning@-1 {{used after it is released}}
+}
+
+- (void)testOverreleaseOwnedIvarAutorelease {
+  [_ownedProp retain]; // expected-note {{Object loaded from instance variable}}
+  // expected-note@-1 {{Reference count incremented. The object now has a +1 retain count}}
+  [_ownedProp release]; // expected-note {{Reference count decremented}}
+  [_ownedProp autorelease]; // expected-note {{Object autoreleased}}
+  [_ownedProp autorelease]; // expected-note {{Object autoreleased}}
+  // expected-note@+1 {{Object was autoreleased 2 times but the object has a +0 retain count}}
+} // expected-warning{{Object autoreleased too many times}}
+
+- (void)testOverreleaseIvarOnlyAutorelease {
+  [_ivarOnly retain]; // expected-note {{Object loaded from instance variable}}
+  // expected-note@-1 {{Reference count incremented. The object now has a +1 retain count}}
+  [_ivarOnly release]; // expected-note {{Reference count decremented}}
+  [_ivarOnly autorelease]; // expected-note {{Object autoreleased}}
+  [_ivarOnly autorelease]; // expected-note {{Object autoreleased}}
+  // expected-note@+1 {{Object was autoreleased 2 times but the object has a +0 retain count}}
+} // expected-warning{{Object autoreleased too many times}}
+
+@end
+
+
 
 // CHECK:  <key>diagnostics</key>
 // CHECK-NEXT:  <array>
@@ -399,6 +464,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>creationViaAlloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -542,6 +608,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>creationViaCFCreate</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -910,6 +977,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>acquisitionViaMethod</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1128,6 +1196,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>acquisitionViaProperty</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1346,6 +1415,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>acquisitionViaCFFunction</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1564,6 +1634,7 @@
 // CHECK-NEXT:    <key>description</key><string>Reference-counted object is used after it is released</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Use-after-release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>explicitDealloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -1782,6 +1853,7 @@
 // CHECK-NEXT:    <key>description</key><string>Reference-counted object is used after it is released</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Use-after-release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>implicitDealloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -2075,6 +2147,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>overAutorelease</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -2293,6 +2366,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>autoreleaseUnowned</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -2586,6 +2660,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;leaked&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>makeCollectableIgnored</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -2770,6 +2845,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Method should return an owned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>CFCopyRuleViolation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -2954,6 +3030,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;object&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak of returned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>CFGetRuleViolation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3138,6 +3215,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Method should return an owned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>copyViolation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -3322,6 +3400,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Method should return an owned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>copyViolationIndexedSubscript</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -3506,6 +3585,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Method should return an owned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>copyViolationKeyedSubscript</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -3690,6 +3770,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object stored into &apos;result&apos;</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak of returned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>getViolation</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -3908,6 +3989,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object with a +0 retain count returned to caller where a +1 (owning) retain count is expected</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Method should return an owned object</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>copyAutorelease</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -4051,6 +4133,7 @@
 // CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testNumericLiteral</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -4194,6 +4277,7 @@
 // CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testBoxedInt</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -4337,6 +4421,7 @@
 // CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testBoxedString</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -4480,6 +4565,7 @@
 // CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testArray</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -4623,6 +4709,7 @@
 // CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>testDictionary</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -5003,6 +5090,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -5354,6 +5442,7 @@
 // CHECK-NEXT:    <key>description</key><string>Potential leak of an object</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Leak</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>8</string>
@@ -5647,6 +5736,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>CFOverAutorelease</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -5865,6 +5955,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>CFAutoreleaseUnowned</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>3</string>
@@ -6158,6 +6249,7 @@
 // CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
 // CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
 // CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>CFAutoreleaseUnownedMixed</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>4</string>
@@ -6168,4 +6260,1894 @@
 // CHECK-NEXT:    <key>file</key><integer>0</integer>
 // CHECK-NEXT:   </dict>
 // CHECK-NEXT:   </dict>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>path</key>
+// CHECK-NEXT:    <array>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>15</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>285</integer>
+// CHECK-NEXT:       <key>col</key><integer>4</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>285</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>285</integer>
+// CHECK-NEXT:          <key>col</key><integer>15</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>15</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>285</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>285</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>285</integer>
+// CHECK-NEXT:          <key>col</key><integer>23</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>285</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>285</integer>
+// CHECK-NEXT:          <key>col</key><integer>15</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>285</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>287</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>287</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>287</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>287</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>287</integer>
+// CHECK-NEXT:          <key>col</key><integer>24</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>287</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>287</integer>
+// CHECK-NEXT:          <key>col</key><integer>15</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>287</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>287</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>288</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>288</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>288</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>288</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>288</integer>
+// CHECK-NEXT:          <key>col</key><integer>15</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:    </array>
+// CHECK-NEXT:    <key>description</key><string>Incorrect decrement of the reference count of an object that is not owned at this point by the caller</string>
+// CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
+// CHECK-NEXT:    <key>type</key><string>Bad release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
+// CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT:   <key>issue_context</key><string>testOverreleaseUnownedIvar</string>
+// CHECK-NEXT:   <key>issue_hash</key><string>4</string>
+// CHECK-NEXT:   <key>location</key>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>line</key><integer>288</integer>
+// CHECK-NEXT:    <key>col</key><integer>3</integer>
+// CHECK-NEXT:    <key>file</key><integer>0</integer>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>path</key>
+// CHECK-NEXT:    <array>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>13</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>293</integer>
+// CHECK-NEXT:       <key>col</key><integer>4</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>293</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>293</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>13</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>293</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>293</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>293</integer>
+// CHECK-NEXT:          <key>col</key><integer>21</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>293</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>293</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>293</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>295</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>295</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>295</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>295</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>295</integer>
+// CHECK-NEXT:          <key>col</key><integer>22</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>295</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>295</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>295</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>295</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>296</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>296</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>296</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>296</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>296</integer>
+// CHECK-NEXT:          <key>col</key><integer>22</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>296</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>296</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Strong instance variable relinquished. Object released</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Strong instance variable relinquished. Object released</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>296</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>296</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>297</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>297</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>297</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>297</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>297</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference-counted object is used after it is released</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference-counted object is used after it is released</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:    </array>
+// CHECK-NEXT:    <key>description</key><string>Reference-counted object is used after it is released</string>
+// CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
+// CHECK-NEXT:    <key>type</key><string>Use-after-release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
+// CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT:   <key>issue_context</key><string>testOverreleaseOwnedIvarUse</string>
+// CHECK-NEXT:   <key>issue_hash</key><string>5</string>
+// CHECK-NEXT:   <key>location</key>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>line</key><integer>297</integer>
+// CHECK-NEXT:    <key>col</key><integer>3</integer>
+// CHECK-NEXT:    <key>file</key><integer>0</integer>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>path</key>
+// CHECK-NEXT:    <array>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>12</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>302</integer>
+// CHECK-NEXT:       <key>col</key><integer>4</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>302</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>302</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>12</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>302</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>302</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>302</integer>
+// CHECK-NEXT:          <key>col</key><integer>20</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>302</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>302</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>302</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>304</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>304</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>304</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>304</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>304</integer>
+// CHECK-NEXT:          <key>col</key><integer>21</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>304</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>304</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>304</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>304</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>305</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>305</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>305</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>305</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>305</integer>
+// CHECK-NEXT:          <key>col</key><integer>21</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>305</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>305</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Strong instance variable relinquished. Object released</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Strong instance variable relinquished. Object released</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>305</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>305</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>306</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>306</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>306</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>306</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>306</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference-counted object is used after it is released</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference-counted object is used after it is released</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:    </array>
+// CHECK-NEXT:    <key>description</key><string>Reference-counted object is used after it is released</string>
+// CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
+// CHECK-NEXT:    <key>type</key><string>Use-after-release</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
+// CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT:   <key>issue_context</key><string>testOverreleaseIvarOnlyUse</string>
+// CHECK-NEXT:   <key>issue_hash</key><string>5</string>
+// CHECK-NEXT:   <key>location</key>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>line</key><integer>306</integer>
+// CHECK-NEXT:    <key>col</key><integer>3</integer>
+// CHECK-NEXT:    <key>file</key><integer>0</integer>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>path</key>
+// CHECK-NEXT:    <array>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>13</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>311</integer>
+// CHECK-NEXT:       <key>col</key><integer>4</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>311</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>311</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>13</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>311</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>311</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>311</integer>
+// CHECK-NEXT:          <key>col</key><integer>21</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>311</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>311</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>311</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>313</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>313</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>313</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>313</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>313</integer>
+// CHECK-NEXT:          <key>col</key><integer>22</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>313</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>313</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>313</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>313</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>314</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>314</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>314</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>314</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>314</integer>
+// CHECK-NEXT:          <key>col</key><integer>26</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>314</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>314</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>314</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>314</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>315</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>315</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>315</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>315</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>315</integer>
+// CHECK-NEXT:          <key>col</key><integer>26</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>315</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>315</integer>
+// CHECK-NEXT:          <key>col</key><integer>13</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>315</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>315</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>317</integer>
+// CHECK-NEXT:            <key>col</key><integer>1</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>317</integer>
+// CHECK-NEXT:            <key>col</key><integer>1</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>317</integer>
+// CHECK-NEXT:       <key>col</key><integer>1</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object was autoreleased 2 times but the object has a +0 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object was autoreleased 2 times but the object has a +0 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:    </array>
+// CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
+// CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
+// CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT:   <key>issue_context</key><string>testOverreleaseOwnedIvarAutorelease</string>
+// CHECK-NEXT:   <key>issue_hash</key><string>7</string>
+// CHECK-NEXT:   <key>location</key>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>line</key><integer>317</integer>
+// CHECK-NEXT:    <key>col</key><integer>1</integer>
+// CHECK-NEXT:    <key>file</key><integer>0</integer>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>path</key>
+// CHECK-NEXT:    <array>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>12</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>320</integer>
+// CHECK-NEXT:       <key>col</key><integer>4</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>320</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>320</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object loaded from instance variable</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>4</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>12</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>320</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>320</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>320</integer>
+// CHECK-NEXT:          <key>col</key><integer>20</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>320</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>320</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count incremented. The object now has a +1 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>320</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>322</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>322</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>322</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>322</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>322</integer>
+// CHECK-NEXT:          <key>col</key><integer>21</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>322</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>322</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Reference count decremented</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>322</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>322</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>323</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>323</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>323</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>323</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>323</integer>
+// CHECK-NEXT:          <key>col</key><integer>25</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>323</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>323</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>323</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>323</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>324</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>324</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>324</integer>
+// CHECK-NEXT:       <key>col</key><integer>3</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>ranges</key>
+// CHECK-NEXT:      <array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>324</integer>
+// CHECK-NEXT:          <key>col</key><integer>3</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>324</integer>
+// CHECK-NEXT:          <key>col</key><integer>25</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:        <array>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>324</integer>
+// CHECK-NEXT:          <key>col</key><integer>4</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:         <dict>
+// CHECK-NEXT:          <key>line</key><integer>324</integer>
+// CHECK-NEXT:          <key>col</key><integer>12</integer>
+// CHECK-NEXT:          <key>file</key><integer>0</integer>
+// CHECK-NEXT:         </dict>
+// CHECK-NEXT:        </array>
+// CHECK-NEXT:      </array>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object autoreleased</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>control</string>
+// CHECK-NEXT:      <key>edges</key>
+// CHECK-NEXT:       <array>
+// CHECK-NEXT:        <dict>
+// CHECK-NEXT:         <key>start</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>324</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>324</integer>
+// CHECK-NEXT:            <key>col</key><integer>3</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:         <key>end</key>
+// CHECK-NEXT:          <array>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>326</integer>
+// CHECK-NEXT:            <key>col</key><integer>1</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:           <dict>
+// CHECK-NEXT:            <key>line</key><integer>326</integer>
+// CHECK-NEXT:            <key>col</key><integer>1</integer>
+// CHECK-NEXT:            <key>file</key><integer>0</integer>
+// CHECK-NEXT:           </dict>
+// CHECK-NEXT:          </array>
+// CHECK-NEXT:        </dict>
+// CHECK-NEXT:       </array>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:     <dict>
+// CHECK-NEXT:      <key>kind</key><string>event</string>
+// CHECK-NEXT:      <key>location</key>
+// CHECK-NEXT:      <dict>
+// CHECK-NEXT:       <key>line</key><integer>326</integer>
+// CHECK-NEXT:       <key>col</key><integer>1</integer>
+// CHECK-NEXT:       <key>file</key><integer>0</integer>
+// CHECK-NEXT:      </dict>
+// CHECK-NEXT:      <key>depth</key><integer>0</integer>
+// CHECK-NEXT:      <key>extended_message</key>
+// CHECK-NEXT:      <string>Object was autoreleased 2 times but the object has a +0 retain count</string>
+// CHECK-NEXT:      <key>message</key>
+// CHECK-NEXT:      <string>Object was autoreleased 2 times but the object has a +0 retain count</string>
+// CHECK-NEXT:     </dict>
+// CHECK-NEXT:    </array>
+// CHECK-NEXT:    <key>description</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>category</key><string>Memory (Core Foundation/Objective-C)</string>
+// CHECK-NEXT:    <key>type</key><string>Object autoreleased too many times</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.cocoa.RetainCount</string>
+// CHECK-NEXT:   <key>issue_context_kind</key><string>Objective-C method</string>
+// CHECK-NEXT:   <key>issue_context</key><string>testOverreleaseIvarOnlyAutorelease</string>
+// CHECK-NEXT:   <key>issue_hash</key><string>7</string>
+// CHECK-NEXT:   <key>location</key>
+// CHECK-NEXT:   <dict>
+// CHECK-NEXT:    <key>line</key><integer>326</integer>
+// CHECK-NEXT:    <key>col</key><integer>1</integer>
+// CHECK-NEXT:    <key>file</key><integer>0</integer>
+// CHECK-NEXT:   </dict>
+// CHECK-NEXT:   </dict>
 // CHECK-NEXT:  </array>
diff --git a/test/Analysis/stack-addr-ps.c b/test/Analysis/stack-addr-ps.c
index a443a32..d668f8f 100644
--- a/test/Analysis/stack-addr-ps.c
+++ b/test/Analysis/stack-addr-ps.c
@@ -90,3 +90,10 @@
   return b; // no-warning
 }
 
+void testRegister(register const char *reg) {
+    if (reg) (void)reg[0];
+}
+void callTestRegister() {
+    char buf[20];
+    testRegister(buf); // no-warning
+}
diff --git a/test/Analysis/unix-fns.c b/test/Analysis/unix-fns.c
index dad03fa..d591e6b 100644
--- a/test/Analysis/unix-fns.c
+++ b/test/Analysis/unix-fns.c
@@ -406,6 +406,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;open&apos; requires a third argument when the &apos;O_CREAT&apos; flag is set</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Improper use of &apos;open&apos;</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_open</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>6</string>
@@ -554,6 +555,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;dispatch_once&apos; uses the local variable &apos;pred&apos; for the predicate value.  Using such transient memory for the predicate is potentially dangerous.  Perhaps you intended to declare the variable as &apos;static&apos;?</string>
 // CHECK-NEXT:    <key>category</key><string>API Misuse (Apple)</string>
 // CHECK-NEXT:    <key>type</key><string>Improper use of &apos;dispatch_once&apos;</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_dispatch_once</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -634,6 +636,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;pthread_once&apos; uses the local variable &apos;pred&apos; for the &quot;control&quot; value.  Using such transient memory for the control value is potentially dangerous.  Perhaps you intended to declare the variable as &apos;static&apos;?</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Improper use of &apos;pthread_once&apos;</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_pthread_once</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -714,6 +717,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;malloc&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>pr2899</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -794,6 +798,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;calloc&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_calloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -874,6 +879,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;calloc&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_calloc2</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -954,6 +960,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;realloc&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_realloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1034,6 +1041,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;reallocf&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_reallocf</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1114,6 +1122,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;alloca&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_alloca</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1194,6 +1203,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;alloca&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_builtin_alloca</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1274,6 +1284,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;valloc&apos; has an allocation size of 0 bytes</string>
 // CHECK-NEXT:    <key>category</key><string>Unix API</string>
 // CHECK-NEXT:    <key>type</key><string>Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)</string>
+// CHECK-NEXT:    <key>check_name</key><string>unix.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_valloc</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>1</string>
@@ -1354,6 +1365,7 @@
 // CHECK-NEXT:    <key>description</key><string>Call to &apos;dispatch_once&apos; uses the local variable &apos;pred&apos; for the predicate value.  Using such transient memory for the predicate is potentially dangerous.  Perhaps you intended to declare the variable as &apos;static&apos;?</string>
 // CHECK-NEXT:    <key>category</key><string>API Misuse (Apple)</string>
 // CHECK-NEXT:    <key>type</key><string>Improper use of &apos;dispatch_once&apos;</string>
+// CHECK-NEXT:    <key>check_name</key><string>osx.API</string>
 // CHECK-NEXT:   <key>issue_context_kind</key><string>function</string>
 // CHECK-NEXT:   <key>issue_context</key><string>test_dispatch_once_in_macro</string>
 // CHECK-NEXT:   <key>issue_hash</key><string>2</string>
@@ -1763,6 +1775,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
 // CHECK-NEXT:    <key>line</key><integer>192</integer>
@@ -2149,6 +2162,7 @@
 // CHECK-NEXT:    <key>description</key><string>Dereference of null pointer (loaded from variable &apos;p&apos;)</string>
 // CHECK-NEXT:    <key>category</key><string>Logic error</string>
 // CHECK-NEXT:    <key>type</key><string>Dereference of null pointer</string>
+// CHECK-NEXT:    <key>check_name</key><string>core.NullDereference</string>
 // CHECK-NEXT:   <key>location</key>
 // CHECK-NEXT:   <dict>
 // CHECK-NEXT:    <key>line</key><integer>202</integer>
diff --git a/test/CXX/basic/basic.lookup/basic.lookup.qual/class.qual/p2.cpp b/test/CXX/basic/basic.lookup/basic.lookup.qual/class.qual/p2.cpp
index b9e8398..d1562d4 100644
--- a/test/CXX/basic/basic.lookup/basic.lookup.qual/class.qual/p2.cpp
+++ b/test/CXX/basic/basic.lookup/basic.lookup.qual/class.qual/p2.cpp
@@ -108,7 +108,7 @@
   // FIXME: Consider reusing the same diagnostic between dependent and non-dependent contexts
   typedef int I;
   struct UsingInt {
-    using I::I; // expected-error {{'I' (aka 'int') is not a class, namespace, or scoped enumeration}}
+    using I::I; // expected-error {{'I' (aka 'int') is not a class, namespace, or enumeration}}
   };
   template<typename T> struct UsingIntTemplate {
     using T::T; // expected-error {{type 'int' cannot be used prior to '::' because it has no members}}
diff --git a/test/CXX/basic/basic.types/p10.cpp b/test/CXX/basic/basic.types/p10.cpp
index 9d99a77..7b1af00 100644
--- a/test/CXX/basic/basic.types/p10.cpp
+++ b/test/CXX/basic/basic.types/p10.cpp
@@ -38,15 +38,14 @@
 
 //  - it has a trivial destructor
 struct UserProvDtor {
-  constexpr int f() const; // expected-error {{non-literal type 'UserProvDtor' cannot have constexpr members}}
   ~UserProvDtor(); // expected-note {{has a user-provided destructor}}
 };
-
+constexpr int f(UserProvDtor) { return 0; } // expected-error {{'UserProvDtor' is not a literal type}}
 struct NonTrivDtor {
   constexpr NonTrivDtor();
-  constexpr int f() const; // expected-error {{non-literal type 'NonTrivDtor' cannot have constexpr members}}
   virtual ~NonTrivDtor() = default; // expected-note {{has a non-trivial destructor}} expected-note {{because it is virtual}}
 };
+constexpr int f(NonTrivDtor) { return 0; } // expected-error {{'NonTrivDtor' is not a literal type}}
 struct NonTrivDtorBase {
   ~NonTrivDtorBase();
 };
@@ -77,12 +76,12 @@
 };
 struct CopyCtorOnly { // expected-note {{'CopyCtorOnly' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors}}
   constexpr CopyCtorOnly(CopyCtorOnly&);
-  constexpr int f() const; // expected-error {{non-literal type 'CopyCtorOnly' cannot have constexpr members}}
 };
+constexpr int f(CopyCtorOnly) { return 0; } // expected-error {{'CopyCtorOnly' is not a literal type}}
 struct MoveCtorOnly { // expected-note {{no constexpr constructors other than copy or move constructors}}
   constexpr MoveCtorOnly(MoveCtorOnly&&);
-  constexpr int f() const; // expected-error {{non-literal type 'MoveCtorOnly' cannot have constexpr members}}
 };
+constexpr int f(MoveCtorOnly) { return 0; } // expected-error {{'MoveCtorOnly' is not a literal type}}
 template<typename T>
 struct CtorArg {
   constexpr CtorArg(T);
@@ -110,8 +109,8 @@
 struct NonLitBase :
   S { // expected-note {{base class 'S' of non-literal type}}
   constexpr NonLitBase();
-  constexpr int f() const { return 0; } // expected-error {{non-literal type 'NonLitBase' cannot have constexpr members}}
 };
+constexpr int f(NonLitBase) { return 0; } // expected-error {{'NonLitBase' is not a literal type}}
 struct LitMemBase : Agg {
   Agg agg;
 };
diff --git a/test/CXX/class.access/class.friend/p11.cpp b/test/CXX/class.access/class.friend/p11.cpp
index ba44a0d..a5107fd 100644
--- a/test/CXX/class.access/class.friend/p11.cpp
+++ b/test/CXX/class.access/class.friend/p11.cpp
@@ -24,6 +24,8 @@
   void foo() { // expected-note {{'::test2::foo' declared here}}
     struct S1 {
       friend void foo(); // expected-error {{no matching function 'foo' found in local scope; did you mean '::test2::foo'?}}
+      // expected-note@-1{{'::test2::foo' declared here}}
+      // TODO: the above note should go on line 24
     };
 
     void foo(); // expected-note {{local declaration nearly matches}}
@@ -40,17 +42,19 @@
     {
       int foo;
       struct S3 {
-        friend void foo(); // expected-error {{no matching function found in local scope}}
+        friend void foo(); // expected-error {{no matching function 'foo' found in local scope; did you mean '::test2::foo'?}}
       };
     }
 
     struct S4 {
       friend void bar(); // expected-error {{no matching function 'bar' found in local scope; did you mean '::test2::bar'?}}
+      // expected-note@-1 2 {{'::test2::bar' declared here}}
+      // TODO: the above two notes should go on line 22
     };
 
     { void bar(); }
     struct S5 {
-      friend void bar(); // expected-error {{no matching function found in local scope}}
+      friend void bar(); // expected-error {{no matching function 'bar' found in local scope; did you mean '::test2::bar'?}}
     };
 
     {
@@ -85,7 +89,7 @@
       void quux() {}
       void foo() {
         struct Inner1 {
-          friend void bar(); // expected-error {{no matching function found in local scope}}
+          friend void bar(); // expected-error {{no matching function 'bar' found in local scope; did you mean '::test2::bar'?}}
           friend void quux(); // expected-error {{no matching function found in local scope}}
         };
 
diff --git a/test/CXX/class.derived/class.virtual/p2.cpp b/test/CXX/class.derived/class.virtual/p2.cpp
index 64d93c8..9e8d243 100644
--- a/test/CXX/class.derived/class.virtual/p2.cpp
+++ b/test/CXX/class.derived/class.virtual/p2.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-inaccessible-base %s
 struct A {
   virtual void f() = 0; // expected-note 2{{overridden virtual function}}
 };
diff --git a/test/CXX/class/class.friend/p1.cpp b/test/CXX/class/class.friend/p1.cpp
index 07b3a10..96701b3 100644
--- a/test/CXX/class/class.friend/p1.cpp
+++ b/test/CXX/class/class.friend/p1.cpp
@@ -66,6 +66,10 @@
   class facet;
   friend class facet;  // should not assert
   class facet {};
+
+  friend int Unknown::thing(); // expected-error {{use of undeclared identifier}}
+  friend int friendfunc(), Unknown::thing(); // expected-error {{use of undeclared identifier}}
+  friend int friendfunc(), Unknown::thing() : 4; // expected-error {{use of undeclared identifier}}
 };
 
 A::UndeclaredSoFar y; // expected-error {{no type named 'UndeclaredSoFar' in 'A'}}
diff --git a/test/CXX/conv/conv.mem/p4.cpp b/test/CXX/conv/conv.mem/p4.cpp
index e0748d8..1618ae1 100644
--- a/test/CXX/conv/conv.mem/p4.cpp
+++ b/test/CXX/conv/conv.mem/p4.cpp
@@ -47,7 +47,7 @@
 // Can't be virtual even if there's a non-virtual path.
 namespace test4 {
   struct A : Base {};
-  struct Derived : Base, virtual A {};
+  struct Derived : Base, virtual A {}; // expected-warning  {{direct base 'Base' is inaccessible due to ambiguity:\n    struct test4::Derived -> struct Base\n    struct test4::Derived -> struct test4::A -> struct Base}}
   void test() {
     int (Derived::*d) = data_ptr; // expected-error {{ambiguous conversion from pointer to member of base class 'Base' to pointer to member of derived class 'test4::Derived':}}
     int (Derived::*m)() = method_ptr; // expected-error {{ambiguous conversion from pointer to member of base class 'Base' to pointer to member of derived class 'test4::Derived':}}
diff --git a/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p8-cxx0x.cpp b/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p8-cxx0x.cpp
index 4f89dcf..ebe5388 100644
--- a/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p8-cxx0x.cpp
+++ b/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p8-cxx0x.cpp
@@ -17,6 +17,11 @@
   using X::s; // expected-error{{using declaration cannot refer to class member}}
 }
 
+template <typename T>
+struct PR21933 : T {
+  static void StaticFun() { using T::member; } // expected-error{{using declaration cannot refer to class member}}
+};
+
 struct S {
   static int n;
   struct Q {};
diff --git a/test/CXX/dcl.dcl/dcl.attr/dcl.align/p5.cpp b/test/CXX/dcl.dcl/dcl.attr/dcl.align/p5.cpp
index 3c250f9..e713d72 100644
--- a/test/CXX/dcl.dcl/dcl.attr/dcl.align/p5.cpp
+++ b/test/CXX/dcl.dcl/dcl.attr/dcl.align/p5.cpp
@@ -15,6 +15,12 @@
 enum alignas(1) E2 : char {}; // ok
 enum alignas(4) E3 { e3 = 0 }; // ok
 enum alignas(4) E4 { e4 = 1ull << 33 }; // expected-error {{requested alignment is less than minimum alignment of 8 for type 'E4'}}
+enum alignas(8) E5 {};
+static_assert(alignof(E5) == 8, "");
+
+typedef __attribute__((aligned(16))) int IntAlign16;
+enum E6 : IntAlign16 {};
+static_assert(alignof(E6) == 4, "");
 
 struct S1 {
   alignas(8) int n;
diff --git a/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp b/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
index 448351b..1e3734e 100644
--- a/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
+++ b/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
@@ -27,9 +27,9 @@
 
 // The definition of a constexpr function shall satisfy the following
 // constraints:
-struct T : SS, NonLiteral { // expected-note {{base class 'NonLiteral' of non-literal type}}
+struct T : SS, NonLiteral {
   constexpr T();
-  constexpr int f() const; // expected-error {{non-literal type 'T' cannot have constexpr members}}
+  constexpr int f() const;
 
   //  - it shall not be virtual;
   virtual constexpr int ExplicitlyVirtual() const { return 0; } // expected-error {{virtual function cannot be constexpr}}
diff --git a/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p8.cpp b/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p8.cpp
index 21e4a23..428fd50 100644
--- a/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p8.cpp
+++ b/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p8.cpp
@@ -36,10 +36,10 @@
 
 namespace std_example {
 
-  class debug_flag { // expected-note {{not an aggregate and has no constexpr constructors}}
+  class debug_flag {
   public:
     explicit debug_flag(bool);
-    constexpr bool is_on() const; // expected-error {{non-literal type 'std_example::debug_flag' cannot have constexpr members}}
+    constexpr bool is_on() const; // ok (dr1684)
   private:
     bool flag;
   };
diff --git a/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp b/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp
index 42dee92..48c5b23 100644
--- a/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp
+++ b/test/CXX/dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp
@@ -57,6 +57,9 @@
 
   Agg<char> ce1 = { Convert<float>(1.0) }; // expected-error {{type 'float' cannot be narrowed to 'char'}} expected-note {{silence}}
   Agg<char> ce2 = { ConvertVar<double>() }; // expected-error {{type 'double' cannot be narrowed to 'char'}} expected-note {{silence}}
+
+  bool b{1.0}; // expected-error {{type 'double' cannot be narrowed to 'bool'}} expected-note {{silence}}
+  Agg<bool> ab = {0.0}; // expected-error {{type 'double' cannot be narrowed to 'bool'}} expected-note {{silence}}
 }
 
 // * from long double to double or float, or from double to float, except where
diff --git a/test/CXX/dcl.decl/dcl.meaning/dcl.fct.default/p4.cpp b/test/CXX/dcl.decl/dcl.meaning/dcl.fct.default/p4.cpp
index f3dec52..a5ac85c 100644
--- a/test/CXX/dcl.decl/dcl.meaning/dcl.fct.default/p4.cpp
+++ b/test/CXX/dcl.decl/dcl.meaning/dcl.fct.default/p4.cpp
@@ -6,6 +6,7 @@
 void f0(int i, int j, int k);
 void f0(int i = 1, // expected-note{{previous definition}}
         int j, int k);
+void f0(int i, int j, int k);   // want 2 decls before next default arg
 void f0(int i, int j, int k);
 
 namespace N0 {
@@ -53,3 +54,22 @@
     f2(6); // okay
   }
 }
+
+
+namespace PR18432 {
+
+struct A {
+  struct B {
+    static void Foo (int = 0);
+  };
+  
+  // should not hide default args
+  friend void B::Foo (int);
+};
+
+void Test ()
+{
+  A::B::Foo ();
+}
+
+} // namespace
diff --git a/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp b/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp
index 93c246b..de1c5a7 100644
--- a/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp
+++ b/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp
@@ -68,6 +68,10 @@
 void di(int ... x[]); // expected-error{{type 'int []' of function parameter pack does not contain any unexpanded parameter packs}}
 }
 
+void f5a(auto fp(int)->unk ...) {} // expected-error{{unknown type name 'unk'}}
+void f5b(auto fp(int)->auto ...) {} // expected-error{{'auto' not allowed in function return type}}
+void f5c(auto fp()->...) {} // expected-error{{expected a type}}
+
 // FIXME: Expand for function and member pointer types.
 
 
diff --git a/test/CXX/dcl.decl/dcl.meaning/p1.cpp b/test/CXX/dcl.decl/dcl.meaning/p1.cpp
index 5747380..cefee7b 100644
--- a/test/CXX/dcl.decl/dcl.meaning/p1.cpp
+++ b/test/CXX/dcl.decl/dcl.meaning/p1.cpp
@@ -27,6 +27,7 @@
   struct X;
   template<typename T> struct Y;
   template<typename T> void wibble(T);
+  struct Z;
 }
 namespace NS {
   // Under DR482, these are all valid, except for forward-declaring a struct
@@ -43,3 +44,6 @@
   template<typename T> struct NS::Y { }; // expected-warning{{extra qualification on member 'Y'}}
   template<typename T> void NS::wibble(T) { } // expected-warning{{extra qualification on member 'wibble'}}
 }
+
+struct ::{} a; // expected-error{{expected identifier}}
+struct NS::Z:: {} b; // expected-error{{expected identifier}}
diff --git a/test/CXX/drs/dr0xx.cpp b/test/CXX/drs/dr0xx.cpp
index 011b420..8a4334f 100644
--- a/test/CXX/drs/dr0xx.cpp
+++ b/test/CXX/drs/dr0xx.cpp
@@ -425,7 +425,7 @@
       using V::z;
       float &z(float);
     };
-    struct C : A, B, virtual V {} c;
+    struct C : A, B, virtual V {} c; // expected-warning {{direct base 'dr39::example2::A' is inaccessible due to ambiguity:\n    struct dr39::example2::C -> struct dr39::example2::A\n    struct dr39::example2::C -> struct dr39::example2::B -> struct dr39::example2::A}}
     int &x = c.x(0); // expected-error {{found in multiple base classes}}
     // FIXME: This is valid, because we find the same static data member either way.
     int &y = c.y(0); // expected-error {{found in multiple base classes}}
@@ -521,17 +521,28 @@
 }
 
 namespace dr49 { // dr49: yes
-  template<int*> struct A {}; // expected-note {{here}}
+  template<int*> struct A {}; // expected-note 0-2{{here}}
   int k;
 #if __has_feature(cxx_constexpr)
   constexpr
 #endif
-  int *const p = &k;
+  int *const p = &k; // expected-note 0-2{{here}}
   A<&k> a;
-  A<p> b; // expected-error {{must have its address taken}}
+  A<p> b;
+#if __cplusplus <= 201402L
+  // expected-error@-2 {{must have its address taken}}
+#endif
 #if __cplusplus < 201103L
-  // expected-error@-2 {{internal linkage}}
-  // expected-note@-5 {{here}}
+  // expected-error@-5 {{internal linkage}}
+#endif
+  int *q = &k;
+  A<q> c;
+#if __cplusplus < 201103L
+  // expected-error@-2 {{must have its address taken}}
+#else
+  // expected-error@-4 {{constant expression}}
+  // expected-note@-5 {{read of non-constexpr}}
+  // expected-note@-7 {{declared here}}
 #endif
 }
 
@@ -995,6 +1006,10 @@
     g(q); // expected-error {{is not superset}}
   }
 
+  // Prior to C++17, this is OK because the exception specification is not
+  // considered in this context. In C++17, we *do* perform an implicit
+  // conversion (which performs initialization), but we convert to the type of
+  // the template parameter, which does not include the exception specification.
   template<void() throw()> struct X {};
   X<&f> xp; // ok
 }
diff --git a/test/CXX/drs/dr10xx.cpp b/test/CXX/drs/dr10xx.cpp
index 733621d..a1d7ef6 100644
--- a/test/CXX/drs/dr10xx.cpp
+++ b/test/CXX/drs/dr10xx.cpp
@@ -14,6 +14,24 @@
   };
 }
 
+namespace dr1048 { // dr1048: 3.6
+  struct A {};
+  const A f();
+  A g();
+  typedef const A CA;
+#if __cplusplus >= 201103L
+  // ok: we deduce non-const A in each case.
+  A &&a = [] (int n) {
+    while (1) switch (n) {
+      case 0: return f();
+      case 1: return g();
+      case 2: return A();
+      case 3: return CA();
+    }
+  } (0);
+#endif
+}
+
 namespace dr1070 { // dr1070: 3.5
 #if __cplusplus >= 201103L
   struct A {
diff --git a/test/CXX/drs/dr14xx.cpp b/test/CXX/drs/dr14xx.cpp
index e931924..9491f7d 100644
--- a/test/CXX/drs/dr14xx.cpp
+++ b/test/CXX/drs/dr14xx.cpp
@@ -195,3 +195,151 @@
   }
 #endif
 }
+
+#if __cplusplus >= 201103L
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+
+  // libc++'s implementation
+  template <class _E>
+  class initializer_list
+  {
+    const _E* __begin_;
+    size_t    __size_;
+
+    initializer_list(const _E* __b, size_t __s)
+    : __begin_(__b), __size_(__s) {}
+
+  public:
+    typedef _E        value_type;
+    typedef const _E& reference;
+    typedef const _E& const_reference;
+    typedef size_t    size_type;
+
+    typedef const _E* iterator;
+    typedef const _E* const_iterator;
+
+    initializer_list() : __begin_(nullptr), __size_(0) {}
+
+    size_t    size()  const {return __size_;}
+    const _E* begin() const {return __begin_;}
+    const _E* end()   const {return __begin_ + __size_;}
+  };
+} // std
+
+namespace dr1467 {  // dr1467: 3.7 c++11
+  // List-initialization of aggregate from same-type object
+
+  namespace basic0 {
+    struct S {
+      int i = 42;
+    };
+
+    S a;
+    S b(a);
+    S c{a};
+
+    struct SS : public S { } x;
+    S y(x);
+    S z{x};
+  } // basic0
+
+  namespace basic1 {
+    struct S {
+      int i{42};
+    };
+
+    S a;
+    S b(a);
+    S c{a};
+
+    struct SS : public S { } x;
+    S y(x);
+    S z{x};
+  } // basic1
+
+  namespace basic2 {
+    struct S {
+      int i = {42};
+    };
+
+    S a;
+    S b(a);
+    S c{a};
+
+    struct SS : public S { } x;
+    S y(x);
+    S z{x};
+  } // basic2
+
+  namespace dr_example {
+    struct OK {
+      OK() = default;
+      OK(const OK&) = default;
+      OK(int) { }
+    };
+
+    OK ok;
+    OK ok2{ok};
+
+    struct X {
+      X() = default;
+      X(const X&) = default;
+    };
+
+    X x;
+    X x2{x};
+  } // dr_example
+
+  namespace nonaggregate {
+    struct NonAggregate {
+      NonAggregate() {}
+    };
+
+    struct WantsIt {
+      WantsIt(NonAggregate);
+    };
+
+    void f(NonAggregate);
+    void f(WantsIt);
+
+    void test1() {
+      NonAggregate n;
+      f({n});
+    }
+
+    void test2() {
+      NonAggregate x;
+      NonAggregate y{x};
+      NonAggregate z{{x}};
+    }
+  } // nonaggregate
+
+  namespace SelfInitIsNotListInit {
+    struct S {
+      S();
+      explicit S(S &);
+      S(const S &);
+    };
+    S s1;
+    S s2 = {s1}; // ok, not list-initialization so we pick the non-explicit constructor
+  }
+
+  struct NestedInit { int a, b, c; };
+  NestedInit ni[1] = {{NestedInit{1, 2, 3}}};
+
+  namespace NestedInit2 {
+    struct Pair { int a, b; };
+    struct TwoPairs { TwoPairs(Pair, Pair); };
+    struct Value { Value(Pair); Value(TwoPairs); };
+    void f() { Value{{{1,2},{3,4}}}; }
+  }
+} // dr1467
+
+namespace dr1490 {  // dr1490: 3.7 c++11
+  // List-initialization from a string literal
+
+  char s[4]{"abc"};                   // Ok
+  std::initializer_list<char>{"abc"}; // expected-error {{expected unqualified-id}}}
+} // dr190
+#endif
diff --git a/test/CXX/drs/dr15xx.cpp b/test/CXX/drs/dr15xx.cpp
index a9df026..d35583f 100644
--- a/test/CXX/drs/dr15xx.cpp
+++ b/test/CXX/drs/dr15xx.cpp
@@ -3,15 +3,17 @@
 // RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
 // RUN: %clang_cc1 -std=c++1z -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
 
+#if __cplusplus < 201103L
 // expected-no-diagnostics
+#endif
 
-namespace DR1550 { // dr1550: yes
+namespace dr1550 { // dr1550: yes
   int f(bool b, int n) {
     return (b ? (throw 0) : n) + (b ? n : (throw 0));
   }
 }
 
-namespace DR1560 { // dr1560: 3.5
+namespace dr1560 { // dr1560: 3.5
   void f(bool b, int n) {
     (b ? throw 0 : n) = (b ? n : throw 0) = 0;
   }
@@ -19,3 +21,84 @@
   const X &get();
   const X &x = true ? get() : throw 0;
 }
+
+#if __cplusplus >= 201103L
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+
+  // libc++'s implementation
+  template <class _E>
+  class initializer_list
+  {
+    const _E* __begin_;
+    size_t    __size_;
+
+    initializer_list(const _E* __b, size_t __s)
+    : __begin_(__b), __size_(__s) {}
+
+  public:
+    typedef _E        value_type;
+    typedef const _E& reference;
+    typedef const _E& const_reference;
+    typedef size_t    size_type;
+
+    typedef const _E* iterator;
+    typedef const _E* const_iterator;
+
+    initializer_list() : __begin_(nullptr), __size_(0) {}
+
+    size_t    size()  const {return __size_;}
+    const _E* begin() const {return __begin_;}
+    const _E* end()   const {return __begin_ + __size_;}
+  };
+
+  template < class _T1, class _T2 > struct pair { _T2 second; };
+
+  template<typename T> struct basic_string {
+    basic_string(const T* x) {}
+    ~basic_string() {};
+  };
+  typedef basic_string<char> string;
+
+} // std
+
+namespace dr1589 {   // dr1589: 3.7 c++11
+  // Ambiguous ranking of list-initialization sequences
+
+  void f0(long, int=0);                 // Would makes selection of #0 ambiguous
+  void f0(long);                        // #0
+  void f0(std::initializer_list<int>);  // #00
+  void g0() { f0({1L}); }               // chooses #00
+
+  void f1(int, int=0);                    // Would make selection of #1 ambiguous
+  void f1(int);                           // #1
+  void f1(std::initializer_list<long>);   // #2
+  void g1() { f1({42}); }                 // chooses #2
+
+  void f2(std::pair<const char*, const char*>, int = 0); // Would makes selection of #3 ambiguous
+  void f2(std::pair<const char*, const char*>); // #3
+  void f2(std::initializer_list<std::string>);  // #4
+  void g2() { f2({"foo","bar"}); }              // chooses #4
+
+  namespace with_error {
+    void f0(long);                        // #0    expected-note {{candidate function}}
+    void f0(std::initializer_list<int>);  // #00   expected-note {{candidate function}}
+    void f0(std::initializer_list<int>, int = 0);  // Makes selection of #00 ambiguous \
+    // expected-note {{candidate function}}
+    void g0() { f0({1L}); }                 // chooses #00    expected-error{{call to 'f0' is ambiguous}}
+
+    void f1(int);                           // #1   expected-note {{candidate function}}
+    void f1(std::initializer_list<long>);   // #2   expected-note {{candidate function}}
+    void f1(std::initializer_list<long>, int = 0);   // Makes selection of #00 ambiguous \
+    // expected-note {{candidate function}}
+    void g1() { f1({42}); }                 // chooses #2   expected-error{{call to 'f1' is ambiguous}}
+
+    void f2(std::pair<const char*, const char*>); // #3   TODO: expected- note {{candidate function}}
+    void f2(std::initializer_list<std::string>);  // #4   expected-note {{candidate function}}
+    void f2(std::initializer_list<std::string>, int = 0);   // Makes selection of #00 ambiguous \
+    // expected-note {{candidate function}}
+    void g2() { f2({"foo","bar"}); }        // chooses #4   expected-error{{call to 'f2' is ambiguous}}
+  }
+
+} // dr1589
+#endif
diff --git a/test/CXX/drs/dr16xx.cpp b/test/CXX/drs/dr16xx.cpp
new file mode 100644
index 0000000..ddb7d16
--- /dev/null
+++ b/test/CXX/drs/dr16xx.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -std=c++98 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++1z -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+
+#if __cplusplus < 201103L
+// expected-no-diagnostics
+#endif
+
+namespace dr1684 { // dr1684: 3.6
+#if __cplusplus >= 201103L
+  struct NonLiteral { // expected-note {{because}}
+    NonLiteral();
+    constexpr int f() { return 0; } // expected-warning 0-1{{will not be implicitly 'const'}}
+  };
+  constexpr int f(NonLiteral &) { return 0; }
+  constexpr int f(NonLiteral) { return 0; } // expected-error {{not a literal type}}
+#endif
+}
+
+#if __cplusplus >= 201103L
+namespace dr1631 {  // dr1631: 3.7 c++11
+  // Incorrect overload resolution for single-element initializer-list
+
+  struct A { int a[1]; };
+  struct B { B(int); };
+  void f(B, int);
+  void f(B, int, int = 0);
+  void f(int, A);
+
+  void test() {
+    f({0}, {{1}}); // expected-warning {{braces around scalar init}}
+  }
+
+  namespace with_error {
+    void f(B, int);           // TODO: expected- note {{candidate function}}
+    void f(int, A);           // expected-note {{candidate function}}
+    void f(int, A, int = 0);  // expected-note {{candidate function}}
+    
+    void test() {
+      f({0}, {{1}});        // expected-error{{call to 'f' is ambiguous}}
+    }
+  }
+} // dr1631
+#endif
diff --git a/test/CXX/drs/dr1748.cpp b/test/CXX/drs/dr1748.cpp
new file mode 100644
index 0000000..7e04f40
--- /dev/null
+++ b/test/CXX/drs/dr1748.cpp
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | FileCheck %s
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | FileCheck %s
+// RUN: %clang_cc1 -std=c++1z %s -triple x86_64-linux-gnu -emit-llvm -o - -fexceptions -fcxx-exceptions -pedantic-errors | FileCheck %s
+
+// dr1748: 3.7
+
+// FIXME: __SIZE_TYPE__ expands to 'long long' on some targets.
+__extension__ typedef __SIZE_TYPE__ size_t;
+
+void *operator new(size_t, void *);
+void *operator new[](size_t, void *);
+
+struct X { X(); };
+
+// The reserved placement allocation functions get inlined
+// even if we can't see their definitions. They do not
+// perform a null check.
+
+// CHECK-LABEL: define {{.*}} @_Z1fPv(
+// CHECK-NOT: call
+// CHECK-NOT: icmp{{.*}} null
+// CHECK-NOT: br i1
+// CHECK: call void @_ZN1XC1Ev(
+// CHECK: }
+X *f(void *p) { return new (p) X; }
+
+// CHECK-LABEL: define {{.*}} @_Z1gPv(
+// CHECK-NOT: call
+// CHECK-NOT: icmp{{.*}} null
+// CHECK-NOT: br i1
+// CHECK: call void @_ZN1XC1Ev(
+// CHECK: br i1
+// CHECK: }
+X *g(void *p) { return new (p) X[5]; }
diff --git a/test/CXX/drs/dr17xx.cpp b/test/CXX/drs/dr17xx.cpp
new file mode 100644
index 0000000..1ab8c40
--- /dev/null
+++ b/test/CXX/drs/dr17xx.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++1z %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+
+// expected-no-diagnostics
+
+#if __cplusplus >= 201103L
+namespace dr1756 {  // dr1756: 3.7 c++11
+  // Direct-list-initialization of a non-class object
+  
+  int a{0};
+  
+  struct X { operator int(); } x;
+  int b{x};
+} // dr1756
+
+namespace dr1758 {  // dr1758: 3.7 c++11
+  // Explicit conversion in copy/move list initialization
+
+  struct X { X(); };
+  struct Y { explicit operator X(); } y;
+  X x{y};
+
+  struct A {
+    A() {}
+    A(const A &) {}
+  };
+  struct B {
+    operator A() { return A(); }
+  } b;
+  A a{b};
+} // dr1758
+#endif
diff --git a/test/CXX/drs/dr18xx.cpp b/test/CXX/drs/dr18xx.cpp
new file mode 100644
index 0000000..bc72b67
--- /dev/null
+++ b/test/CXX/drs/dr18xx.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -std=c++98 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++1z -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+
+#if __cplusplus < 201103L
+// expected-no-diagnostics
+#endif
+
+void dr1891() { // dr1891: 3.6
+#if __cplusplus >= 201103L
+  int n;
+  auto a = []{}; // expected-note 2{{candidate}}
+  auto b = [=]{ return n; }; // expected-note 2{{candidate}}
+  typedef decltype(a) A;
+  typedef decltype(b) B;
+
+  static_assert(!__has_trivial_constructor(A), "");
+  static_assert(!__has_trivial_constructor(B), "");
+
+  A x; // expected-error {{no matching constructor}}
+  B y; // expected-error {{no matching constructor}}
+#endif
+}
diff --git a/test/CXX/drs/dr19xx.cpp b/test/CXX/drs/dr19xx.cpp
new file mode 100644
index 0000000..9c2d3e7
--- /dev/null
+++ b/test/CXX/drs/dr19xx.cpp
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+// RUN: %clang_cc1 -std=c++1z %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
+
+namespace std { struct type_info; }
+
+namespace dr1902 { // dr1902: 3.7
+  struct A {};
+  struct B {
+    B(A);
+#if __cplusplus >= 201103L
+        // expected-note@-2 {{candidate}}
+#endif
+
+    B() = delete;
+#if __cplusplus < 201103L
+        // expected-error@-2 {{extension}}
+#endif
+
+    B(const B&) // expected-note {{deleted here}}
+#if __cplusplus >= 201103L
+        // expected-note@-2 {{candidate}}
+#else
+        // expected-error@+2 {{extension}}
+#endif
+        = delete;
+
+    operator A();
+  };
+
+  extern B b1;
+  B b2(b1); // expected-error {{call to deleted}}
+
+#if __cplusplus >= 201103L
+  // This is ambiguous, even though calling the B(const B&) constructor would
+  // both directly and indirectly call a deleted function.
+  B b({}); // expected-error {{ambiguous}}
+#endif
+}
+
+#if __cplusplus >= 201103L
+namespace dr1940 { // dr1940: yes
+static union {
+  static_assert(true, "");  // ok
+  static_assert(false, ""); // expected-error {{static_assert failed}}
+};
+}
+#endif
+
+#if __cplusplus >= 201402L
+namespace dr1947 { // dr1947: yes
+unsigned o = 0'01;  // ok
+unsigned b = 0b'01; // expected-error {{invalid digit 'b' in octal constant}}
+unsigned x = 0x'01; // expected-error {{invalid suffix 'x'01' on integer constant}}
+}
+#endif
+
+#if __cplusplus >= 201103L
+// dr1948: yes
+// FIXME: This diagnostic could be improved.
+void *operator new(__SIZE_TYPE__) noexcept { return nullptr; } // expected-error{{exception specification in declaration does not match previous declaration}}
+#endif
+
+#if __cplusplus >= 201103L
+namespace dr1968 { // dr1968: yes
+static_assert(&typeid(int) == &typeid(int), ""); // expected-error{{not an integral constant expression}}
+}
+#endif
+
+// dr1994: dup 529
diff --git a/test/CXX/drs/dr1xx.cpp b/test/CXX/drs/dr1xx.cpp
index 89d0d84..cc6c5af 100644
--- a/test/CXX/drs/dr1xx.cpp
+++ b/test/CXX/drs/dr1xx.cpp
@@ -4,8 +4,8 @@
 // RUN: %clang_cc1 -std=c++1z -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
 
 namespace dr100 { // dr100: yes
-  template<const char *> struct A {}; // expected-note {{declared here}}
-  template<const char (&)[4]> struct B {}; // expected-note {{declared here}}
+  template<const char *> struct A {}; // expected-note 0-1{{declared here}}
+  template<const char (&)[4]> struct B {}; // expected-note 0-1{{declared here}}
   A<"foo"> a; // expected-error {{does not refer to any declaration}}
   B<"bar"> b; // expected-error {{does not refer to any declaration}}
 }
diff --git a/test/CXX/drs/dr2xx.cpp b/test/CXX/drs/dr2xx.cpp
index e4e7554..bb1f13a 100644
--- a/test/CXX/drs/dr2xx.cpp
+++ b/test/CXX/drs/dr2xx.cpp
@@ -991,12 +991,11 @@
 namespace dr294 { // dr294: no
   void f() throw(int);
   int main() {
-    // FIXME: we reject this for the wrong reason, because we don't implement
-    // dr87 yet.
-    (void)static_cast<void (*)() throw()>(f); // expected-error {{not superset}}
-    void (*p)() throw() = f; // expected-error {{not superset}}
-
+    (void)static_cast<void (*)() throw()>(f); // FIXME: ill-formed
     (void)static_cast<void (*)() throw(int)>(f); // FIXME: ill-formed
+
+    void (*p)() throw() = f; // expected-error {{not superset}}
+    void (*q)() throw(int) = f;
   }
 }
 
diff --git a/test/CXX/drs/dr3xx.cpp b/test/CXX/drs/dr3xx.cpp
index 59deaca..cea4d64 100644
--- a/test/CXX/drs/dr3xx.cpp
+++ b/test/CXX/drs/dr3xx.cpp
@@ -206,7 +206,7 @@
 #endif
 }
 
-namespace dr314 { // dr314: dup 1710
+namespace dr314 { // FIXME 314: dup 1710
   template<typename T> struct A {
     template<typename U> struct B {};
   };
@@ -505,7 +505,7 @@
 
 // dr342: na
 
-namespace dr343 { // dr343: no
+namespace dr343 { // FIXME 343: no
   // FIXME: dup 1710
   template<typename T> struct A {
     template<typename U> struct B {};
@@ -705,7 +705,7 @@
   // FIXME: Should we allow this in C++98 too?
   struct S {};
 
-  template<int*> struct ptr {}; // expected-note +{{here}}
+  template<int*> struct ptr {}; // expected-note 0-4{{here}}
   ptr<0> p0;
   ptr<(int*)0> p1;
   ptr<(float*)0> p2;
@@ -715,11 +715,16 @@
   // expected-error@-5 {{does not refer to any decl}}
   // expected-error@-5 {{does not refer to any decl}}
   // expected-error@-5 {{does not refer to any decl}}
-#else
+#elif __cplusplus <= 201402L
   // expected-error@-10 {{must be cast}}
   // ok
   // expected-error@-10 {{does not match}}
   // expected-error@-10 {{does not match}}
+#else
+  // expected-error@-15 {{conversion from 'int' to 'int *' is not allowed}}
+  // ok
+  // expected-error@-15 {{'float *' is not implicitly convertible to 'int *'}}
+  // expected-error@-15 {{'int dr354::S::*' is not implicitly convertible to 'int *'}}
 #endif
 
   template<int*> int both();
@@ -732,7 +737,7 @@
   // expected-note@-6 {{candidate}}
 #endif
 
-  template<int S::*> struct ptr_mem {}; // expected-note +{{here}}
+  template<int S::*> struct ptr_mem {}; // expected-note 0-4{{here}}
   ptr_mem<0> m0;
   ptr_mem<(int S::*)0> m1;
   ptr_mem<(float S::*)0> m2;
@@ -742,11 +747,16 @@
   // expected-error@-5 {{is not a pointer to member constant}}
   // expected-error@-5 {{cannot be converted}}
   // expected-error@-5 {{cannot be converted}}
-#else
+#elif __cplusplus <= 201402L
   // expected-error@-10 {{must be cast}}
   // ok
   // expected-error@-10 {{does not match}}
   // expected-error@-10 {{does not match}}
+#else
+  // expected-error@-15 {{conversion from 'int' to 'int dr354::S::*' is not allowed}}
+  // ok
+  // expected-error@-15 {{'float dr354::S::*' is not implicitly convertible to 'int dr354::S::*'}}
+  // expected-error@-15 {{'int *' is not implicitly convertible to 'int dr354::S::*'}}
 #endif
 }
 
@@ -1209,7 +1219,7 @@
 
 namespace dr395 { // dr395: yes
   struct S {
-    template <typename T, int N>(&operator T())[N]; // expected-error {{must use a typedef}}
+    template <typename T, int N>(&operator T())[N]; // expected-error {{cannot specify any part of a return type}}
     template <typename T, int N> operator(T (&)[N])(); // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error +{{}}
     template <typename T> operator T *() const { return 0; }
     template <typename T, typename U> operator T U::*() const { return 0; }
diff --git a/test/CXX/drs/dr5xx.cpp b/test/CXX/drs/dr5xx.cpp
index b0254f2..5bf085f 100644
--- a/test/CXX/drs/dr5xx.cpp
+++ b/test/CXX/drs/dr5xx.cpp
@@ -798,7 +798,7 @@
 }
 
 namespace dr576 { // dr576: yes
-  typedef void f() {} // expected-error {{function definition is not allowed}}
+  typedef void f() {} // expected-error {{function definition declared 'typedef'}}
   void f(typedef int n); // expected-error {{invalid storage class}}
   void f(char c) { typedef int n; }
 }
diff --git a/test/CXX/drs/dr6xx.cpp b/test/CXX/drs/dr6xx.cpp
index 594eac8..988c8f4 100644
--- a/test/CXX/drs/dr6xx.cpp
+++ b/test/CXX/drs/dr6xx.cpp
@@ -256,7 +256,9 @@
     '&' == L'&' && '|' == L'|' && '~' == L'~' && '!' == L'!' && '=' == L'=' &&
     ',' == L',' && '\\' == L'\\' && '"' == L'"' && '\'' == L'\'';
 #if __STDC_MB_MIGHT_NEQ_WC__
+#ifndef __FreeBSD__ // PR22208, FreeBSD expects us to give a bad (but conforming) answer here.
 _Static_assert(!MB_EQ_WC, "__STDC_MB_MIGHT_NEQ_WC__ but all basic source characters have same representation"); // expected-error {{C11}}
+#endif
 #else
 _Static_assert(MB_EQ_WC, "!__STDC_MB_MIGHT_NEQ_WC__ but some character differs"); // expected-error {{C11}}
 #endif
diff --git a/test/CXX/except/except.spec/p14-ir.cpp b/test/CXX/except/except.spec/p14-ir.cpp
index e3b15e5..af1d9a4 100644
--- a/test/CXX/except/except.spec/p14-ir.cpp
+++ b/test/CXX/except/except.spec/p14-ir.cpp
@@ -66,16 +66,16 @@
   // CHECK-NEXT: ret void
   X9();
 
+  // CHECK: define linkonce_odr void @_ZN2X8C2Ev(%struct.X8* %this) unnamed_addr
+  // CHECK:      call void @_ZN2X6C2Ev({{.*}}) [[NUW]]
+  // CHECK-NEXT: ret void
+
   // CHECK: define linkonce_odr void @_ZN2X9C2Ev(%struct.X9* %this) unnamed_addr
   // CHECK:      call void @_ZN2X6C2Ev({{.*}}) [[NUW]]
   //   FIXME: and here:
   // CHECK-NEXT: bitcast
   // CHECK-NEXT: call void @_ZN2X7C2Ev({{.*}})
   // CHECK: ret void
-
-  // CHECK: define linkonce_odr void @_ZN2X8C2Ev(%struct.X8* %this) unnamed_addr
-  // CHECK:      call void @_ZN2X6C2Ev({{.*}}) [[NUW]]
-  // CHECK-NEXT: ret void
 }
 
 // CHECK: attributes [[NUW]] = { nounwind{{.*}} }
diff --git a/test/CXX/except/except.spec/p5-delayed.cpp b/test/CXX/except/except.spec/p5-delayed.cpp
new file mode 100644
index 0000000..99c0e2d
--- /dev/null
+++ b/test/CXX/except/except.spec/p5-delayed.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -std=c++11 -verify %s -fexceptions -fcxx-exceptions
+
+struct A { struct X { virtual ~X() throw(Y); }; struct Y : X {}; };
+struct B { struct X { virtual void f() throw(Y); }; struct Y : X { void f() throw(Y); }; };
+struct C { struct X { virtual void f() throw(Y); }; struct Y : X { void f() throw(); }; };
+struct D { struct X { virtual void f() throw(Y); }; struct Y : X { void f() noexcept; }; };
+struct E { struct Y; struct X { virtual Y &operator=(const Y&) throw(Y); }; struct Y : X {}; };
+struct F {
+  struct X {
+    virtual void f() throw(Y); // expected-note {{here}}
+  };
+  struct Y : X {
+    void f() throw(int); // expected-error {{more lax}}
+  };
+};
diff --git a/test/CXX/expr/expr.const/p2-0x.cpp b/test/CXX/expr/expr.const/p2-0x.cpp
index 249e552..d027c7a 100644
--- a/test/CXX/expr/expr.const/p2-0x.cpp
+++ b/test/CXX/expr/expr.const/p2-0x.cpp
@@ -131,14 +131,14 @@
 namespace UndefinedBehavior {
   void f(int n) {
     switch (n) {
-    case (int)4.4e9: // expected-error {{constant expression}} expected-note {{value 4.4E+9 is outside the range of representable values of type 'int'}} expected-note {{previous case defined here}}
+    case (int)4.4e9: // expected-error {{constant expression}} expected-note {{value 4.4E+9 is outside the range of representable values of type 'int'}}
     case (int)0x80000000u: // ok
     case (int)10000000000ll: // expected-note {{here}}
     case (unsigned int)10000000000ll: // expected-error {{duplicate case value}}
     case (int)(unsigned)(long long)4.4e9: // ok
-    case (int)(float)1e300: // expected-error {{constant expression}} expected-note {{value 1.0E+300 is outside the range of representable values of type 'float'}} expected-error {{duplicate case value '2147483647'}} expected-note {{previous case defined here}}
+    case (int)(float)1e300: // expected-error {{constant expression}} expected-note {{value 1.0E+300 is outside the range of representable values of type 'float'}}
     case (int)((float)1e37 / 1e30): // ok
-    case (int)(__fp16)65536: // expected-error {{constant expression}} expected-note {{value 65536 is outside the range of representable values of type '__fp16'}} expected-error {{duplicate case value '2147483647'}}
+    case (int)(__fp16)65536: // expected-error {{constant expression}} expected-note {{value 65536 is outside the range of representable values of type '__fp16'}}
       break;
     }
   }
diff --git a/test/CXX/expr/expr.prim/expr.prim.general/p8-0x.cpp b/test/CXX/expr/expr.prim/expr.prim.general/p8-0x.cpp
index 5b3a004..b5cd988 100644
--- a/test/CXX/expr/expr.prim/expr.prim.general/p8-0x.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.general/p8-0x.cpp
@@ -47,8 +47,8 @@
   decltype()::middle::fail g; // expected-error{{expected expression}}
   
   decltype(int()) h;
-  decltype(int())::PR10127::outer i; // expected-error{{'decltype(int())' (aka 'int') is not a class, namespace, or scoped enumeration}}
-  decltype(int())::global j; // expected-error{{'decltype(int())' (aka 'int') is not a class, namespace, or scoped enumeration}}
+  decltype(int())::PR10127::outer i; // expected-error{{'decltype(int())' (aka 'int') is not a class, namespace, or enumeration}}
+  decltype(int())::global j; // expected-error{{'decltype(int())' (aka 'int') is not a class, namespace, or enumeration}}
   
   outer::middle k = decltype(outer())::middle();
   outer::middle::inner l = decltype(outer())::middle::inner();
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
index 6be200d..1228c74 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
@@ -48,7 +48,7 @@
 auto bad_init_3 = [&a(void_fn())] {}; // expected-error {{cannot form a reference to 'void'}}
 auto bad_init_4 = [a(void_fn())] {}; // expected-error {{has incomplete type 'void'}}
 auto bad_init_5 = [a(overload_fn)] {}; // expected-error {{cannot deduce type for lambda capture 'a' from initializer of type '<overloaded function}}
-auto bad_init_6 = [a{overload_fn}] {}; // expected-error {{cannot deduce type for lambda capture 'a' from initializer list}}
+auto bad_init_6 = [a{overload_fn}] {}; // expected-error {{cannot deduce type for lambda capture 'a' from initializer list}} expected-warning {{will change meaning in a future version of Clang}}
 
 template<typename...T> void pack_1(T...t) { (void)[a(t...)] {}; } // expected-error {{initializer missing for lambda capture 'a'}}
 template void pack_1<>(); // expected-note {{instantiation of}}
@@ -61,7 +61,7 @@
   using T = decltype(c);
   using T = const int &;
 };
-auto b = [a{0}] {}; // expected-error {{include <initializer_list>}}
+auto b = [a{0}] {}; // expected-error {{include <initializer_list>}} expected-warning {{will change meaning in a future version of Clang}}
 
 struct S { S(); S(S&&); };
 template<typename T> struct remove_reference { typedef T type; };
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p19.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p19.cpp
index 35b7789..40360e4 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p19.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p19.cpp
@@ -7,10 +7,10 @@
 
 template<typename T> T &&move(T&);
 void test_special_member_functions(MoveOnly mo, int i) {
-  auto lambda1 = [i]() { }; // expected-note 2 {{lambda expression begins here}}
+  auto lambda1 = [i]() { }; // expected-note {{lambda expression begins here}} expected-note 2{{candidate}}
 
   // Default constructor
-  decltype(lambda1) lambda2; // expected-error{{call to implicitly-deleted default constructor of 'decltype(lambda1)' (aka '(lambda}}
+  decltype(lambda1) lambda2; // expected-error{{no matching constructor}}
 
   // Copy assignment operator
   lambda1 = lambda1; // expected-error{{copy assignment operator is implicitly deleted}}
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p2-generic-lambda-1y.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p2-generic-lambda-1y.cpp
index 03147a6..d791ed6 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p2-generic-lambda-1y.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p2-generic-lambda-1y.cpp
@@ -18,7 +18,7 @@
   // FIXME: this should only emit one error.
   int i2 = sizeof([](auto a, auto b)->void{}(3, '4')); // expected-error{{lambda expression in an unevaluated operand}} \
                                                        // expected-error{{invalid application of 'sizeof'}}
-  const std::type_info &ti1 = typeid([](auto &a) -> P& { static P p; return p; }(i));
+  const std::type_info &ti1 = typeid([](auto &a) -> P& { static P p; return p; }(i)); // expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
   const std::type_info &ti2 = typeid([](auto) -> int { return i; }(i));  // expected-error{{lambda expression in an unevaluated operand}}\
                                                                          // expected-error{{cannot be implicitly captured}}\
                                                                          // expected-note{{begins here}}
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p2.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p2.cpp
index 1fbe287..647c76d 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p2.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p2.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -std=c++11 %s -verify
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wno-unused-value %s -verify
 
 // prvalue
 void prvalue() {
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
index c0fa72b..80771d7 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
@@ -1,11 +1,11 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 %s -verify
 
 void test_nonaggregate(int i) {
-  auto lambda = [i]() -> void {}; // expected-note 3{{candidate constructor}}
+  auto lambda = [i]() -> void {}; // expected-note 2{{candidate constructor}}
   decltype(lambda) foo = { 1 }; // expected-error{{no matching constructor}}
   static_assert(!__is_literal(decltype(lambda)), "");
 
-  auto lambda2 = []{}; // expected-note {{lambda}}
-  decltype(lambda2) bar = {}; // expected-error{{call to implicitly-deleted default constructor}}
+  auto lambda2 = []{}; // expected-note 2{{candidate constructor}}
+  decltype(lambda2) bar = {}; // expected-error{{no matching constructor}}
   static_assert(!__is_literal(decltype(lambda2)), "");
 }
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp
index 1016cb1..a36175a 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp
@@ -34,15 +34,12 @@
   }(5);
 }
 
-X infer_X_return_type_fail(X x) {
+X infer_X_return_type_2(X x) {
   return [x](int y) {
     if (y > 0)
       return X();
     else
-      return x;
-#if __cplusplus <= 201103L
-    // expected-error@-2 {{return type 'const X' must match previous return type 'X' when lambda expression has unspecified explicit return type}}
-#endif
+      return x; // ok even in c++11, per dr1048.
   }(5);
 }
 
diff --git a/test/CXX/expr/expr.unary/expr.unary.noexcept/sema.cpp b/test/CXX/expr/expr.unary/expr.unary.noexcept/sema.cpp
index 427e8c5..a2a5795 100644
--- a/test/CXX/expr/expr.unary/expr.unary.noexcept/sema.cpp
+++ b/test/CXX/expr/expr.unary/expr.unary.noexcept/sema.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -fsyntax-only -verify -std=c++11 -fms-extensions -Wno-delete-incomplete %s
+// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -fsyntax-only -verify -std=c++11 -fms-extensions -Wno-delete-incomplete -Wno-unused-value %s
 // expected-no-diagnostics
 
 #define P(e) static_assert(noexcept(e), "expected nothrow")
diff --git a/test/CXX/lex/lex.trigraph/p1.cpp b/test/CXX/lex/lex.trigraph/p1.cpp
index aacbc55..a80b00e 100644
--- a/test/CXX/lex/lex.trigraph/p1.cpp
+++ b/test/CXX/lex/lex.trigraph/p1.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -trigraphs -Wtrigraphs -verify %s
+// RUN: %clang_cc1 -fsyntax-only -ftrigraphs -Wtrigraphs -verify %s
 
 ??=pragma // expected-warning {{trigraph converted to '#' character}}
 
diff --git a/test/CXX/lex/lex.trigraph/p2.cpp b/test/CXX/lex/lex.trigraph/p2.cpp
index 7d11d5b..6502aa8 100644
--- a/test/CXX/lex/lex.trigraph/p2.cpp
+++ b/test/CXX/lex/lex.trigraph/p2.cpp
@@ -1,3 +1,3 @@
-// RUN: %clang_cc1 -fsyntax-only -trigraphs -Wtrigraphs -verify %s
+// RUN: %clang_cc1 -fsyntax-only -ftrigraphs -Wtrigraphs -verify %s
 
 ??=define arraycheck(a,b) a??(b??) ??!??! b??(a??) // expected-warning {{trigraph converted to '#' character}} expected-warning {{trigraph converted to '[' character}} expected-warning {{trigraph converted to ']' character}} expected-warning {{trigraph converted to '|' character}} expected-warning {{trigraph converted to '|' character}} expected-warning {{trigraph converted to '[' character}} expected-warning {{trigraph converted to ']' character}}
diff --git a/test/CXX/lex/lex.trigraph/p3.cpp b/test/CXX/lex/lex.trigraph/p3.cpp
index c74d8f3..bf93570 100644
--- a/test/CXX/lex/lex.trigraph/p3.cpp
+++ b/test/CXX/lex/lex.trigraph/p3.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -trigraphs -Wtrigraphs -verify %s
+// RUN: %clang_cc1 -fsyntax-only -ftrigraphs -Wtrigraphs -verify %s
 // expected-no-diagnostics
 
 char a[] =
diff --git a/test/CXX/special/class.copy/implicit-move.cpp b/test/CXX/special/class.copy/implicit-move.cpp
index a10d139..588778c 100644
--- a/test/CXX/special/class.copy/implicit-move.cpp
+++ b/test/CXX/special/class.copy/implicit-move.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base %s
 
 // Tests for implicit (non-)declaration of move constructor and
 // assignment: p9, p11, p20, p23.
diff --git a/test/CXX/special/class.copy/p15-inclass.cpp b/test/CXX/special/class.copy/p15-inclass.cpp
index 6cfa94f..30872cc 100644
--- a/test/CXX/special/class.copy/p15-inclass.cpp
+++ b/test/CXX/special/class.copy/p15-inclass.cpp
@@ -20,21 +20,21 @@
     X x3(static_cast<X&&>(x));
   }
 
-  // CHECK: define linkonce_odr void @_ZN7PR114181XC2EOS0_
+  // CHECK: define linkonce_odr void @_ZN7PR114181XC2ERKS0_
   // CHECK-NOT: 17
-  // CHECK: call void @_ZN7PR114186NonPODC1EOS0_
+  // CHECK: call void @_ZN7PR114186NonPODC1ERKS0_
   // CHECK-NOT: 17
-  // CHECK: load i32* 
+  // CHECK: load i32*
   // CHECK-NOT: 17
   // CHECK: store i32
   // CHECK-NOT: 17
   // CHECK: ret
 
-  // CHECK: define linkonce_odr void @_ZN7PR114181XC2ERKS0_
+  // CHECK: define linkonce_odr void @_ZN7PR114181XC2EOS0_
   // CHECK-NOT: 17
-  // CHECK: call void @_ZN7PR114186NonPODC1ERKS0_
+  // CHECK: call void @_ZN7PR114186NonPODC1EOS0_
   // CHECK-NOT: 17
-  // CHECK: load i32* 
+  // CHECK: load i32*
   // CHECK-NOT: 17
   // CHECK: store i32
   // CHECK-NOT: 17
diff --git a/test/CXX/special/class.dtor/p9.cpp b/test/CXX/special/class.dtor/p9.cpp
index a03fcdb..42a4236 100644
--- a/test/CXX/special/class.dtor/p9.cpp
+++ b/test/CXX/special/class.dtor/p9.cpp
@@ -89,4 +89,11 @@
     virtual ~B() {}
     static void operator delete(void*);
   };
+
+  void f() {
+#ifdef MSABI
+    // expected-note@+2 {{implicit default constructor for 'test3::B' first required here}}
+#endif
+    B use_vtable;
+  }
 }
diff --git a/test/CXX/special/class.inhctor/p2.cpp b/test/CXX/special/class.inhctor/p2.cpp
index e6abd68..d1c16ff 100644
--- a/test/CXX/special/class.inhctor/p2.cpp
+++ b/test/CXX/special/class.inhctor/p2.cpp
@@ -96,7 +96,7 @@
   template<typename T = int> TemplateCtors(int, int = 0, int = 0); // expected-note {{inherited from here}}
 };
 
-struct UsingTemplateCtors : TemplateCtors {
+struct UsingTemplateCtors : TemplateCtors {  // expected-note 2{{candidate is the implicit}}
   using TemplateCtors::TemplateCtors; // expected-note 4{{here}} expected-note {{candidate}}
 
   constexpr UsingTemplateCtors(X<0>, X<0>) {}
diff --git a/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp b/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
index c23cd28..7d689ae 100644
--- a/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
+++ b/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
@@ -50,6 +50,18 @@
   struct NoEndADL {
     null_t alt_begin();
   };
+
+  struct C {
+    C();
+    struct It {
+      int val;
+      operator int &() { return val; }
+    };
+    It begin();
+    It end();
+  };
+
+  constexpr int operator*(const C::It &) { return 0; }
 }
 
 using X::A;
@@ -118,7 +130,7 @@
   for (extern int a : A()) {} // expected-error {{loop variable 'a' may not be declared 'extern'}}
   for (static int a : A()) {} // expected-error {{loop variable 'a' may not be declared 'static'}}
   for (register int a : A()) {} // expected-error {{loop variable 'a' may not be declared 'register'}} expected-warning {{deprecated}}
-  for (constexpr int a : A()) {} // expected-error {{loop variable 'a' may not be declared 'constexpr'}}
+  for (constexpr int a : X::C()) {} // OK per CWG issue #1204.
 
   for (auto u : X::NoBeginADL()) { // expected-error {{invalid range expression of type 'X::NoBeginADL'; no viable 'begin' function available}}
   }
diff --git a/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p4.cpp b/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p4.cpp
index b2a6219..9b3088f 100644
--- a/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p4.cpp
+++ b/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p4.cpp
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
 
 template<class T> struct A { A(); };
 template<class T> int &f(T); 
@@ -21,3 +22,23 @@
   const A<int> z2; 
   int &ir1 = h(z2);
 }
+
+
+namespace core_26909 {
+  template<typename T> struct A {};
+  template<typename T, typename U> void f(T&, U); // expected-note {{candidate}}
+  template<typename T, typename U> void f(T&&, A<U>); // expected-note {{candidate}} expected-warning 0-1{{extension}}
+  template<typename T, typename U> void g(const T&, U); // expected-note {{candidate}}
+  template<typename T, typename U> void g(T&, A<U>); // expected-note {{candidate}}
+
+  void h(int a, const char b, A<int> c) {
+    f(a, c); // expected-error{{ambiguous}}
+    g(b, c); // expected-error{{ambiguous}}
+  }
+}
+
+namespace PR22435 {
+  template<typename T, typename U> void foo(void (*)(T), const U &); // expected-note {{candidate}}
+  template<typename T, typename U> bool foo(void (*)(T &), U &); // expected-note {{candidate}}
+  void bar(const int x) { bool b = foo<char>(0, x); } // expected-error {{ambiguous}}
+}
diff --git a/test/CXX/temp/temp.param/p15-cxx0x.cpp b/test/CXX/temp/temp.param/p15-cxx0x.cpp
index 59618d2..ade192b 100644
--- a/test/CXX/temp/temp.param/p15-cxx0x.cpp
+++ b/test/CXX/temp/temp.param/p15-cxx0x.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
-template<typename T> struct X;
+template<typename T> struct X; // expected-note {{'X' is incomplete}}
 template<int I> struct Y;
 
 X<X<int>> *x1;
diff --git a/test/CXX/temp/temp.res/temp.local/p3.cpp b/test/CXX/temp/temp.res/temp.local/p3.cpp
index e29ced1..d5e3786 100644
--- a/test/CXX/temp/temp.res/temp.local/p3.cpp
+++ b/test/CXX/temp/temp.res/temp.local/p3.cpp
@@ -15,7 +15,7 @@
     t->Base<T>::f();
     t->Base::f(); // expected-error{{member 'Base' found in multiple base classes of different types}} \
     // expected-error{{no member named 'f' in 'X0'}} \
-    // expected-error{{'Base' is not a class, namespace, or scoped enumeration}}
+    // expected-error{{'Base' is not a class, namespace, or enumeration}}
   }
 };
 
diff --git a/test/CodeGen/2003-08-06-BuiltinSetjmpLongjmp.c b/test/CodeGen/2003-08-06-BuiltinSetjmpLongjmp.c
deleted file mode 100644
index 3aa5c00..0000000
--- a/test/CodeGen/2003-08-06-BuiltinSetjmpLongjmp.c
+++ /dev/null
@@ -1,15 +0,0 @@
-/* RUN: %clang_cc1  %s -emit-llvm -o - | FileCheck %s
- *
- * __builtin_longjmp/setjmp should get transformed into intrinsics.
- */
-
-// CHECK-NOT: builtin_longjmp
-
-void jumpaway(int *ptr) {
-  __builtin_longjmp(ptr,1);
-}
-    
-int main(void) {
-  __builtin_setjmp(0);
-  jumpaway(0);
-}
diff --git a/test/CodeGen/2004-06-17-UnorderedCompares.c b/test/CodeGen/2004-06-17-UnorderedCompares.c
index 7d2ba96..2c80180 100644
--- a/test/CodeGen/2004-06-17-UnorderedCompares.c
+++ b/test/CodeGen/2004-06-17-UnorderedCompares.c
@@ -1,4 +1,6 @@
-// RUN: %clang_cc1  -std=c99 %s -emit-llvm -o - | grep -v llvm.isunordered | not grep call
+// RUN: %clang_cc1  -std=c99 %s -emit-llvm -o - | FileCheck %s
+// CHECK: @Test
+// CHECK-NOT: call
 
 _Bool A, B, C, D, E, F;
 void TestF(float X, float Y) {
diff --git a/test/CodeGen/2009-01-05-BlockInlining.c b/test/CodeGen/2009-01-05-BlockInlining.c
index 2ae9b70..61e5244 100644
--- a/test/CodeGen/2009-01-05-BlockInlining.c
+++ b/test/CodeGen/2009-01-05-BlockInlining.c
@@ -1,12 +1,12 @@
-// RUN: %clang_cc1 %s -emit-llvm -fblocks -o - | FileCheck %s
+// RUN: %clang_cc1 %s -triple x86_64-linux -emit-llvm -fblocks -o - | FileCheck %s
 // rdar://5865221
 
 // These will be inlined by the optimizers provided the block descriptors
 // and block literals are internal constants.
 // CHECK: @__block_descriptor_tmp = internal constant
 // CHECK: @__block_literal_global = internal constant
-// CHECK: @__block_descriptor_tmp1 = internal constant
-// CHECK: @__block_literal_global2 = internal constant
+// CHECK: @__block_descriptor_tmp2 = internal constant
+// CHECK: @__block_literal_global3 = internal constant
 static int fun(int x) {
 	return x+1;
 }
diff --git a/test/CodeGen/2009-10-20-GlobalDebug.c b/test/CodeGen/2009-10-20-GlobalDebug.c
index 1b80b3e..e56f227 100644
--- a/test/CodeGen/2009-10-20-GlobalDebug.c
+++ b/test/CodeGen/2009-10-20-GlobalDebug.c
@@ -6,5 +6,5 @@
   return 0;
 }
 
-// CHECK: metadata !{metadata !"0x34\00localstatic\00localstatic\00\005\001\001", metadata !{{.*}}, metadata !{{.*}}, metadata !{{.*}}, i32* @main.localstatic, null} ; [ DW_TAG_variable ]
-// CHECK: metadata !{metadata !"0x34\00global\00global\00\003\000\001", null, metadata !{{.*}}, metadata !{{.*}}, i32* @global, null} ; [ DW_TAG_variable ]
+// CHECK:  !"0x34\00localstatic\00localstatic\00\005\001\001", !{{.*}}, !{{.*}}, !{{.*}}, i32* @main.localstatic, null} ; [ DW_TAG_variable ]
+// CHECK:  !"0x34\00global\00global\00\003\000\001", null, !{{.*}}, !{{.*}}, i32* @global, null} ; [ DW_TAG_variable ]
diff --git a/test/CodeGen/2010-02-15-DbgStaticVar.c b/test/CodeGen/2010-02-15-DbgStaticVar.c
index a75ffbb..8980b60 100644
--- a/test/CodeGen/2010-02-15-DbgStaticVar.c
+++ b/test/CodeGen/2010-02-15-DbgStaticVar.c
@@ -11,4 +11,4 @@
 	int j = foo(1);
 	return 0;
 }
-// CHECK: metadata !"0x34\00b\00b\00\00{{.*}}",
+// CHECK: !"0x34\00b\00b\00\00{{.*}}",
diff --git a/test/CodeGen/2010-07-08-DeclDebugLineNo.c b/test/CodeGen/2010-07-08-DeclDebugLineNo.c
index 5e9edd9..44c973a 100644
--- a/test/CodeGen/2010-07-08-DeclDebugLineNo.c
+++ b/test/CodeGen/2010-07-08-DeclDebugLineNo.c
@@ -6,5 +6,5 @@
   int p = 0;    // line #5: CHECK: {{call.*llvm.dbg.declare.*%p.*\!dbg }}[[variable_p:![0-9]+]]
 }
 // Now match the line number records:
-// CHECK: {{^}}[[variable_l]]{{ = metadata ![{]i32 5,}}
-// CHECK: {{^}}[[variable_p]]{{ = metadata ![{]i32 6,}}
+// CHECK: {{^}}[[variable_l]] = !MDLocation(line: 5,
+// CHECK: {{^}}[[variable_p]] = !MDLocation(line: 6,
diff --git a/test/CodeGen/aarch64-fix-cortex-a53-835769.c b/test/CodeGen/aarch64-fix-cortex-a53-835769.c
new file mode 100644
index 0000000..7ad1240
--- /dev/null
+++ b/test/CodeGen/aarch64-fix-cortex-a53-835769.c
@@ -0,0 +1,27 @@
+// REQUIRES: aarch64-registered-target
+
+// RUN: %clang -O3 -target aarch64-linux-eabi %s -S -o- \
+// RUN:   | FileCheck --check-prefix=CHECK-NO --check-prefix=CHECK %s
+// RUN: %clang -O3 -target aarch64-linux-eabi -mfix-cortex-a53-835769 %s -S -o- 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-YES --check-prefix=CHECK %s
+// RUN: %clang -O3 -target aarch64-linux-eabi -mno-fix-cortex-a53-835769 %s -S -o- 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO --check-prefix=CHECK %s
+
+// RUN: %clang -O3 -target aarch64-android-eabi %s -S -o- \
+// RUN:   | FileCheck --check-prefix=CHECK-YES --check-prefix=CHECK %s
+// RUN: %clang -O3 -target aarch64-android-eabi -mfix-cortex-a53-835769 %s -S -o- \
+// RUN:   | FileCheck --check-prefix=CHECK-YES --check-prefix=CHECK %s
+// RUN: %clang -O3 -target aarch64-android-eabi -mno-fix-cortex-a53-835769 %s -S -o- \
+// RUN:   | FileCheck --check-prefix=CHECK-NO --check-prefix=CHECK %s
+
+typedef long int64_t;
+
+int64_t f_load_madd_64(int64_t a, int64_t b, int64_t *c) {
+    int64_t result = a+b*(*c);
+    return result;
+}
+
+// CHECK: ldr
+// CHECK-YES-NEXT: nop
+// CHECK-NO-NEXT-NOT: nop
+// CHECK-NEXT: madd
diff --git a/test/CodeGen/address-space.c b/test/CodeGen/address-space.c
index 3e865fd..110406e 100644
--- a/test/CodeGen/address-space.c
+++ b/test/CodeGen/address-space.c
@@ -1,7 +1,4 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm < %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm < %s | grep 'load.*addrspace(2).. @A'
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm < %s | grep 'load.*addrspace(2).. @B'
-
 
 // CHECK: @foo = common addrspace(1) global
 int foo __attribute__((address_space(1)));
@@ -23,7 +20,7 @@
 
 // CHECK-LABEL: define void @test3()
 // CHECK: load i32 addrspace(2)** @B
-// CHECK: load i32 addrspace(2)* 
+// CHECK: load i32 addrspace(2)*
 // CHECK: load i32 addrspace(2)** @A
 // CHECK: store i32 {{.*}}, i32 addrspace(2)*
 void test3() {
diff --git a/test/CodeGen/align-local.c b/test/CodeGen/align-local.c
index b839ee1..c8b27a8 100644
--- a/test/CodeGen/align-local.c
+++ b/test/CodeGen/align-local.c
@@ -1,7 +1,9 @@
-// RUN: %clang_cc1 -emit-llvm < %s | grep "align 16" | count 2
+// RUN: %clang_cc1 -emit-llvm < %s | FileCheck %s
 
 typedef struct __attribute((aligned(16))) {int x[4];} ff;
 
+// CHECK: alloca %struct.ff, align 16
+// CHECK: alloca %struct.anon, align 16
 int a() {
   ff a;
   struct {int x[4];} b __attribute((aligned(16)));
diff --git a/test/CodeGen/arm-aapcs-vfp.c b/test/CodeGen/arm-aapcs-vfp.c
index da1e675..9c463fd 100644
--- a/test/CodeGen/arm-aapcs-vfp.c
+++ b/test/CodeGen/arm-aapcs-vfp.c
@@ -29,7 +29,7 @@
   float f4;
 };
 // CHECK: define arm_aapcs_vfpcc %struct.homogeneous_struct @test_struct(%struct.homogeneous_struct %{{.*}})
-// CHECK64: define %struct.homogeneous_struct @test_struct(float %{{.*}}, float %{{.*}}, float %{{.*}}, float %{{.*}})
+// CHECK64: define %struct.homogeneous_struct @test_struct([4 x float] %{{.*}})
 extern struct homogeneous_struct struct_callee(struct homogeneous_struct);
 struct homogeneous_struct test_struct(struct homogeneous_struct arg) {
   return struct_callee(arg);
@@ -44,7 +44,7 @@
   double d[4];
 };
 // CHECK: define arm_aapcs_vfpcc void @test_array(%struct.nested_array %{{.*}})
-// CHECK64: define void @test_array(double %{{.*}}, double %{{.*}}, double %{{.*}}, double %{{.*}})
+// CHECK64: define void @test_array([4 x double] %{{.*}})
 extern void array_callee(struct nested_array);
 void test_array(struct nested_array arg) {
   array_callee(arg);
@@ -52,7 +52,7 @@
 
 extern void complex_callee(__complex__ double);
 // CHECK: define arm_aapcs_vfpcc void @test_complex({ double, double } %{{.*}})
-// CHECK64: define void @test_complex(double %{{.*}}, double %{{.*}})
+// CHECK64: define void @test_complex([2 x double] %cd.coerce)
 void test_complex(__complex__ double cd) {
   complex_callee(cd);
 }
@@ -98,7 +98,7 @@
 
 // Neon multi-vector types are homogeneous aggregates.
 // CHECK: define arm_aapcs_vfpcc <16 x i8> @f0(%struct.int8x16x4_t %{{.*}})
-// CHECK64: define <16 x i8> @f0(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
+// CHECK64: define <16 x i8> @f0([4 x <16 x i8>] %{{.*}})
 int8x16_t f0(int8x16x4_t v4) {
   return vaddq_s8(v4.val[0], v4.val[3]);
 }
@@ -112,7 +112,7 @@
   int16x4_t v4;
 };
 // CHECK: define arm_aapcs_vfpcc void @test_neon(%struct.neon_struct %{{.*}})
-// CHECK64: define void @test_neon(<8 x i8> %{{.*}}, <8 x i8> %{{.*}}, <2 x i32> %{{.*}}, <4 x i16> %{{.*}})
+// CHECK64: define void @test_neon([4 x <8 x i8>] %{{.*}})
 extern void neon_callee(struct neon_struct);
 void test_neon(struct neon_struct arg) {
   neon_callee(arg);
@@ -126,19 +126,19 @@
 // CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_1(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, i64 %k, i32 %l)
 void test_vfp_stack_gpr_split_1(double a, double b, double c, double d, double e, double f, double g, double h, double i, int j, long long k, int l) {}
 
-// CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_2(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, [3 x i32], [2 x i64] %k.coerce)
+// CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_2(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, [2 x i64] %k.coerce)
 void test_vfp_stack_gpr_split_2(double a, double b, double c, double d, double e, double f, double g, double h, double i, int j, struct_long_long_int k) {}
 
-// CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_3(%struct.struct_long_long_int* noalias sret %agg.result, double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, [3 x i32], [2 x i64] %k.coerce)
+// CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_3(%struct.struct_long_long_int* noalias sret %agg.result, double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, [2 x i64] %k.coerce)
 struct_long_long_int test_vfp_stack_gpr_split_3(double a, double b, double c, double d, double e, double f, double g, double h, double i, struct_long_long_int k) {}
 
 typedef struct { int a; int b:4; int c; } struct_int_bitfield_int;
-// CHECK: define arm_aapcs_vfpcc void @test_test_vfp_stack_gpr_split_bitfield(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, i32 %k, [2 x i32], [3 x i32] %l.coerce)
+// CHECK: define arm_aapcs_vfpcc void @test_test_vfp_stack_gpr_split_bitfield(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, i32 %k, [3 x i32] %l.coerce)
 void test_test_vfp_stack_gpr_split_bitfield(double a, double b, double c, double d, double e, double f, double g, double h, double i, int j, int k, struct_int_bitfield_int l) {}
 
 // Note: this struct requires internal padding
 typedef struct { int x; long long y; } struct_int_long_long;
-// CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_4(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, [3 x i32], [2 x i64] %k.coerce)
+// CHECK: define arm_aapcs_vfpcc void @test_vfp_stack_gpr_split_4(double %a, double %b, double %c, double %d, double %e, double %f, double %g, double %h, double %i, i32 %j, [2 x i64] %k.coerce)
 void test_vfp_stack_gpr_split_4(double a, double b, double c, double d, double e, double f, double g, double h, double i, int j, struct_int_long_long k) {}
 
 // This very large struct (passed byval) uses up the GPRs, so no padding is needed
diff --git a/test/CodeGen/arm-asm-variable.c b/test/CodeGen/arm-asm-variable.c
index f874269..6868cb7 100644
--- a/test/CodeGen/arm-asm-variable.c
+++ b/test/CodeGen/arm-asm-variable.c
@@ -17,7 +17,7 @@
 		       : [_rl] "=&r" (rl), [_rh] "=&r" (rh)		\
 		       : [_p] "p" (p) : "memory");
 
-  // CHECK: call { i32, i32 } asm sideeffect "ldrexd$0, $1, [$2]", "={r1},={r2},r,~{memory}"(i64*
+  // CHECK: call { i32, i32 } asm sideeffect "ldrexd$0, $1, [$2]", "=&{r1},=&{r2},r,~{memory}"(i64*
 
   return r;
 }
diff --git a/test/CodeGen/arm-homogenous.c b/test/CodeGen/arm-homogenous.c
index 2ab6c10..3426d99 100644
--- a/test/CodeGen/arm-homogenous.c
+++ b/test/CodeGen/arm-homogenous.c
@@ -5,7 +5,7 @@
 // RUN:  -ffreestanding -emit-llvm -w -o - %s | FileCheck -check-prefix=CHECK64 %s
 
 // RUN: %clang_cc1 -triple arm64-linux-gnu -ffreestanding -emit-llvm -w -o - %s \
-// RUN:   | FileCheck --check-prefix=CHECK64-AAPCS %s
+// RUN:   | FileCheck --check-prefix=CHECK64 %s
 typedef long long int64_t;
 typedef unsigned int uint32_t;
 
@@ -176,9 +176,7 @@
 // CHECK: test_struct_of_four_doubles
 // CHECK: call arm_aapcs_vfpcc void @takes_struct_of_four_doubles(double {{.*}}, %struct.struct_of_four_doubles {{.*}}, %struct.struct_of_four_doubles {{.*}}, double {{.*}})
 // CHECK64: test_struct_of_four_doubles
-// CHECK64: call void @takes_struct_of_four_doubles(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [3 x float] undef, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}})
-// CHECK64-AAPCS: test_struct_of_four_doubles
-// CHECK64-AAPCS: call void @takes_struct_of_four_doubles(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [3 x float] undef, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}})
+// CHECK64: call void @takes_struct_of_four_doubles(double {{.*}}, [4 x double] {{.*}}, [4 x double] {{.*}}, double {{.*}})
   takes_struct_of_four_doubles(3.0, g_s4d, g_s4d, 4.0);
 }
 
@@ -212,9 +210,7 @@
 // CHECK: test_struct_of_vecs
 // CHECK: call arm_aapcs_vfpcc void @takes_struct_of_vecs(double {{.*}}, %struct.struct_of_vecs {{.*}}, %struct.struct_of_vecs {{.*}}, double {{.*}})
 // CHECK64: test_struct_of_vecs
-// CHECK64: call void @takes_struct_of_vecs(double {{.*}}, <8 x i8> {{.*}}, <4 x i16> {{.*}}, <8 x i8> {{.*}}, <4 x i16> {{.*}}, [3 x float] undef, <8 x i8> {{.*}}, <4 x i16> {{.*}}, <8 x i8> {{.*}}, <4 x i16> {{.*}}, double {{.*}})
-// CHECK64-AAPCS: test_struct_of_vecs
-// CHECK64-AAPCS: call void @takes_struct_of_vecs(double {{.*}}, <8 x i8> {{.*}}, <4 x i16> {{.*}}, <8 x i8> {{.*}}, <4 x i16> {{.*}}, [3 x float] undef, <8 x i8> {{.*}}, <4 x i16> {{.*}}, <8 x i8> {{.*}}, <4 x i16> {{.*}}, double {{.*}})
+// CHECK64: call void @takes_struct_of_vecs(double {{.*}}, [4 x <8 x i8>] {{.*}}, [4 x <8 x i8>] {{.*}}, double {{.*}})
   takes_struct_of_vecs(3.0, g_vec, g_vec, 4.0);
 }
 
diff --git a/test/CodeGen/arm-metadata.c b/test/CodeGen/arm-metadata.c
index 1cd9880..1f7756c 100644
--- a/test/CodeGen/arm-metadata.c
+++ b/test/CodeGen/arm-metadata.c
@@ -2,11 +2,11 @@
 // RUN: %clang_cc1 -triple armv7a-linux-gnueabi -emit-llvm -o - %s -fshort-enums | FileCheck -check-prefix=SHORT-ENUM %s
 // RUN: %clang_cc1 -triple armv7a-linux-gnueabi -emit-llvm -o - %s -fshort-wchar | FileCheck -check-prefix=SHORT-WCHAR %s
 
-// DEFAULT:  !{{[0-9]+}} = metadata !{i32 1, metadata !"wchar_size", i32 4}
-// DEFAULT:   !{{[0-9]+}} = metadata !{i32 1, metadata !"min_enum_size", i32 4}
+// DEFAULT:  !{{[0-9]+}} = !{i32 1, !"wchar_size", i32 4}
+// DEFAULT:   !{{[0-9]+}} = !{i32 1, !"min_enum_size", i32 4}
 
-// SHORT-WCHAR: !{{[0-9]+}} = metadata !{i32 1, metadata !"wchar_size", i32 2}
-// SHORT-WCHAR:   !{{[0-9]+}} = metadata !{i32 1, metadata !"min_enum_size", i32 4}
+// SHORT-WCHAR: !{{[0-9]+}} = !{i32 1, !"wchar_size", i32 2}
+// SHORT-WCHAR:   !{{[0-9]+}} = !{i32 1, !"min_enum_size", i32 4}
 
-// SHORT_ENUM:  !{{[0-9]+}} = metadata !{i32 1, metadata !"wchar_size", i32 4}
-// SHORT-ENUM:  !{{[0-9]+}} = metadata !{i32 1, metadata !"min_enum_size", i32 1}
+// SHORT_ENUM:  !{{[0-9]+}} = !{i32 1, !"wchar_size", i32 4}
+// SHORT-ENUM:  !{{[0-9]+}} = !{i32 1, !"min_enum_size", i32 1}
diff --git a/test/CodeGen/arm-pnaclcall.c b/test/CodeGen/arm-pnaclcall.c
deleted file mode 100644
index 2faac1c..0000000
--- a/test/CodeGen/arm-pnaclcall.c
+++ /dev/null
@@ -1,33 +0,0 @@
-// RUN: %clang_cc1 -triple armv7-unknown-nacl-gnueabi \
-// RUN:   -ffreestanding -mfloat-abi hard -target-cpu cortex-a8 \
-// RUN:   -emit-llvm -w -o - %s | FileCheck %s
-
-// Test that functions with pnaclcall attribute generate portable bitcode
-// like the le32 arch target
-
-typedef struct {
-  int a;
-  int b;
-} s1;
-// CHECK-LABEL: define i32 @f48(%struct.s1* byval %s)
-int __attribute__((pnaclcall)) f48(s1 s) { return s.a; }
-
-// CHECK-LABEL: define void @f49(%struct.s1* noalias sret %agg.result)
-s1 __attribute__((pnaclcall)) f49() { s1 s; s.a = s.b = 1; return s; }
-
-union simple_union {
-  int a;
-  char b;
-};
-// Unions should be passed as byval structs
-// CHECK-LABEL: define void @f50(%union.simple_union* byval %s)
-void __attribute__((pnaclcall)) f50(union simple_union s) {}
-
-typedef struct {
-  int b4 : 4;
-  int b3 : 3;
-  int b8 : 8;
-} bitfield1;
-// Bitfields should be passed as byval structs
-// CHECK-LABEL: define void @f51(%struct.bitfield1* byval %bf1)
-void __attribute__((pnaclcall)) f51(bitfield1 bf1) {}
diff --git a/test/CodeGen/arm64-aapcs-arguments.c b/test/CodeGen/arm64-aapcs-arguments.c
index 38ac522..ab302d4 100644
--- a/test/CodeGen/arm64-aapcs-arguments.c
+++ b/test/CodeGen/arm64-aapcs-arguments.c
@@ -17,7 +17,7 @@
 // stack in order to avoid holes. Make sure we get all of them, and not just the
 // first:
 
-// CHECK: void @test3(float %s0_s3.0, float %s0_s3.1, float %s0_s3.2, float %s0_s3.3, float %s4, [3 x float], [2 x double] %sp.coerce, [2 x double] %sp16.coerce)
+// CHECK: void @test3([4 x float] %s0_s3.coerce, float %s4, [4 x float] %sp.coerce, [4 x float] %sp16.coerce)
 typedef struct { float arr[4]; } HFA;
 void test3(HFA s0_s3, float s4, HFA sp, HFA sp16) {
 }
@@ -28,7 +28,7 @@
 // fp128] or something, but leaving them as-is retains more information for
 // users to debug.
 
-//  CHECK: void @test4(<16 x i8> %v0_v2.0, <16 x i8> %v0_v2.1, <16 x i8> %v0_v2.2, <16 x i8> %v3_v5.0, <16 x i8> %v3_v5.1, <16 x i8> %v3_v5.2, [2 x float], <16 x i8> %sp.0, <16 x i8> %sp.1, <16 x i8> %sp.2, double %sp48, <16 x i8> %sp64.0, <16 x i8> %sp64.1, <16 x i8> %sp64.2)
+//  CHECK: void @test4([3 x <16 x i8>] %v0_v2.coerce, [3 x <16 x i8>] %v3_v5.coerce, [3 x <16 x i8>] %sp.coerce, double %sp48, [3 x <16 x i8>] %sp64.coerce)
 typedef __attribute__((neon_vector_type(16))) signed char int8x16_t;
 typedef struct { int8x16_t arr[3]; } BigHFA;
 void test4(BigHFA v0_v2, BigHFA v3_v5, BigHFA sp, double sp48, BigHFA sp64) {
@@ -46,6 +46,6 @@
 __fp16 test_half(__fp16 A) { }
 
 // __fp16 is a base type for homogeneous floating-point aggregates for AArch64 (but not 32-bit ARM).
-// CHECK: define %struct.HFA_half @test_half_hfa(half %{{.*}}, half %{{.*}}, half %{{.*}}, half %{{.*}})
+// CHECK: define %struct.HFA_half @test_half_hfa([4 x half] %{{.*}})
 struct HFA_half { __fp16 a[4]; };
 struct HFA_half test_half_hfa(struct HFA_half A) { }
diff --git a/test/CodeGen/arm64-arguments.c b/test/CodeGen/arm64-arguments.c
index b2de08d..ae1ff98 100644
--- a/test/CodeGen/arm64-arguments.c
+++ b/test/CodeGen/arm64-arguments.c
@@ -123,8 +123,7 @@
 
 struct s32 { double x; };
 void f32(struct s32 s) { }
-// Expand Homogeneous Aggregate.
-// CHECK: @f32(double %{{.*}})
+// CHECK: @f32([1 x double] %{{.*}})
 
 // A composite type larger than 16 bytes should be passed indirectly.
 struct s33 { char buf[32*32]; };
@@ -197,7 +196,7 @@
 
 typedef __attribute__((neon_vector_type(4))) float float32x4_t;
 float32x4_t f35(int i, s35_with_align s1, s35_with_align s2) {
-// CHECK: define <4 x float> @f35(i32 %i, float %s1.0, float %s1.1, float %s1.2, float %s1.3, float %s2.0, float %s2.1, float %s2.2, float %s2.3)
+// CHECK: define <4 x float> @f35(i32 %i, [4 x float] %s1.coerce, [4 x float] %s2.coerce)
 // CHECK: %s1 = alloca %struct.s35, align 16
 // CHECK: %s2 = alloca %struct.s35, align 16
 // CHECK: %[[a:.*]] = bitcast %struct.s35* %s1 to <4 x float>*
@@ -598,24 +597,24 @@
 __attribute__ ((noinline))
 int f40_split(int i, int i2, int i3, int i4, int i5, int i6, int i7,
               s40_no_align s1, s40_no_align s2) {
-// CHECK: define i32 @f40_split(i32 %i, i32 %i2, i32 %i3, i32 %i4, i32 %i5, i32 %i6, i32 %i7, [1 x i32], [2 x i64] %s1.coerce, [2 x i64] %s2.coerce)
+// CHECK: define i32 @f40_split(i32 %i, i32 %i2, i32 %i3, i32 %i4, i32 %i5, i32 %i6, i32 %i7, [2 x i64] %s1.coerce, [2 x i64] %s2.coerce)
   return s1.i + s2.i + i + i2 + i3 + i4 + i5 + i6 + i7 + s1.s + s2.s;
 }
 int caller40_split() {
 // CHECK: define i32 @caller40_split()
-// CHECK: call i32 @f40_split(i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, [1 x i32] undef, [2 x i64] %{{.*}} [2 x i64] %{{.*}})
+// CHECK: call i32 @f40_split(i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, [2 x i64] %{{.*}} [2 x i64] %{{.*}})
   return f40_split(1, 2, 3, 4, 5, 6, 7, g40, g40_2);
 }
 
 __attribute__ ((noinline))
 int f41_split(int i, int i2, int i3, int i4, int i5, int i6, int i7,
               s41_with_align s1, s41_with_align s2) {
-// CHECK: define i32 @f41_split(i32 %i, i32 %i2, i32 %i3, i32 %i4, i32 %i5, i32 %i6, i32 %i7, [1 x i32], i128 %s1.coerce, i128 %s2.coerce)
+// CHECK: define i32 @f41_split(i32 %i, i32 %i2, i32 %i3, i32 %i4, i32 %i5, i32 %i6, i32 %i7, i128 %s1.coerce, i128 %s2.coerce)
   return s1.i + s2.i + i + i2 + i3 + i4 + i5 + i6 + i7 + s1.s + s2.s;
 }
 int caller41_split() {
 // CHECK: define i32 @caller41_split()
-// CHECK: call i32 @f41_split(i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, [1 x i32] undef, i128 %{{.*}}, i128 %{{.*}})
+// CHECK: call i32 @f41_split(i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i128 %{{.*}}, i128 %{{.*}})
   return f41_split(1, 2, 3, 4, 5, 6, 7, g41, g41_2);
 }
 
@@ -642,7 +641,7 @@
 
 float test_hfa_call(struct HFA *a) {
 // CHECK-LABEL: define float @test_hfa_call(%struct.HFA* %a)
-// CHECK: call float (i32, ...)* @test_hfa(i32 1, [2 x double] {{.*}})
+// CHECK: call float (i32, ...)* @test_hfa(i32 1, [4 x float] {{.*}})
   test_hfa(1, *a);
 }
 
diff --git a/test/CodeGen/arm64_vMaxMin.c b/test/CodeGen/arm64_vMaxMin.c
index 5f77b6c..a1dd2ad 100644
--- a/test/CodeGen/arm64_vMaxMin.c
+++ b/test/CodeGen/arm64_vMaxMin.c
@@ -7,75 +7,75 @@
 
 // Test a represntative sample of 8 and 16, signed and unsigned, 64 and 128 bit reduction
 int8_t test_vmaxv_s8(int8x8_t a1) {
-  // CHECK: test_vmaxv_s8
+  // CHECK-LABEL: define i8 @test_vmaxv_s8(
   return vmaxv_s8(a1);
-  // CHECK @llvm.aarch64.neon.smaxv.i32.v8i8
+  // CHECK: call i32 @llvm.aarch64.neon.smaxv.i32.v8i8(
 }
 
 uint16_t test_vminvq_u16(uint16x8_t a1) {
-  // CHECK: test_vminvq_u16
+  // CHECK-LABEL: define i16 @test_vminvq_u16(
   return vminvq_u16(a1);
-  // CHECK llvm.aarch64.neon.uminv.i16.v8i16
+  // CHECK: call i32 @llvm.aarch64.neon.uminv.i32.v8i16(
 }
 
 // Test a represntative sample of 8 and 16, signed and unsigned, 64 and 128 bit pairwise
 uint8x8_t test_vmin_u8(uint8x8_t a1, uint8x8_t a2) {
-  // CHECK: test_vmin_u8
+  // CHECK-LABEL: define <8 x i8> @test_vmin_u8(
   return vmin_u8(a1, a2);
-  // CHECK llvm.aarch64.neon.umin.v8i8
+  // CHECK: call <8 x i8> @llvm.aarch64.neon.umin.v8i8(
 }
 
 uint8x16_t test_vminq_u8(uint8x16_t a1, uint8x16_t a2) {
-  // CHECK: test_vminq_u8
+  // CHECK-LABEL: define <16 x i8> @test_vminq_u8(
   return vminq_u8(a1, a2);
-  // CHECK llvm.aarch64.neon.umin.v16i8
+  // CHECK: call <16 x i8> @llvm.aarch64.neon.umin.v16i8(
 }
 
 int16x8_t test_vmaxq_s16(int16x8_t a1, int16x8_t a2) {
-  // CHECK: test_vmaxq_s16
+  // CHECK-LABEL: define <8 x i16> @test_vmaxq_s16(
   return vmaxq_s16(a1, a2);
-  // CHECK llvm.aarch64.neon.smax.v8i16
+  // CHECK: call <8 x i16> @llvm.aarch64.neon.smax.v8i16(
 }
 
 // Test the more complicated cases of [suf]32 and f64
 float64x2_t test_vmaxq_f64(float64x2_t a1, float64x2_t a2) {
-  // CHECK: test_vmaxq_f64
+  // CHECK-LABEL: define <2 x double> @test_vmaxq_f64(
   return vmaxq_f64(a1, a2);
-  // CHECK llvm.aarch64.neon.fmax.v2f64
+  // CHECK: call <2 x double> @llvm.aarch64.neon.fmax.v2f64(
 }
 
 float32x4_t test_vmaxq_f32(float32x4_t a1, float32x4_t a2) {
-  // CHECK: test_vmaxq_f32
+  // CHECK-LABEL: define <4 x float> @test_vmaxq_f32(
   return vmaxq_f32(a1, a2);
-  // CHECK llvm.aarch64.neon.fmax.v4f32
+  // CHECK: call <4 x float> @llvm.aarch64.neon.fmax.v4f32(
 }
 
 float64x2_t test_vminq_f64(float64x2_t a1, float64x2_t a2) {
-  // CHECK: test_vminq_f64
+  // CHECK-LABEL: define <2 x double> @test_vminq_f64(
   return vminq_f64(a1, a2);
-  // CHECK llvm.aarch64.neon.fmin.v2f64
+  // CHECK: call <2 x double> @llvm.aarch64.neon.fmin.v2f64(
 }
 
 float32x2_t test_vmax_f32(float32x2_t a1, float32x2_t a2) {
-  // CHECK: test_vmax_f32
+  // CHECK-LABEL: define <2 x float> @test_vmax_f32(
   return vmax_f32(a1, a2);
-  // CHECK llvm.aarch64.neon.fmax.v2f32
+  // CHECK: call <2 x float> @llvm.aarch64.neon.fmax.v2f32(
 }
 
 int32x2_t test_vmax_s32(int32x2_t a1, int32x2_t a2) {
-  // CHECK: test_vmax_s32
+  // CHECK-LABEL: define <2 x i32> @test_vmax_s32(
   return vmax_s32(a1, a2);
-  // CHECK llvm.aarch64.neon.smax.v2i32
+  // CHECK: call <2 x i32> @llvm.aarch64.neon.smax.v2i32(
 }
 
 uint32x2_t test_vmin_u32(uint32x2_t a1, uint32x2_t a2) {
-  // CHECK: test_vmin_u32
+  // CHECK-LABEL: define <2 x i32> @test_vmin_u32(
   return vmin_u32(a1, a2);
-  // CHECK llvm.aarch64.neon.umin.v2i32
+  // CHECK: call <2 x i32> @llvm.aarch64.neon.umin.v2i32(
 }
 
 float32_t test_vmaxnmv_f32(float32x2_t a1) {
-  // CHECK: test_vmaxnmv_f32
+  // CHECK-LABEL: define float @test_vmaxnmv_f32(
   return vmaxnmv_f32(a1);
   // CHECK: llvm.aarch64.neon.fmaxnmv.f32.v2f32
   // CHECK-NEXT: ret
@@ -93,34 +93,34 @@
 #endif
 
 float32_t test_vmaxnmvq_f32(float32x4_t a1) {
-  // CHECK: test_vmaxnmvq_f32
+  // CHECK-LABEL: define float @test_vmaxnmvq_f32(
   return vmaxnmvq_f32(a1);
-  // CHECK: llvm.aarch64.neon.fmaxnmv.f32.v4f32
+  // CHECK: call float @llvm.aarch64.neon.fmaxnmv.f32.v4f32(
   // CHECK-NEXT: ret
 }
 
 float32_t test_vmaxv_f32(float32x2_t a1) {
-  // CHECK: test_vmaxv_f32
+  // CHECK-LABEL: define float @test_vmaxv_f32(
   return vmaxv_f32(a1);
-  // CHECK: llvm.aarch64.neon.fmaxv.f32.v2f32
+  // CHECK: call float @llvm.aarch64.neon.fmaxv.f32.v2f32(
   // FIXME check that the 2nd and 3rd arguments are the same V register below
   // CHECK-CODEGEN: fmaxp.2s
   // CHECK-NEXT: ret
 }
 
 int32_t test_vmaxv_s32(int32x2_t a1) {
-  // CHECK: test_vmaxv_s32
+  // CHECK-LABEL: define i32 @test_vmaxv_s32(
   return vmaxv_s32(a1);
-  // CHECK: llvm.aarch64.neon.smaxv.i32.v2i32
+  // CHECK: call i32 @llvm.aarch64.neon.smaxv.i32.v2i32(
   // FIXME check that the 2nd and 3rd arguments are the same V register below
   // CHECK-CODEGEN: smaxp.2s
   // CHECK-NEXT: ret
 }
 
 uint32_t test_vmaxv_u32(uint32x2_t a1) {
-  // CHECK: test_vmaxv_u32
+  // CHECK-LABEL: define i32 @test_vmaxv_u32(
   return vmaxv_u32(a1);
-  // CHECK: llvm.aarch64.neon.umaxv.i32.v2i32
+  // CHECK: call i32 @llvm.aarch64.neon.umaxv.i32.v2i32(
   // FIXME check that the 2nd and 3rd arguments are the same V register below
   // CHECK-CODEGEN: umaxp.2s
   // CHECK-NEXT: ret
@@ -137,23 +137,23 @@
 #endif
 
 float32_t test_vmaxvq_f32(float32x4_t a1) {
-  // CHECK: test_vmaxvq_f32
+  // CHECK-LABEL: define float @test_vmaxvq_f32(
   return vmaxvq_f32(a1);
-  // CHECK: llvm.aarch64.neon.fmaxv.f32.v4f32
+  // CHECK: call float @llvm.aarch64.neon.fmaxv.f32.v4f32(
   // CHECK-NEXT: ret
 }
 
 float32_t test_vminnmv_f32(float32x2_t a1) {
-  // CHECK: test_vminnmv_f32
+  // CHECK-LABEL: define float @test_vminnmv_f32(
   return vminnmv_f32(a1);
-  // CHECK: llvm.aarch64.neon.fminnmv.f32.v2f32
+  // CHECK: call float @llvm.aarch64.neon.fminnmv.f32.v2f32(
   // CHECK-NEXT: ret
 }
 
 float32_t test_vminvq_f32(float32x4_t a1) {
-  // CHECK: test_vminvq_f32
+  // CHECK-LABEL: define float @test_vminvq_f32(
   return vminvq_f32(a1);
-  // CHECK: llvm.aarch64.neon.fminv.f32.v4f32
+  // CHECK: call float @llvm.aarch64.neon.fminv.f32.v4f32(
   // CHECK-NEXT: ret
 }
 
@@ -169,31 +169,31 @@
 #endif
 
 float32_t test_vminnmvq_f32(float32x4_t a1) {
-  // CHECK: test_vminnmvq_f32
+  // CHECK-LABEL: define float @test_vminnmvq_f32(
   return vminnmvq_f32(a1);
-  // CHECK: llvm.aarch64.neon.fminnmv.f32.v4f32
+  // CHECK: call float @llvm.aarch64.neon.fminnmv.f32.v4f32(
   // CHECK-NEXT: ret
 }
 
 float32_t test_vminv_f32(float32x2_t a1) {
-  // CHECK: test_vminv_f32
+  // CHECK-LABEL: define float @test_vminv_f32(
   return vminv_f32(a1);
-  // CHECK: llvm.aarch64.neon.fminv.f32.v2f32
+  // CHECK: call float @llvm.aarch64.neon.fminv.f32.v2f32(
   // CHECK-NEXT: ret
 }
 
 int32_t test_vminv_s32(int32x2_t a1) {
-  // CHECK: test_vminv_s32
+  // CHECK-LABEL: define i32 @test_vminv_s32(
   return vminv_s32(a1);
-  // CHECK: llvm.aarch64.neon.sminv.i32.v2i32
+  // CHECK: call i32 @llvm.aarch64.neon.sminv.i32.v2i32(
   // CHECK-CODEGEN: sminp.2s
   // CHECK-NEXT: ret
 }
 
 uint32_t test_vminv_u32(uint32x2_t a1) {
-  // CHECK: test_vminv_u32
+  // CHECK-LABEL: define i32 @test_vminv_u32(
   return vminv_u32(a1);
-  // CHECK: llvm.aarch64.neon.fminv.f32.v2f32
+  // CHECK: call i32 @llvm.aarch64.neon.uminv.i32.v2i32(
 }
 
 // FIXME punt on this for now; don't forget to fix CHECKs
diff --git a/test/CodeGen/asan-globals.cpp b/test/CodeGen/asan-globals.cpp
index 4fae9a4..20c1fa7 100644
--- a/test/CodeGen/asan-globals.cpp
+++ b/test/CodeGen/asan-globals.cpp
@@ -15,23 +15,23 @@
 }
 
 // CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
-// CHECK: ![[EXTRA_GLOBAL]] = metadata !{{{.*}} metadata ![[EXTRA_GLOBAL_LOC:[0-9]+]], metadata !"extra_global", i1 false, i1 false}
-// CHECK: ![[EXTRA_GLOBAL_LOC]] = metadata !{metadata !"{{.*}}extra-source.cpp", i32 1, i32 5}
-// CHECK: ![[GLOBAL]] = metadata !{{{.*}} metadata ![[GLOBAL_LOC:[0-9]+]], metadata !"global", i1 false, i1 false}
-// CHECK: ![[GLOBAL_LOC]] = metadata !{metadata !"{{.*}}asan-globals.cpp", i32 8, i32 5}
-// CHECK: ![[DYN_INIT_GLOBAL]] = metadata !{{{.*}} metadata ![[DYN_INIT_LOC:[0-9]+]], metadata !"dyn_init_global", i1 true, i1 false}
-// CHECK: ![[DYN_INIT_LOC]] = metadata !{metadata !"{{.*}}asan-globals.cpp", i32 9, i32 5}
-// CHECK: ![[BLACKLISTED_GLOBAL]] = metadata !{{{.*}}, null, null, i1 false, i1 true}
-// CHECK: ![[STATIC_VAR]] = metadata !{{{.*}} metadata ![[STATIC_LOC:[0-9]+]], metadata !"static_var", i1 false, i1 false}
-// CHECK: ![[STATIC_LOC]] = metadata !{metadata !"{{.*}}asan-globals.cpp", i32 13, i32 14}
-// CHECK: ![[LITERAL]] = metadata !{{{.*}} metadata ![[LITERAL_LOC:[0-9]+]], metadata !"<string literal>", i1 false, i1 false}
-// CHECK: ![[LITERAL_LOC]] = metadata !{metadata !"{{.*}}asan-globals.cpp", i32 14, i32 25}
+// CHECK: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], !"extra_global", i1 false, i1 false}
+// CHECK: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
+// CHECK: ![[GLOBAL]] = !{{{.*}} ![[GLOBAL_LOC:[0-9]+]], !"global", i1 false, i1 false}
+// CHECK: ![[GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 8, i32 5}
+// CHECK: ![[DYN_INIT_GLOBAL]] = !{{{.*}} ![[DYN_INIT_LOC:[0-9]+]], !"dyn_init_global", i1 true, i1 false}
+// CHECK: ![[DYN_INIT_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 9, i32 5}
+// CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
+// CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 false, i1 false}
+// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 13, i32 14}
+// CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"<string literal>", i1 false, i1 false}
+// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 25}
 
 // BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
-// BLACKLIST-SRC: ![[EXTRA_GLOBAL]] = metadata !{{{.*}} metadata ![[EXTRA_GLOBAL_LOC:[0-9]+]], metadata !"extra_global", i1 false, i1 false}
-// BLACKLIST-SRC: ![[EXTRA_GLOBAL_LOC]] = metadata !{metadata !"{{.*}}extra-source.cpp", i32 1, i32 5}
-// BLACKLIST-SRC: ![[GLOBAL]] = metadata !{{{.*}} null, null, i1 false, i1 true}
-// BLACKLIST-SRC: ![[DYN_INIT_GLOBAL]] = metadata !{{{.*}} null, null, i1 true, i1 true}
-// BLACKLIST-SRC: ![[BLACKLISTED_GLOBAL]] = metadata !{{{.*}}, null, null, i1 false, i1 true}
-// BLACKLIST-SRC: ![[STATIC_VAR]] = metadata !{{{.*}} null, null, i1 false, i1 true}
-// BLACKLIST-SRC: ![[LITERAL]] = metadata !{{{.*}} null, null, i1 false, i1 true}
+// BLACKLIST-SRC: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], !"extra_global", i1 false, i1 false}
+// BLACKLIST-SRC: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
+// BLACKLIST-SRC: ![[GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
+// BLACKLIST-SRC: ![[DYN_INIT_GLOBAL]] = !{{{.*}} null, null, i1 true, i1 true}
+// BLACKLIST-SRC: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
+// BLACKLIST-SRC: ![[STATIC_VAR]] = !{{{.*}} null, null, i1 false, i1 true}
+// BLACKLIST-SRC: ![[LITERAL]] = !{{{.*}} null, null, i1 false, i1 true}
diff --git a/test/CodeGen/asm-errors.c b/test/CodeGen/asm-errors.c
index 438c82b..05751a8 100644
--- a/test/CodeGen/asm-errors.c
+++ b/test/CodeGen/asm-errors.c
@@ -3,6 +3,12 @@
 // RUN: true
 // UN: not %clang_cc1 -triple i386-apple-darwin10 -emit-obj %s -o /dev/null > %t 2>&1
 // UN: FileCheck %s < %t
+// RUN: %clang_cc1 -triple i386-apple-darwin10 -emit-llvm-bc %s -o %t.bc
+// RUN: %clang_cc1 -triple i386-apple-darwin10 -emit-obj %t.bc -o /dev/null 2>&1 | \
+// RUN:   FileCheck --check-prefix=CRASH-REPORT %s
+// CRASH-REPORT: <inline asm>:
+// CRASH-REPORT: error: invalid instruction mnemonic 'abc'
+// CRASH-REPORT-NOT: note: diagnostic msg:
 
 int test1(int X) {
 // CHECK: error: invalid instruction mnemonic 'abc'
diff --git a/test/CodeGen/asm-reg-var-local.c b/test/CodeGen/asm-reg-var-local.c
index 9060e12..44417d4 100644
--- a/test/CodeGen/asm-reg-var-local.c
+++ b/test/CodeGen/asm-reg-var-local.c
@@ -2,6 +2,7 @@
 // Exercise various use cases for local asm "register variables".
 
 int foo() {
+// CHECK-LABEL: define i32 @foo()
 // CHECK: [[A:%[a-zA-Z0-9]+]] = alloca i32
 
   register int a asm("rsi")=5;
@@ -22,3 +23,26 @@
 // CHECK:  [[TMP1:%[a-zA-Z0-9]+]] = load i32* [[A]]
 // CHECK:  ret i32 [[TMP1]]
 }
+
+int earlyclobber() {
+// CHECK-LABEL: define i32 @earlyclobber()
+// CHECK: [[A:%[a-zA-Z0-9]+]] = alloca i32
+
+  register int a asm("rsi")=5;
+// CHECK: store i32 5, i32* [[A]]
+
+  asm volatile("; %0 This asm defines rsi" : "=&r"(a));
+// CHECK: [[Z:%[a-zA-Z0-9]+]] = call i32 asm sideeffect "; $0 This asm defines rsi", "=&{rsi},~{dirflag},~{fpsr},~{flags}"()
+// CHECK: store i32 [[Z]], i32* [[A]]
+
+  a = 42;
+// CHECK:  store i32 42, i32* [[A]]
+
+  asm volatile("; %0 This asm uses rsi" : : "r"(a));
+// CHECK:  [[TMP:%[a-zA-Z0-9]+]] = load i32* [[A]]
+// CHECK:  call void asm sideeffect "; $0 This asm uses rsi", "{rsi},~{dirflag},~{fpsr},~{flags}"(i32 [[TMP]])
+
+  return a;
+// CHECK:  [[TMP1:%[a-zA-Z0-9]+]] = load i32* [[A]]
+// CHECK:  ret i32 [[TMP1]]
+}
diff --git a/test/CodeGen/asm.c b/test/CodeGen/asm.c
index 5dbc01b..038d346 100644
--- a/test/CodeGen/asm.c
+++ b/test/CodeGen/asm.c
@@ -248,3 +248,17 @@
   // CHECK: @t29
   // CHECK: call void asm sideeffect "movl %eax, $0", "*m,~{dirflag},~{fpsr},~{flags}"([1 x i32]* @t29_var)
 }
+
+void t30(int len) {
+  __asm__ volatile(""
+                   : "+&&rm"(len));
+  // CHECK: @t30
+  // CHECK: call void asm sideeffect "", "=*&rm,0,~{dirflag},~{fpsr},~{flags}"
+}
+
+void t31(int len) {
+  __asm__ volatile(""
+                   : "+%%rm"(len), "+rm"(len));
+  // CHECK: @t31
+  // CHECK: call void asm sideeffect "", "=*%rm,=*rm,0,1,~{dirflag},~{fpsr},~{flags}"
+}
diff --git a/test/CodeGen/atomic-ops.c b/test/CodeGen/atomic-ops.c
index 7bc45b6..559b135 100644
--- a/test/CodeGen/atomic-ops.c
+++ b/test/CodeGen/atomic-ops.c
@@ -383,14 +383,23 @@
 }
 int structAtomicCmpExchange() {
   // CHECK-LABEL: @structAtomicCmpExchange
+  // CHECK: %[[x_mem:.*]] = alloca i8
   _Bool x = __atomic_compare_exchange(&smallThing, &thing1, &thing2, 1, 5, 5);
-  // CHECK: call zeroext i1 @__atomic_compare_exchange(i32 3, {{.*}} @smallThing{{.*}} @thing1{{.*}} @thing2
+  // CHECK: %[[call1:.*]] = call zeroext i1 @__atomic_compare_exchange(i32 3, {{.*}} @smallThing{{.*}} @thing1{{.*}} @thing2
+  // CHECK: %[[zext1:.*]] = zext i1 %[[call1]] to i8
+  // CHECK: store i8 %[[zext1]], i8* %[[x_mem]], align 1
+  // CHECK: %[[x:.*]] = load i8* %[[x_mem]]
+  // CHECK: %[[x_bool:.*]] = trunc i8 %[[x]] to i1
+  // CHECK: %[[conv1:.*]] = zext i1 %[[x_bool]] to i32
 
   struct foo f = {0};
   struct foo g = {0};
   g.big[12] = 12;
   return x & __c11_atomic_compare_exchange_strong(&bigAtomic, &f, g, 5, 5);
-  // CHECK: call zeroext i1 @__atomic_compare_exchange(i32 512, i8* bitcast ({{.*}} @bigAtomic to i8*),
+  // CHECK: %[[call2:.*]] = call zeroext i1 @__atomic_compare_exchange(i32 512, i8* bitcast ({{.*}} @bigAtomic to i8*),
+  // CHECK: %[[conv2:.*]] = zext i1 %[[call2]] to i32
+  // CHECK: %[[and:.*]] = and i32 %[[conv1]], %[[conv2]]
+  // CHECK: ret i32 %[[and]]
 }
 
 // Check that no atomic operations are used in any initialisation of _Atomic
@@ -543,4 +552,51 @@
   // CHECK: = cmpxchg weak {{.*}} seq_cst seq_cst
 }
 
+int PR21643() {
+  return __atomic_or_fetch((int __attribute__((address_space(257))) *)0x308, 1,
+                           __ATOMIC_RELAXED);
+  // CHECK: %[[atomictmp:.*]] = alloca i32, align 4
+  // CHECK: %[[atomicdst:.*]] = alloca i32, align 4
+  // CHECK: store i32 1, i32* %[[atomictmp]]
+  // CHECK: %[[one:.*]] = load i32* %[[atomictmp]], align 4
+  // CHECK: %[[old:.*]] = atomicrmw or i32 addrspace(257)* inttoptr (i32 776 to i32 addrspace(257)*), i32 %[[one]] monotonic
+  // CHECK: %[[new:.*]] = or i32 %[[old]], %[[one]]
+  // CHECK: store i32 %[[new]], i32* %[[atomicdst]], align 4
+  // CHECK: %[[ret:.*]] = load i32* %[[atomicdst]], align 4
+  // CHECK: ret i32 %[[ret]]
+}
+
+int PR17306_1(volatile _Atomic(int) *i) {
+  // CHECK-LABEL: @PR17306_1
+  // CHECK:      %[[i_addr:.*]] = alloca i32
+  // CHECK-NEXT: %[[atomicdst:.*]] = alloca i32
+  // CHECK-NEXT: store i32* %i, i32** %[[i_addr]]
+  // CHECK-NEXT: %[[addr:.*]] = load i32** %[[i_addr]]
+  // CHECK-NEXT: %[[res:.*]] = load atomic volatile i32* %[[addr]] seq_cst
+  // CHECK-NEXT: store i32 %[[res]], i32* %[[atomicdst]]
+  // CHECK-NEXT: %[[retval:.*]] = load i32* %[[atomicdst]]
+  // CHECK-NEXT: ret i32 %[[retval]]
+  return __c11_atomic_load(i, memory_order_seq_cst);
+}
+
+int PR17306_2(volatile int *i, int value) {
+  // CHECK-LABEL: @PR17306_2
+  // CHECK:      %[[i_addr:.*]] = alloca i32*
+  // CHECK-NEXT: %[[value_addr:.*]] = alloca i32
+  // CHECK-NEXT: %[[atomictmp:.*]] = alloca i32
+  // CHECK-NEXT: %[[atomicdst:.*]] = alloca i32
+  // CHECK-NEXT: store i32* %i, i32** %[[i_addr]]
+  // CHECK-NEXT: store i32 %value, i32* %[[value_addr]]
+  // CHECK-NEXT: %[[i_lval:.*]] = load i32** %[[i_addr]]
+  // CHECK-NEXT: %[[value:.*]] = load i32* %[[value_addr]]
+  // CHECK-NEXT: store i32 %[[value]], i32* %[[atomictmp]]
+  // CHECK-NEXT: %[[value_lval:.*]] = load i32* %[[atomictmp]]
+  // CHECK-NEXT: %[[old_val:.*]] = atomicrmw volatile add i32* %[[i_lval]], i32 %[[value_lval]] seq_cst
+  // CHECK-NEXT: %[[new_val:.*]] = add i32 %[[old_val]], %[[value_lval]]
+  // CHECK-NEXT: store i32 %[[new_val]], i32* %[[atomicdst]]
+  // CHECK-NEXT: %[[retval:.*]] = load i32* %[[atomicdst]]
+  // CHECK-NEXT: ret i32 %[[retval]]
+  return __atomic_add_fetch(i, value, memory_order_seq_cst);
+}
+
 #endif
diff --git a/test/CodeGen/atomic_ops.c b/test/CodeGen/atomic_ops.c
index 910e9b9..050b543 100644
--- a/test/CodeGen/atomic_ops.c
+++ b/test/CodeGen/atomic_ops.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple mips-linux-gnu -emit-llvm %s -o - | FileCheck %s
 
 void foo(int x)
 {
@@ -7,12 +8,30 @@
   // Check that multiply / divides on atomics produce a cmpxchg loop
   i *= 2;
   // CHECK: mul nsw i32
-  // CHECK: cmpxchg i32*
+  // CHECK: {{(cmpxchg i32*|i1 @__atomic_compare_exchange\(i32 4,)}}
   i /= 2;
   // CHECK: sdiv i32
-  // CHECK: cmpxchg i32*
+  // CHECK: {{(cmpxchg i32*|i1 @__atomic_compare_exchange\(i32 4, )}}
   j /= x;
   // CHECK: sdiv i32
-  // CHECK: cmpxchg i16*
+  // CHECK: {{(cmpxchg i16*|i1 @__atomic_compare_exchange\(i32 2, )}}
 
 }
+
+extern _Atomic _Bool b;
+
+_Bool bar() {
+// CHECK-LABEL: @bar
+// CHECK: %[[load:.*]] = load atomic i8* @b seq_cst
+// CHECK: %[[tobool:.*]] = trunc i8 %[[load]] to i1
+// CHECK: ret i1 %[[tobool]]
+  return b;
+}
+
+extern _Atomic(_Complex int) x;
+
+void baz(int y) {
+// CHECK-LABEL: @baz
+// CHECK: {{store atomic|call void @__atomic_store}}
+  x += y;
+}
diff --git a/test/CodeGen/atomics-inlining.c b/test/CodeGen/atomics-inlining.c
index ec916e1..9cd2802 100644
--- a/test/CodeGen/atomics-inlining.c
+++ b/test/CodeGen/atomics-inlining.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple arm-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=ARM
+// RUN: %clang_cc1 -triple arm-linux-gnueabi -emit-llvm %s -o - | FileCheck %s -check-prefix=ARM
 // RUN: %clang_cc1 -triple powerpc-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=PPC32
 // RUN: %clang_cc1 -triple powerpc64-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=PPC64
 // RUN: %clang_cc1 -triple mipsel-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=MIPS32
@@ -31,17 +31,17 @@
   (void)__atomic_load(&a1, &a2, memory_order_seq_cst);
   (void)__atomic_store(&a1, &a2, memory_order_seq_cst);
 
-// ARM-LABEL: define arm_aapcscc void @test1
-// ARM: = call arm_aapcscc zeroext i8 @__atomic_load_1(i8* @c1
-// ARM: call arm_aapcscc void @__atomic_store_1(i8* @c1, i8 zeroext
-// ARM: = call arm_aapcscc zeroext i16 @__atomic_load_2(i8* bitcast (i16* @s1 to i8*)
-// ARM: call arm_aapcscc void @__atomic_store_2(i8* bitcast (i16* @s1 to i8*), i16 zeroext
-// ARM: = call arm_aapcscc i32 @__atomic_load_4(i8* bitcast (i32* @i1 to i8*)
-// ARM: call arm_aapcscc void @__atomic_store_4(i8* bitcast (i32* @i1 to i8*), i32
-// ARM: = call arm_aapcscc i64 @__atomic_load_8(i8* bitcast (i64* @ll1 to i8*)
-// ARM: call arm_aapcscc void @__atomic_store_8(i8* bitcast (i64* @ll1 to i8*), i64
-// ARM: call arm_aapcscc void @__atomic_load(i32 100, i8* getelementptr inbounds ([100 x i8]* @a1, i32 0, i32 0), i8* getelementptr inbounds ([100 x i8]* @a2, i32 0, i32 0)
-// ARM: call arm_aapcscc void @__atomic_store(i32 100, i8* getelementptr inbounds ([100 x i8]* @a1, i32 0, i32 0), i8* getelementptr inbounds ([100 x i8]* @a2, i32 0, i32 0)
+// ARM-LABEL: define{{.*}} void @test1
+// ARM: = call{{.*}} zeroext i8 @__atomic_load_1(i8* @c1
+// ARM: call{{.*}} void @__atomic_store_1(i8* @c1, i8 zeroext
+// ARM: = call{{.*}} zeroext i16 @__atomic_load_2(i8* bitcast (i16* @s1 to i8*)
+// ARM: call{{.*}} void @__atomic_store_2(i8* bitcast (i16* @s1 to i8*), i16 zeroext
+// ARM: = call{{.*}} i32 @__atomic_load_4(i8* bitcast (i32* @i1 to i8*)
+// ARM: call{{.*}} void @__atomic_store_4(i8* bitcast (i32* @i1 to i8*), i32
+// ARM: = call{{.*}} i64 @__atomic_load_8(i8* bitcast (i64* @ll1 to i8*)
+// ARM: call{{.*}} void @__atomic_store_8(i8* bitcast (i64* @ll1 to i8*), i64
+// ARM: call{{.*}} void @__atomic_load(i32 100, i8* getelementptr inbounds ([100 x i8]* @a1, i32 0, i32 0), i8* getelementptr inbounds ([100 x i8]* @a2, i32 0, i32 0)
+// ARM: call{{.*}} void @__atomic_store(i32 100, i8* getelementptr inbounds ([100 x i8]* @a1, i32 0, i32 0), i8* getelementptr inbounds ([100 x i8]* @a2, i32 0, i32 0)
 
 // PPC32-LABEL: define void @test1
 // PPC32: = load atomic i8* @c1 seq_cst
diff --git a/test/CodeGen/attr-optnone.c b/test/CodeGen/attr-optnone.c
index e7069b1..96493bf 100644
--- a/test/CodeGen/attr-optnone.c
+++ b/test/CodeGen/attr-optnone.c
@@ -1,12 +1,19 @@
 // RUN: %clang_cc1 -emit-llvm < %s > %t
 // RUN: FileCheck %s --check-prefix=PRESENT < %t
 // RUN: FileCheck %s --check-prefix=ABSENT  < %t
+// RUN: %clang_cc1 -emit-llvm -Os < %s > %t
+// RUN: FileCheck %s --check-prefix=PRESENT < %t
+// RUN: FileCheck %s --check-prefix=OPTSIZE < %t
+// RUN: %clang_cc1 -emit-llvm -Oz < %s > %t
+// RUN: FileCheck %s --check-prefix=PRESENT < %t
+// RUN: FileCheck %s --check-prefix=MINSIZE < %t
 
 __attribute__((always_inline))
 int test2() { return 0; }
-// PRESENT-DAG: @test2{{.*}}[[ATTR2:#[0-9]+]]
+// OPTSIZE: @test2{{.*}}[[ATTR2:#[0-9]+]]
+// MINSIZE: @test2{{.*}}[[ATTR2:#[0-9]+]]
 
-__attribute__((optnone)) __attribute__((minsize))
+__attribute__((optnone))
 int test3() { return 0; }
 // PRESENT-DAG: @test3{{.*}}[[ATTR3:#[0-9]+]]
 
@@ -23,3 +30,13 @@
 // Check that no 'optsize' or 'minsize' attributes appear.
 // ABSENT-NOT: optsize
 // ABSENT-NOT: minsize
+
+// With -Os, check that 'optsize' appears only on test2.
+// OPTSIZE-NOT: optsize
+// OPTSIZE: attributes [[ATTR2]] = { {{.*}}optsize{{.*}} }
+// OPTSIZE-NOT: optsize
+
+// With -Oz, check that 'minsize' appears only on test2.
+// MINSIZE-NOT: minsize
+// MINSIZE: attributes [[ATTR2]] = { {{.*}}minsize{{.*}} }
+// MINSIZE-NOT: minsize
diff --git a/test/CodeGen/avx-builtins.c b/test/CodeGen/avx-builtins.c
index 5b5b6a5..28e11ba 100644
--- a/test/CodeGen/avx-builtins.c
+++ b/test/CodeGen/avx-builtins.c
@@ -123,3 +123,27 @@
   // CHECK: shufflevector <8 x float> %{{.*}}, <8 x float> %{{.*}}, <8 x i32> <i32 8, i32 1, i32 10, i32 3, i32 12, i32 13, i32 6, i32 7>
   return _mm256_blend_ps(__a, __b, 0x35);
 }
+
+__m256i test_256_insert_epi8(__m256i __a) {
+  // CHECK-LABEL: @test_256_insert_epi8
+  // CHECK: insertelement <32 x i8> {{.*}}, i8 {{.*}}, i32 {{.*}}
+  return _mm256_insert_epi8(__a, 42, 3);
+}
+
+__m256i test_256_insert_epi16(__m256i __a) {
+  // CHECK-LABEL: @test_256_insert_epi16
+  // CHECK: insertelement <16 x i16> {{.*}}, i16 {{.*}}, i32 {{.*}}
+  return _mm256_insert_epi16(__a, 42, 3);
+}
+
+__m256i test_256_insert_epi32(__m256i __a) {
+  // CHECK-LABEL: @test_256_insert_epi32
+  // CHECK: insertelement <8 x i32> {{.*}}, i32 {{.*}}, i32 {{.*}}
+  return _mm256_insert_epi32(__a, 42, 3);
+}
+
+__m256i test_256_insert_epi64(__m256i __a) {
+  // CHECK-LABEL: @test_256_insert_epi64
+  // CHECK: insertelement <4 x i64> {{.*}}, i64 {{.*}}, i32 {{.*}}
+  return _mm256_insert_epi64(__a, 42, 3);
+}
diff --git a/test/CodeGen/avx2-builtins.c b/test/CodeGen/avx2-builtins.c
index 04825ff..27ee91e 100644
--- a/test/CodeGen/avx2-builtins.c
+++ b/test/CodeGen/avx2-builtins.c
@@ -96,7 +96,7 @@
 }
 
 __m256i test2_mm256_alignr_epi8(__m256i a, __m256i b) {
-  // CHECK: @llvm.x86.avx2.psrl.dq({{.*}}, i32 8)
+  // CHECK: shufflevector <32 x i8> %{{.*}}, <32 x i8> zeroinitializer, <32 x i32> <i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 32, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 27, i32 28, i32 29, i32 30, i32 31, i32 48>
   return _mm256_alignr_epi8(a, b, 17);
 }
 
@@ -462,7 +462,7 @@
 }
 
 __m256i test_mm256_slli_si256(__m256i a) {
-  // CHECK: @llvm.x86.avx2.psll.dq
+  // CHECK: shufflevector <32 x i8> zeroinitializer, <32 x i8> %{{.*}}, <32 x i32> <i32 13, i32 14, i32 15, i32 32, i32 33, i32 34, i32 35, i32 36, i32 37, i32 38, i32 39, i32 40, i32 41, i32 42, i32 43, i32 44, i32 29, i32 30, i32 31, i32 48, i32 49, i32 50, i32 51, i32 52, i32 53, i32 54, i32 55, i32 56, i32 57, i32 58, i32 59, i32 60>
   return _mm256_slli_si256(a, 3);
 }
 
@@ -517,7 +517,7 @@
 }
 
 __m256i test_mm256_srli_si256(__m256i a) {
-  // CHECK: @llvm.x86.avx2.psrl.dq
+  // CHECK: shufflevector <32 x i8> %{{.*}}, <32 x i8> zeroinitializer, <32 x i32> <i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 32, i32 33, i32 34, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 27, i32 28, i32 29, i32 30, i32 31, i32 48, i32 49, i32 50>
   return _mm256_srli_si256(a, 3);
 }
 
diff --git a/test/CodeGen/avx512bw-builtins.c b/test/CodeGen/avx512bw-builtins.c
index ada8465..f34c51e 100644
--- a/test/CodeGen/avx512bw-builtins.c
+++ b/test/CodeGen/avx512bw-builtins.c
@@ -25,3 +25,315 @@
   // CHECK: @llvm.x86.avx512.mask.pcmpeq.w.512
   return (__mmask32)_mm512_mask_cmpeq_epi16_mask(__u, __a, __b);
 }
+
+__mmask64 test_mm512_cmpgt_epi8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.b.512
+  return (__mmask64)_mm512_cmpgt_epi8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpgt_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.b.512
+  return (__mmask64)_mm512_mask_cmpgt_epi8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpgt_epi16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.w.512
+  return (__mmask32)_mm512_cmpgt_epi16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpgt_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.w.512
+  return (__mmask32)_mm512_mask_cmpgt_epi16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmpeq_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpeq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 0, i64 -1)
+  return (__mmask64)_mm512_cmpeq_epu8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpeq_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpeq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 0, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmpeq_epu8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpeq_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpeq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 0, i32 -1)
+  return (__mmask32)_mm512_cmpeq_epu16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpeq_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpeq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 0, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmpeq_epu16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmpgt_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 6, i64 -1)
+  return (__mmask64)_mm512_cmpgt_epu8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpgt_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 6, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmpgt_epu8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpgt_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 6, i32 -1)
+  return (__mmask32)_mm512_cmpgt_epu16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpgt_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 6, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmpgt_epu16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmpge_epi8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 5, i64 -1)
+  return (__mmask64)_mm512_cmpge_epi8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpge_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 5, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmpge_epi8_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmpge_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 5, i64 -1)
+  return (__mmask64)_mm512_cmpge_epu8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpge_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 5, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmpge_epu8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpge_epi16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 5, i32 -1)
+  return (__mmask32)_mm512_cmpge_epi16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpge_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 5, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmpge_epi16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpge_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 5, i32 -1)
+  return (__mmask32)_mm512_cmpge_epu16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpge_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 5, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmpge_epu16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmple_epi8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 2, i64 -1)
+  return (__mmask64)_mm512_cmple_epi8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmple_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 2, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmple_epi8_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmple_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 2, i64 -1)
+  return (__mmask64)_mm512_cmple_epu8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmple_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 2, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmple_epu8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmple_epi16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 2, i32 -1)
+  return (__mmask32)_mm512_cmple_epi16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmple_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 2, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmple_epi16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmple_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 2, i32 -1)
+  return (__mmask32)_mm512_cmple_epu16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmple_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 2, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmple_epu16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmplt_epi8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 1, i64 -1)
+  return (__mmask64)_mm512_cmplt_epi8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmplt_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 1, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmplt_epi8_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmplt_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 1, i64 -1)
+  return (__mmask64)_mm512_cmplt_epu8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmplt_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 1, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmplt_epu8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmplt_epi16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 1, i32 -1)
+  return (__mmask32)_mm512_cmplt_epi16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmplt_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 1, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmplt_epi16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmplt_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 1, i32 -1)
+  return (__mmask32)_mm512_cmplt_epu16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmplt_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 1, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmplt_epu16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmpneq_epi8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 4, i64 -1)
+  return (__mmask64)_mm512_cmpneq_epi8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpneq_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 4, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmpneq_epi8_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmpneq_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 4, i64 -1)
+  return (__mmask64)_mm512_cmpneq_epu8_mask(__a, __b);
+}
+
+__mmask64 test_mm512_mask_cmpneq_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 4, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmpneq_epu8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpneq_epi16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 4, i32 -1)
+  return (__mmask32)_mm512_cmpneq_epi16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpneq_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 4, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmpneq_epi16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm512_cmpneq_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 4, i32 -1)
+  return (__mmask32)_mm512_cmpneq_epu16_mask(__a, __b);
+}
+
+__mmask32 test_mm512_mask_cmpneq_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 4, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmpneq_epu16_mask(__u, __a, __b);
+}
+
+__mmask64 test_mm512_cmp_epi8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 7, i64 -1)
+  return (__mmask64)_mm512_cmp_epi8_mask(__a, __b, 7);
+}
+
+__mmask64 test_mm512_mask_cmp_epi8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 7, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmp_epi8_mask(__u, __a, __b, 7);
+}
+
+__mmask64 test_mm512_cmp_epu8_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 7, i64 -1)
+  return (__mmask64)_mm512_cmp_epu8_mask(__a, __b, 7);
+}
+
+__mmask64 test_mm512_mask_cmp_epu8_mask(__mmask64 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.512(<64 x i8> {{.*}}, <64 x i8> {{.*}}, i8 7, i64 {{.*}})
+  return (__mmask64)_mm512_mask_cmp_epu8_mask(__u, __a, __b, 7);
+}
+
+__mmask32 test_mm512_cmp_epi16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 7, i32 -1)
+  return (__mmask32)_mm512_cmp_epi16_mask(__a, __b, 7);
+}
+
+__mmask32 test_mm512_mask_cmp_epi16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 7, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmp_epi16_mask(__u, __a, __b, 7);
+}
+
+__mmask32 test_mm512_cmp_epu16_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 7, i32 -1)
+  return (__mmask32)_mm512_cmp_epu16_mask(__a, __b, 7);
+}
+
+__mmask32 test_mm512_mask_cmp_epu16_mask(__mmask32 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.512(<32 x i16> {{.*}}, <32 x i16> {{.*}}, i8 7, i32 {{.*}})
+  return (__mmask32)_mm512_mask_cmp_epu16_mask(__u, __a, __b, 7);
+}
diff --git a/test/CodeGen/avx512er-builtins.c b/test/CodeGen/avx512er-builtins.c
new file mode 100644
index 0000000..993f177
--- /dev/null
+++ b/test/CodeGen/avx512er-builtins.c
@@ -0,0 +1,346 @@
+// RUN: %clang_cc1 %s -O0 -triple=x86_64-apple-darwin -ffreestanding -target-feature +avx512f -target-feature +avx512er -emit-llvm -o - -Werror | FileCheck %s
+
+#include <immintrin.h>
+
+__m512d test_mm512_rsqrt28_round_pd(__m512d a) {
+  // CHECK-LABEL: @test_mm512_rsqrt28_round_pd
+  // CHECK: @llvm.x86.avx512.rsqrt28.pd
+  return _mm512_rsqrt28_round_pd(a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_mask_rsqrt28_round_pd(__m512d s, __mmask8 m, __m512d a) {
+  // check-label: @test_mm512_mask_rsqrt28_round_pd
+  // check: @llvm.x86.avx512.rsqrt28.pd
+  return _mm512_mask_rsqrt28_round_pd(s, m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_maskz_rsqrt28_round_pd(__mmask8 m, __m512d a) {
+  // check-label: @test_mm512_maskz_rsqrt28_round_pd
+  // check: @llvm.x86.avx512.rsqrt28.pd
+  return _mm512_maskz_rsqrt28_round_pd(m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_rsqrt28_pd(__m512d a) {
+  // CHECK-LABEL: @test_mm512_rsqrt28_pd
+  // CHECK: @llvm.x86.avx512.rsqrt28.pd
+  return _mm512_rsqrt28_pd(a);
+}
+
+__m512d test_mm512_mask_rsqrt28_pd(__m512d s, __mmask8 m, __m512d a) {
+  // check-label: @test_mm512_mask_rsqrt28_pd
+  // check: @llvm.x86.avx512.rsqrt28.pd
+  return _mm512_mask_rsqrt28_pd(s, m, a);
+}
+
+__m512d test_mm512_maskz_rsqrt28_pd(__mmask8 m, __m512d a) {
+  // check-label: @test_mm512_maskz_rsqrt28_pd
+  // check: @llvm.x86.avx512.rsqrt28.pd
+  return _mm512_maskz_rsqrt28_pd(m, a);
+}
+
+__m512 test_mm512_rsqrt28_round_ps(__m512 a) {
+  // CHECK-LABEL: @test_mm512_rsqrt28_round_ps
+  // CHECK: @llvm.x86.avx512.rsqrt28.ps
+  return _mm512_rsqrt28_round_ps(a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_mask_rsqrt28_round_ps(__m512 s, __mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_mask_rsqrt28_round_ps
+  // CHECK: @llvm.x86.avx512.rsqrt28.ps
+  return _mm512_mask_rsqrt28_round_ps(s, m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_maskz_rsqrt28_round_ps(__mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_maskz_rsqrt28_round_ps
+  // CHECK: @llvm.x86.avx512.rsqrt28.ps
+  return _mm512_maskz_rsqrt28_round_ps(m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_rsqrt28_ps(__m512 a) {
+  // CHECK-LABEL: @test_mm512_rsqrt28_ps
+  // CHECK: @llvm.x86.avx512.rsqrt28.ps
+  return _mm512_rsqrt28_ps(a);
+}
+
+__m512 test_mm512_mask_rsqrt28_ps(__m512 s, __mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_mask_rsqrt28_ps
+  // CHECK: @llvm.x86.avx512.rsqrt28.ps
+  return _mm512_mask_rsqrt28_ps(s, m, a);
+}
+
+__m512 test_mm512_maskz_rsqrt28_ps(__mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_maskz_rsqrt28_ps
+  // CHECK: @llvm.x86.avx512.rsqrt28.ps
+  return _mm512_maskz_rsqrt28_ps(m, a);
+}
+
+__m128 test_mm_rsqrt28_round_ss(__m128 a, __m128 b) {
+  // check-label: @test_mm_rsqrt28_round_ss
+  // check: @llvm.x86.avx512.rsqrt28.ss
+  return _mm_rsqrt28_round_ss(a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128 test_mm_mask_rsqrt28_round_ss(__m128 s, __mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_mask_rsqrt28_round_ss
+  // check: @llvm.x86.avx512.rsqrt28.ss
+  return _mm_mask_rsqrt28_round_ss(s, m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128 test_mm_maskz_rsqrt28_round_ss(__mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_maskz_rsqrt28_round_ss
+  // check: @llvm.x86.avx512.rsqrt28.ss
+  return _mm_maskz_rsqrt28_round_ss(m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128 test_mm_rsqrt28_ss(__m128 a, __m128 b) {
+  // check-label: @test_mm_rsqrt28_ss
+  // check: @llvm.x86.avx512.rsqrt28.ss
+  return _mm_rsqrt28_ss(a, b);
+}
+
+__m128 test_mm_mask_rsqrt28_ss(__m128 s, __mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_mask_rsqrt28_ss
+  // check: @llvm.x86.avx512.rsqrt28.ss
+  return _mm_mask_rsqrt28_ss(s, m, a, b);
+}
+
+__m128 test_mm_maskz_rsqrt28_ss(__mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_maskz_rsqrt28_ss
+  // check: @llvm.x86.avx512.rsqrt28.ss
+  return _mm_maskz_rsqrt28_ss(m, a, b);
+}
+
+__m128d test_mm_rsqrt28_round_sd(__m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_rsqrt28_round_sd
+  // CHECK: @llvm.x86.avx512.rsqrt28.sd
+  return _mm_rsqrt28_round_sd(a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128d test_mm_mask_rsqrt28_round_sd(__m128d s, __mmask8 m, __m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_mask_rsqrt28_round_sd
+  // CHECK: @llvm.x86.avx512.rsqrt28.sd
+  return _mm_mask_rsqrt28_round_sd(s, m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128d test_mm_maskz_rsqrt28_round_sd(__mmask8 m, __m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_maskz_rsqrt28_round_sd
+  // CHECK: @llvm.x86.avx512.rsqrt28.sd
+  return _mm_maskz_rsqrt28_round_sd(m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_rcp28_round_pd(__m512d a) {
+  // CHECK-LABEL: @test_mm512_rcp28_round_pd
+  // CHECK: @llvm.x86.avx512.rcp28.pd
+  return _mm512_rcp28_round_pd(a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_mask_rcp28_round_pd(__m512d s, __mmask8 m, __m512d a) {
+  // check-label: @test_mm512_mask_rcp28_round_pd
+  // check: @llvm.x86.avx512.rcp28.pd
+  return _mm512_mask_rcp28_round_pd(s, m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_maskz_rcp28_round_pd(__mmask8 m, __m512d a) {
+  // check-label: @test_mm512_maskz_rcp28_round_pd
+  // check: @llvm.x86.avx512.rcp28.pd
+  return _mm512_maskz_rcp28_round_pd(m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_rcp28_pd(__m512d a) {
+  // CHECK-LABEL: @test_mm512_rcp28_pd
+  // CHECK: @llvm.x86.avx512.rcp28.pd
+  return _mm512_rcp28_pd(a);
+}
+
+__m512d test_mm512_mask_rcp28_pd(__m512d s, __mmask8 m, __m512d a) {
+  // check-label: @test_mm512_mask_rcp28_pd
+  // check: @llvm.x86.avx512.rcp28.pd
+  return _mm512_mask_rcp28_pd(s, m, a);
+}
+
+__m512d test_mm512_maskz_rcp28_pd(__mmask8 m, __m512d a) {
+  // check-label: @test_mm512_maskz_rcp28_pd
+  // check: @llvm.x86.avx512.rcp28.pd
+  return _mm512_maskz_rcp28_pd(m, a);
+}
+
+__m512 test_mm512_rcp28_round_ps(__m512 a) {
+  // CHECK-LABEL: @test_mm512_rcp28_round_ps
+  // CHECK: @llvm.x86.avx512.rcp28.ps
+  return _mm512_rcp28_round_ps(a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_mask_rcp28_round_ps(__m512 s, __mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_mask_rcp28_round_ps
+  // CHECK: @llvm.x86.avx512.rcp28.ps
+  return _mm512_mask_rcp28_round_ps(s, m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_maskz_rcp28_round_ps(__mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_maskz_rcp28_round_ps
+  // CHECK: @llvm.x86.avx512.rcp28.ps
+  return _mm512_maskz_rcp28_round_ps(m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_rcp28_ps(__m512 a) {
+  // CHECK-LABEL: @test_mm512_rcp28_ps
+  // CHECK: @llvm.x86.avx512.rcp28.ps
+  return _mm512_rcp28_ps(a);
+}
+
+__m512 test_mm512_mask_rcp28_ps(__m512 s, __mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_mask_rcp28_ps
+  // CHECK: @llvm.x86.avx512.rcp28.ps
+  return _mm512_mask_rcp28_ps(s, m, a);
+}
+
+__m512 test_mm512_maskz_rcp28_ps(__mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_maskz_rcp28_ps
+  // CHECK: @llvm.x86.avx512.rcp28.ps
+  return _mm512_maskz_rcp28_ps(m, a);
+}
+
+__m128 test_mm_rcp28_round_ss(__m128 a, __m128 b) {
+  // check-label: @test_mm_rcp28_round_ss
+  // check: @llvm.x86.avx512.rcp28.ss
+  return _mm_rcp28_round_ss(a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128 test_mm_mask_rcp28_round_ss(__m128 s, __mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_mask_rcp28_round_ss
+  // check: @llvm.x86.avx512.rcp28.ss
+  return _mm_mask_rcp28_round_ss(s, m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128 test_mm_maskz_rcp28_round_ss(__mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_maskz_rcp28_round_ss
+  // check: @llvm.x86.avx512.rcp28.ss
+  return _mm_maskz_rcp28_round_ss(m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128 test_mm_rcp28_ss(__m128 a, __m128 b) {
+  // check-label: @test_mm_rcp28_ss
+  // check: @llvm.x86.avx512.rcp28.ss
+  return _mm_rcp28_ss(a, b);
+}
+
+__m128 test_mm_mask_rcp28_ss(__m128 s, __mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_mask_rcp28_ss
+  // check: @llvm.x86.avx512.rcp28.ss
+  return _mm_mask_rcp28_ss(s, m, a, b);
+}
+
+__m128 test_mm_maskz_rcp28_ss(__mmask16 m, __m128 a, __m128 b) {
+  // check-label: @test_mm_maskz_rcp28_ss
+  // check: @llvm.x86.avx512.rcp28.ss
+  return _mm_maskz_rcp28_ss(m, a, b);
+}
+
+__m128d test_mm_rcp28_round_sd(__m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_rcp28_round_sd
+  // CHECK: @llvm.x86.avx512.rcp28.sd
+  return _mm_rcp28_round_sd(a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128d test_mm_mask_rcp28_round_sd(__m128d s, __mmask8 m, __m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_mask_rcp28_round_sd
+  // CHECK: @llvm.x86.avx512.rcp28.sd
+  return _mm_mask_rcp28_round_sd(s, m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128d test_mm_maskz_rcp28_round_sd(__mmask8 m, __m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_maskz_rcp28_round_sd
+  // CHECK: @llvm.x86.avx512.rcp28.sd
+  return _mm_maskz_rcp28_round_sd(m, a, b, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m128d test_mm_rcp28_sd(__m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_rcp28_sd
+  // CHECK: @llvm.x86.avx512.rcp28.sd
+  return _mm_rcp28_sd(a, b);
+}
+
+__m128d test_mm_mask_rcp28_sd(__m128d s, __mmask8 m, __m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_mask_rcp28_sd
+  // CHECK: @llvm.x86.avx512.rcp28.sd
+  return _mm_mask_rcp28_sd(s, m, a, b);
+}
+
+__m128d test_mm_maskz_rcp28_sd(__mmask8 m, __m128d a, __m128d b) {
+  // CHECK-LABEL: @test_mm_maskz_rcp28_sd
+  // CHECK: @llvm.x86.avx512.rcp28.sd
+  return _mm_maskz_rcp28_sd(m, a, b);
+}
+
+__m512d test_mm512_exp2a23_round_pd(__m512d a) {
+  // CHECK-LABEL: @test_mm512_exp2a23_round_pd
+  // CHECK: @llvm.x86.avx512.exp2.pd
+  return _mm512_exp2a23_round_pd(a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_mask_exp2a23_round_pd(__m512d s, __mmask8 m, __m512d a) {
+  // check-label: @test_mm512_mask_exp2a23_round_pd
+  // check: @llvm.x86.avx512.exp2.pd
+  return _mm512_mask_exp2a23_round_pd(s, m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_maskz_exp2a23_round_pd(__mmask8 m, __m512d a) {
+  // check-label: @test_mm512_maskz_exp2a23_round_pd
+  // check: @llvm.x86.avx512.exp2.pd
+  return _mm512_maskz_exp2a23_round_pd(m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512d test_mm512_exp2a23_pd(__m512d a) {
+  // CHECK-LABEL: @test_mm512_exp2a23_pd
+  // CHECK: @llvm.x86.avx512.exp2.pd
+  return _mm512_exp2a23_pd(a);
+}
+
+__m512d test_mm512_mask_exp2a23_pd(__m512d s, __mmask8 m, __m512d a) {
+  // check-label: @test_mm512_mask_exp2a23_pd
+  // check: @llvm.x86.avx512.exp2.pd
+  return _mm512_mask_exp2a23_pd(s, m, a);
+}
+
+__m512d test_mm512_maskz_exp2a23_pd(__mmask8 m, __m512d a) {
+  // check-label: @test_mm512_maskz_exp2a23_pd
+  // check: @llvm.x86.avx512.exp2.pd
+  return _mm512_maskz_exp2a23_pd(m, a);
+}
+
+__m512 test_mm512_exp2a23_round_ps(__m512 a) {
+  // CHECK-LABEL: @test_mm512_exp2a23_round_ps
+  // CHECK: @llvm.x86.avx512.exp2.ps
+  return _mm512_exp2a23_round_ps(a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_mask_exp2a23_round_ps(__m512 s, __mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_mask_exp2a23_round_ps
+  // CHECK: @llvm.x86.avx512.exp2.ps
+  return _mm512_mask_exp2a23_round_ps(s, m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_maskz_exp2a23_round_ps(__mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_maskz_exp2a23_round_ps
+  // CHECK: @llvm.x86.avx512.exp2.ps
+  return _mm512_maskz_exp2a23_round_ps(m, a, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__m512 test_mm512_exp2a23_ps(__m512 a) {
+  // CHECK-LABEL: @test_mm512_exp2a23_ps
+  // CHECK: @llvm.x86.avx512.exp2.ps
+  return _mm512_exp2a23_ps(a);
+}
+
+__m512 test_mm512_mask_exp2a23_ps(__m512 s, __mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_mask_exp2a23_ps
+  // CHECK: @llvm.x86.avx512.exp2.ps
+  return _mm512_mask_exp2a23_ps(s, m, a);
+}
+
+__m512 test_mm512_maskz_exp2a23_ps(__mmask16 m, __m512 a) {
+  // CHECK-LABEL: @test_mm512_maskz_exp2a23_ps
+  // CHECK: @llvm.x86.avx512.exp2.ps
+  return _mm512_maskz_exp2a23_ps(m, a);
+}
+
diff --git a/test/CodeGen/avx512f-builtins.c b/test/CodeGen/avx512f-builtins.c
index ba05f4a..f7f7df5 100644
--- a/test/CodeGen/avx512f-builtins.c
+++ b/test/CodeGen/avx512f-builtins.c
@@ -75,6 +75,13 @@
   _mm512_storeu_pd(p, a);
 }
 
+void test_mm512_mask_store_ps(void *p, __m512 a, __mmask16 m)
+{
+  // CHECK-LABEL: @test_mm512_mask_store_ps
+  // CHECK: @llvm.x86.avx512.mask.store.ps.512
+  _mm512_mask_store_ps(p, m, a);
+}
+
 void test_mm512_store_ps(void *p, __m512 a)
 {
   // CHECK-LABEL: @test_mm512_store_ps
@@ -82,6 +89,13 @@
   _mm512_store_ps(p, a);
 }
 
+void test_mm512_mask_store_pd(void *p, __m512d a, __mmask8 m)
+{
+  // CHECK-LABEL: @test_mm512_mask_store_pd
+  // CHECK: @llvm.x86.avx512.mask.store.pd.512
+  _mm512_mask_store_pd(p, m, a);
+}
+
 void test_mm512_store_pd(void *p, __m512d a)
 {
   // CHECK-LABEL: @test_mm512_store_pd
@@ -103,6 +117,34 @@
   return _mm512_loadu_pd(p);
 }
 
+__m512 test_mm512_maskz_load_ps(void *p, __mmask16 m)
+{
+  // CHECK-LABEL: @test_mm512_maskz_load_ps
+  // CHECK: @llvm.x86.avx512.mask.load.ps.512
+  return _mm512_maskz_load_ps(m, p);
+}
+
+__m512 test_mm512_load_ps(void *p)
+{
+  // CHECK-LABEL: @test_mm512_load_ps
+  // CHECK: @llvm.x86.avx512.mask.load.ps.512
+  return _mm512_load_ps(p);
+}
+
+__m512d test_mm512_maskz_load_pd(void *p, __mmask8 m)
+{
+  // CHECK-LABEL: @test_mm512_maskz_load_pd
+  // CHECK: @llvm.x86.avx512.mask.load.pd.512
+  return _mm512_maskz_load_pd(m, p);
+}
+
+__m512d test_mm512_load_pd(void *p)
+{
+  // CHECK-LABEL: @test_mm512_load_pd
+  // CHECK: @llvm.x86.avx512.mask.load.pd.512
+  return _mm512_load_pd(p);
+}
+
 __m512d test_mm512_set1_pd(double d)
 {
   // CHECK-LABEL: @test_mm512_set1_pd
@@ -131,11 +173,18 @@
   return _mm512_knot(a);
 }
 
-__m512i test_mm512_valign_epi64(__m512i a, __m512i b)
+__m512i test_mm512_alignr_epi32(__m512i a, __m512i b)
 {
-  // CHECK-LABEL: @test_mm512_valign_epi64
+  // CHECK-LABEL: @test_mm512_alignr_epi32
+  // CHECK: @llvm.x86.avx512.mask.valign.d.512
+  return _mm512_alignr_epi32(a, b, 2);
+}
+
+__m512i test_mm512_alignr_epi64(__m512i a, __m512i b)
+{
+  // CHECK-LABEL: @test_mm512_alignr_epi64
   // CHECK: @llvm.x86.avx512.mask.valign.q.512
-  return _mm512_valign_epi64(a, b, 2);
+  return _mm512_alignr_epi64(a, b, 2);
 }
 
 __m512d test_mm512_broadcastsd_pd(__m128d a)
@@ -182,3 +231,405 @@
   // CHECK: @llvm.x86.avx512.mask.pcmpeq.q.512
   return (__mmask8)_mm512_cmpeq_epi64_mask(__a, __b);
 }
+
+__mmask16 test_mm512_cmpgt_epi32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.d.512
+  return (__mmask16)_mm512_cmpgt_epi32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpgt_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.d.512
+  return (__mmask16)_mm512_mask_cmpgt_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpgt_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.q.512
+  return (__mmask8)_mm512_mask_cmpgt_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpgt_epi64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.q.512
+  return (__mmask8)_mm512_cmpgt_epi64_mask(__a, __b);
+}
+
+__m512d test_mm512_unpackhi_pd(__m512d a, __m512d b)
+{
+  // CHECK-LABEL: @test_mm512_unpackhi_pd
+  // CHECK: shufflevector <8 x double> {{.*}} <i32 1, i32 9, i32 3, i32 11, i32 5, i32 13, i32 7, i32 15>
+  return _mm512_unpackhi_pd(a, b);
+}
+
+__m512d test_mm512_unpacklo_pd(__m512d a, __m512d b)
+{
+  // CHECK-LABEL: @test_mm512_unpacklo_pd
+  // CHECK: shufflevector <8 x double> {{.*}} <i32 0, i32 8, i32 2, i32 10, i32 4, i32 12, i32 6, i32 14>
+  return _mm512_unpacklo_pd(a, b);
+}
+
+__m512 test_mm512_unpackhi_ps(__m512 a, __m512 b)
+{
+  // CHECK-LABEL: @test_mm512_unpackhi_ps
+  // CHECK: shufflevector <16 x float> {{.*}} <i32 2, i32 18, i32 3, i32 19, i32 6, i32 22, i32 7, i32 23, i32 10, i32 26, i32 11, i32 27, i32 14, i32 30, i32 15, i32 31>
+  return _mm512_unpackhi_ps(a, b);
+}
+
+__m512 test_mm512_unpacklo_ps(__m512 a, __m512 b)
+{
+  // CHECK-LABEL: @test_mm512_unpacklo_ps
+  // CHECK: shufflevector <16 x float> {{.*}} <i32 0, i32 16, i32 1, i32 17, i32 4, i32 20, i32 5, i32 21, i32 8, i32 24, i32 9, i32 25, i32 12, i32 28, i32 13, i32 29>
+  return _mm512_unpacklo_ps(a, b);
+}
+
+__mmask16 test_mm512_cmp_round_ps_mask(__m512 a, __m512 b) {
+  // CHECK-LABEL: @test_mm512_cmp_round_ps_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.ps.512
+  return _mm512_cmp_round_ps_mask(a, b, 0, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__mmask16 test_mm512_mask_cmp_round_ps_mask(__mmask16 m, __m512 a, __m512 b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_round_ps_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.ps.512
+  return _mm512_mask_cmp_round_ps_mask(m, a, b, 0, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__mmask16 test_mm512_cmp_ps_mask(__m512 a, __m512 b) {
+  // check-label: @test_mm512_cmp_ps_mask
+  // check: @llvm.x86.avx512.mask.cmp.ps.512
+  return _mm512_cmp_ps_mask(a, b, 0);
+}
+
+__mmask16 test_mm512_mask_cmp_ps_mask(__mmask16 m, __m512 a, __m512 b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_ps_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.ps.512
+  return _mm512_mask_cmp_ps_mask(m, a, b, 0);
+}
+
+__mmask8 test_mm512_cmp_round_pd_mask(__m512d a, __m512d b) {
+  // CHECK-LABEL: @test_mm512_cmp_round_pd_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.pd.512
+  return _mm512_cmp_round_pd_mask(a, b, 0, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__mmask8 test_mm512_mask_cmp_round_pd_mask(__mmask8 m, __m512d a, __m512d b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_round_pd_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.pd.512
+  return _mm512_mask_cmp_round_pd_mask(m, a, b, 0, _MM_FROUND_TO_NEAREST_INT);
+}
+
+__mmask8 test_mm512_cmp_pd_mask(__m512d a, __m512d b) {
+  // check-label: @test_mm512_cmp_pd_mask
+  // check: @llvm.x86.avx512.mask.cmp.pd.512
+  return _mm512_cmp_pd_mask(a, b, 0);
+}
+
+__mmask8 test_mm512_mask_cmp_pd_mask(__mmask8 m, __m512d a, __m512d b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_pd_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.pd.512
+  return _mm512_mask_cmp_pd_mask(m, a, b, 0);
+}
+
+__m256d test_mm512_extractf64x4_pd(__m512d a)
+{
+  // CHECK-LABEL: @test_mm512_extractf64x4_pd
+  // CHECK: @llvm.x86.avx512.mask.vextractf64x4.512
+  return _mm512_extractf64x4_pd(a, 1);
+}
+
+__m128 test_mm512_extractf32x4_ps(__m512 a)
+{
+  // CHECK-LABEL: @test_mm512_extractf32x4_ps
+  // CHECK: @llvm.x86.avx512.mask.vextractf32x4.512
+  return _mm512_extractf32x4_ps(a, 1);
+}
+
+__mmask16 test_mm512_cmpeq_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpeq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 0, i16 -1)
+  return (__mmask16)_mm512_cmpeq_epu32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpeq_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpeq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 0, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmpeq_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpeq_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpeq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 0, i8 -1)
+  return (__mmask8)_mm512_cmpeq_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpeq_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpeq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 0, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmpeq_epu64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmpge_epi32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 5, i16 -1)
+  return (__mmask16)_mm512_cmpge_epi32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpge_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 5, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmpge_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpge_epi64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm512_cmpge_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpge_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmpge_epi64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmpge_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 5, i16 -1)
+  return (__mmask16)_mm512_cmpge_epu32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpge_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 5, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmpge_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpge_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpge_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm512_cmpge_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpge_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpge_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmpge_epu64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmpgt_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 6, i16 -1)
+  return (__mmask16)_mm512_cmpgt_epu32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpgt_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 6, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmpgt_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpgt_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpgt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 6, i8 -1)
+  return (__mmask8)_mm512_cmpgt_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpgt_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpgt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 6, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmpgt_epu64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmple_epi32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 2, i16 -1)
+  return (__mmask16)_mm512_cmple_epi32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmple_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 2, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmple_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmple_epi64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm512_cmple_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmple_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmple_epi64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmple_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 2, i16 -1)
+  return (__mmask16)_mm512_cmple_epu32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmple_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 2, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmple_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmple_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmple_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm512_cmple_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmple_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmple_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmple_epu64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmplt_epi32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 1, i16 -1)
+  return (__mmask16)_mm512_cmplt_epi32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmplt_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 1, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmplt_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmplt_epi64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm512_cmplt_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmplt_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmplt_epi64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmplt_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 1, i16 -1)
+  return (__mmask16)_mm512_cmplt_epu32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmplt_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 1, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmplt_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmplt_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmplt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm512_cmplt_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmplt_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmplt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmplt_epu64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmpneq_epi32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 4, i16 -1)
+  return (__mmask16)_mm512_cmpneq_epi32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpneq_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 4, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmpneq_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpneq_epi64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm512_cmpneq_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpneq_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmpneq_epi64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmpneq_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 4, i16 -1)
+  return (__mmask16)_mm512_cmpneq_epu32_mask(__a, __b);
+}
+
+__mmask16 test_mm512_mask_cmpneq_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 4, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmpneq_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm512_cmpneq_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmpneq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm512_cmpneq_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm512_mask_cmpneq_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmpneq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmpneq_epu64_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm512_cmp_epi32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 3, i16 -1)
+  return (__mmask16)_mm512_cmp_epi32_mask(__a, __b, 3);
+}
+
+__mmask16 test_mm512_mask_cmp_epi32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 3, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmp_epi32_mask(__u, __a, __b, 3);
+}
+
+__mmask8 test_mm512_cmp_epi64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 3, i8 -1)
+  return (__mmask8)_mm512_cmp_epi64_mask(__a, __b, 3);
+}
+
+__mmask8 test_mm512_mask_cmp_epi64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 3, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmp_epi64_mask(__u, __a, __b, 3);
+}
+
+__mmask16 test_mm512_cmp_epu32_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 3, i16 -1)
+  return (__mmask16)_mm512_cmp_epu32_mask(__a, __b, 3);
+}
+
+__mmask16 test_mm512_mask_cmp_epu32_mask(__mmask16 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.512(<16 x i32> {{.*}}, <16 x i32> {{.*}}, i8 3, i16 {{.*}})
+  return (__mmask16)_mm512_mask_cmp_epu32_mask(__u, __a, __b, 3);
+}
+
+__mmask8 test_mm512_cmp_epu64_mask(__m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_cmp_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 3, i8 -1)
+  return (__mmask8)_mm512_cmp_epu64_mask(__a, __b, 3);
+}
+
+__mmask8 test_mm512_mask_cmp_epu64_mask(__mmask8 __u, __m512i __a, __m512i __b) {
+  // CHECK-LABEL: @test_mm512_mask_cmp_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.512(<8 x i64> {{.*}}, <8 x i64> {{.*}}, i8 3, i8 {{.*}})
+  return (__mmask8)_mm512_mask_cmp_epu64_mask(__u, __a, __b, 3);
+}
diff --git a/test/CodeGen/avx512vl-builtins.c b/test/CodeGen/avx512vl-builtins.c
index e4b4517..5bdcbad 100644
--- a/test/CodeGen/avx512vl-builtins.c
+++ b/test/CodeGen/avx512vl-builtins.c
@@ -49,3 +49,603 @@
   // CHECK: @llvm.x86.avx512.mask.pcmpeq.q.128
   return (__mmask8)_mm_mask_cmpeq_epi64_mask(__u, __a, __b);
 }
+
+__mmask8 test_mm256_cmpgt_epi32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.d.256
+  return (__mmask8)_mm256_cmpgt_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpgt_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.d.256
+  return (__mmask8)_mm256_mask_cmpgt_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpgt_epi32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.d.128
+  return (__mmask8)_mm_cmpgt_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpgt_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.d.128
+  return (__mmask8)_mm_mask_cmpgt_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpgt_epi64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.q.256
+  return (__mmask8)_mm256_cmpgt_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpgt_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.q.256
+  return (__mmask8)_mm256_mask_cmpgt_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpgt_epi64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.q.128
+  return (__mmask8)_mm_cmpgt_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpgt_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.q.128
+  return (__mmask8)_mm_mask_cmpgt_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpeq_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 0, i8 -1)
+  return (__mmask8)_mm_cmpeq_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpeq_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpeq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 0, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpeq_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpeq_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 0, i8 -1)
+  return (__mmask8)_mm_cmpeq_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpeq_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpeq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 0, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpeq_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpge_epi32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm_cmpge_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpge_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpge_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpge_epi64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm_cmpge_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpge_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpge_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpge_epi32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm256_cmpge_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpge_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpge_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpge_epi64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm256_cmpge_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpge_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpge_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpge_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm_cmpge_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpge_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpge_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpge_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm_cmpge_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpge_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpge_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpge_epu32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm256_cmpge_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpge_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpge_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpge_epu64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 5, i8 -1)
+  return (__mmask8)_mm256_cmpge_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpge_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpge_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpgt_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 6, i8 -1)
+  return (__mmask8)_mm_cmpgt_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpgt_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 6, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpgt_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpgt_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 6, i8 -1)
+  return (__mmask8)_mm_cmpgt_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpgt_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 6, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpgt_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpgt_epu32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 6, i8 -1)
+  return (__mmask8)_mm256_cmpgt_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpgt_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 6, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpgt_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpgt_epu64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 6, i8 -1)
+  return (__mmask8)_mm256_cmpgt_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpgt_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 6, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpgt_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmple_epi32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm_cmple_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmple_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmple_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmple_epi64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm_cmple_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmple_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmple_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmple_epi32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm256_cmple_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmple_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmple_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmple_epi64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm256_cmple_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmple_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmple_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmple_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm_cmple_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmple_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmple_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmple_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm_cmple_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmple_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmple_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmple_epu32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm256_cmple_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmple_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmple_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmple_epu64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 2, i8 -1)
+  return (__mmask8)_mm256_cmple_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmple_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmple_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmplt_epi32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm_cmplt_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmplt_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmplt_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmplt_epi64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm_cmplt_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmplt_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmplt_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmplt_epi32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm256_cmplt_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmplt_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmplt_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmplt_epi64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm256_cmplt_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmplt_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmplt_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmplt_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm_cmplt_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmplt_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmplt_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmplt_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm_cmplt_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmplt_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmplt_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmplt_epu32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm256_cmplt_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmplt_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmplt_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmplt_epu64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 1, i8 -1)
+  return (__mmask8)_mm256_cmplt_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmplt_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmplt_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpneq_epi32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm_cmpneq_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpneq_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpneq_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpneq_epi64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm_cmpneq_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpneq_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpneq_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpneq_epi32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm256_cmpneq_epi32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpneq_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpneq_epi32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpneq_epi64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm256_cmpneq_epi64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpneq_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpneq_epi64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpneq_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm_cmpneq_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpneq_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpneq_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpneq_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm_cmpneq_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpneq_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmpneq_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpneq_epu32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm256_cmpneq_epu32_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpneq_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpneq_epu32_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm256_cmpneq_epu64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 4, i8 -1)
+  return (__mmask8)_mm256_cmpneq_epu64_mask(__a, __b);
+}
+
+__mmask8 test_mm256_mask_cmpneq_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmpneq_epu64_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmp_epi32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm_cmp_epi32_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm_mask_cmp_epi32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmp_epi32_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm_cmp_epi64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm_cmp_epi64_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm_mask_cmp_epi64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmp_epi64_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm256_cmp_epi32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm256_cmp_epi32_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm256_mask_cmp_epi32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epi32_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmp_epi32_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm256_cmp_epi64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm256_cmp_epi64_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm256_mask_cmp_epi64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epi64_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmp_epi64_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm_cmp_epu32_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm_cmp_epu32_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm_mask_cmp_epu32_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.128(<4 x i32> {{.*}}, <4 x i32> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmp_epu32_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm_cmp_epu64_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm_cmp_epu64_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm_mask_cmp_epu64_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm_mask_cmp_epu64_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm256_cmp_epu32_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm256_cmp_epu32_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm256_mask_cmp_epu32_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epu32_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.d.256(<8 x i32> {{.*}}, <8 x i32> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmp_epu32_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm256_cmp_epu64_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 7, i8 -1)
+  return (__mmask8)_mm256_cmp_epu64_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm256_mask_cmp_epu64_mask(__mmask8 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epu64_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.q.256(<4 x i64> {{.*}}, <4 x i64> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask8)_mm256_mask_cmp_epu64_mask(__u, __a, __b, 7);
+}
diff --git a/test/CodeGen/avx512vlbw-builtins.c b/test/CodeGen/avx512vlbw-builtins.c
index a304f7b..4d8508d 100644
--- a/test/CodeGen/avx512vlbw-builtins.c
+++ b/test/CodeGen/avx512vlbw-builtins.c
@@ -49,3 +49,627 @@
   // CHECK: @llvm.x86.avx512.mask.pcmpeq.w.128
   return (__mmask8)_mm_mask_cmpeq_epi16_mask(__u, __a, __b);
 }
+
+__mmask32 test_mm256_cmpgt_epi8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.b.256
+  return (__mmask32)_mm256_cmpgt_epi8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpgt_epi8_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.b.256
+  return (__mmask32)_mm256_mask_cmpgt_epi8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpgt_epi8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.b.128
+  return (__mmask16)_mm_cmpgt_epi8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpgt_epi8_mask(__mmask16 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.b.128
+  return (__mmask16)_mm_mask_cmpgt_epi8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpgt_epi16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.w.256
+  return (__mmask16)_mm256_cmpgt_epi16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpgt_epi16_mask(__mmask16 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.w.256
+  return (__mmask16)_mm256_mask_cmpgt_epi16_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpgt_epi16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.w.128
+  return (__mmask8)_mm_cmpgt_epi16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpgt_epi16_mask(__mmask8 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.pcmpgt.w.128
+  return (__mmask8)_mm_mask_cmpgt_epi16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpeq_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 0, i16 -1)
+  return (__mmask64)_mm_cmpeq_epu8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpeq_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpeq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 0, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmpeq_epu8_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpeq_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 0, i8 -1)
+  return (__mmask32)_mm_cmpeq_epu16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpeq_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpeq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 0, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmpeq_epu16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmpeq_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpeq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 0, i32 -1)
+  return (__mmask64)_mm256_cmpeq_epu8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpeq_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpeq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 0, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmpeq_epu8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpeq_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpeq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 0, i16 -1)
+  return (__mmask32)_mm256_cmpeq_epu16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpeq_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpeq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 0, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmpeq_epu16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpgt_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 6, i16 -1)
+  return (__mmask64)_mm_cmpgt_epu8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpgt_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 6, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmpgt_epu8_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpgt_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 6, i8 -1)
+  return (__mmask32)_mm_cmpgt_epu16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpgt_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpgt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 6, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmpgt_epu16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmpgt_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 6, i32 -1)
+  return (__mmask64)_mm256_cmpgt_epu8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpgt_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 6, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmpgt_epu8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpgt_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpgt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 6, i16 -1)
+  return (__mmask32)_mm256_cmpgt_epu16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpgt_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpgt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 6, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmpgt_epu16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpge_epi8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 5, i16 -1)
+  return (__mmask64)_mm_cmpge_epi8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpge_epi8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 5, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmpge_epi8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpge_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 5, i16 -1)
+  return (__mmask64)_mm_cmpge_epu8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpge_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 5, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmpge_epu8_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpge_epi16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 5, i8 -1)
+  return (__mmask32)_mm_cmpge_epi16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpge_epi16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmpge_epi16_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpge_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpge_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 5, i8 -1)
+  return (__mmask32)_mm_cmpge_epu16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpge_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpge_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 5, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmpge_epu16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmpge_epi8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 5, i32 -1)
+  return (__mmask64)_mm256_cmpge_epi8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpge_epi8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 5, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmpge_epi8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmpge_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 5, i32 -1)
+  return (__mmask64)_mm256_cmpge_epu8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpge_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 5, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmpge_epu8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpge_epi16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 5, i16 -1)
+  return (__mmask32)_mm256_cmpge_epi16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpge_epi16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 5, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmpge_epi16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpge_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpge_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 5, i16 -1)
+  return (__mmask32)_mm256_cmpge_epu16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpge_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpge_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 5, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmpge_epu16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmple_epi8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 2, i16 -1)
+  return (__mmask64)_mm_cmple_epi8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmple_epi8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 2, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmple_epi8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmple_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 2, i16 -1)
+  return (__mmask64)_mm_cmple_epu8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmple_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 2, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmple_epu8_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmple_epi16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 2, i8 -1)
+  return (__mmask32)_mm_cmple_epi16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmple_epi16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmple_epi16_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmple_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmple_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 2, i8 -1)
+  return (__mmask32)_mm_cmple_epu16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmple_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmple_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 2, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmple_epu16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmple_epi8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 2, i32 -1)
+  return (__mmask64)_mm256_cmple_epi8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmple_epi8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 2, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmple_epi8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmple_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 2, i32 -1)
+  return (__mmask64)_mm256_cmple_epu8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmple_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 2, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmple_epu8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmple_epi16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 2, i16 -1)
+  return (__mmask32)_mm256_cmple_epi16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmple_epi16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 2, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmple_epi16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmple_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmple_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 2, i16 -1)
+  return (__mmask32)_mm256_cmple_epu16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmple_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmple_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 2, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmple_epu16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmplt_epi8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 1, i16 -1)
+  return (__mmask64)_mm_cmplt_epi8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmplt_epi8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 1, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmplt_epi8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmplt_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 1, i16 -1)
+  return (__mmask64)_mm_cmplt_epu8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmplt_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 1, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmplt_epu8_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmplt_epi16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 1, i8 -1)
+  return (__mmask32)_mm_cmplt_epi16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmplt_epi16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmplt_epi16_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmplt_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmplt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 1, i8 -1)
+  return (__mmask32)_mm_cmplt_epu16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmplt_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmplt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 1, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmplt_epu16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmplt_epi8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 1, i32 -1)
+  return (__mmask64)_mm256_cmplt_epi8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmplt_epi8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 1, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmplt_epi8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmplt_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 1, i32 -1)
+  return (__mmask64)_mm256_cmplt_epu8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmplt_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 1, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmplt_epu8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmplt_epi16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 1, i16 -1)
+  return (__mmask32)_mm256_cmplt_epi16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmplt_epi16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 1, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmplt_epi16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmplt_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmplt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 1, i16 -1)
+  return (__mmask32)_mm256_cmplt_epu16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmplt_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmplt_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 1, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmplt_epu16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpneq_epi8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 4, i16 -1)
+  return (__mmask64)_mm_cmpneq_epi8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpneq_epi8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 4, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmpneq_epi8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmpneq_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 4, i16 -1)
+  return (__mmask64)_mm_cmpneq_epu8_mask(__a, __b);
+}
+
+__mmask16 test_mm_mask_cmpneq_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 4, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmpneq_epu8_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpneq_epi16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 4, i8 -1)
+  return (__mmask32)_mm_cmpneq_epi16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpneq_epi16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmpneq_epi16_mask(__u, __a, __b);
+}
+
+__mmask8 test_mm_cmpneq_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 4, i8 -1)
+  return (__mmask32)_mm_cmpneq_epu16_mask(__a, __b);
+}
+
+__mmask8 test_mm_mask_cmpneq_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmpneq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 4, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmpneq_epu16_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmpneq_epi8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 4, i32 -1)
+  return (__mmask64)_mm256_cmpneq_epi8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpneq_epi8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 4, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmpneq_epi8_mask(__u, __a, __b);
+}
+
+__mmask32 test_mm256_cmpneq_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 4, i32 -1)
+  return (__mmask64)_mm256_cmpneq_epu8_mask(__a, __b);
+}
+
+__mmask32 test_mm256_mask_cmpneq_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 4, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmpneq_epu8_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpneq_epi16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 4, i16 -1)
+  return (__mmask32)_mm256_cmpneq_epi16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpneq_epi16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 4, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmpneq_epi16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm256_cmpneq_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmpneq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 4, i16 -1)
+  return (__mmask32)_mm256_cmpneq_epu16_mask(__a, __b);
+}
+
+__mmask16 test_mm256_mask_cmpneq_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmpneq_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 4, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmpneq_epu16_mask(__u, __a, __b);
+}
+
+__mmask16 test_mm_cmp_epi8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 7, i16 -1)
+  return (__mmask64)_mm_cmp_epi8_mask(__a, __b, 7);
+}
+
+__mmask16 test_mm_mask_cmp_epi8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 7, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmp_epi8_mask(__u, __a, __b, 7);
+}
+
+__mmask16 test_mm_cmp_epu8_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 7, i16 -1)
+  return (__mmask64)_mm_cmp_epu8_mask(__a, __b, 7);
+}
+
+__mmask16 test_mm_mask_cmp_epu8_mask(__mmask64 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.128(<16 x i8> {{.*}}, <16 x i8> {{.*}}, i8 7, i16 {{.*}})
+  return (__mmask64)_mm_mask_cmp_epu8_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm_cmp_epi16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 7, i8 -1)
+  return (__mmask32)_mm_cmp_epi16_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm_mask_cmp_epi16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmp_epi16_mask(__u, __a, __b, 7);
+}
+
+__mmask8 test_mm_cmp_epu16_mask(__m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_cmp_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 7, i8 -1)
+  return (__mmask32)_mm_cmp_epu16_mask(__a, __b, 7);
+}
+
+__mmask8 test_mm_mask_cmp_epu16_mask(__mmask32 __u, __m128i __a, __m128i __b) {
+  // CHECK-LABEL: @test_mm_mask_cmp_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.128(<8 x i16> {{.*}}, <8 x i16> {{.*}}, i8 7, i8 {{.*}})
+  return (__mmask32)_mm_mask_cmp_epu16_mask(__u, __a, __b, 7);
+}
+
+__mmask32 test_mm256_cmp_epi8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 7, i32 -1)
+  return (__mmask64)_mm256_cmp_epi8_mask(__a, __b, 7);
+}
+
+__mmask32 test_mm256_mask_cmp_epi8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epi8_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 7, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmp_epi8_mask(__u, __a, __b, 7);
+}
+
+__mmask32 test_mm256_cmp_epu8_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 7, i32 -1)
+  return (__mmask64)_mm256_cmp_epu8_mask(__a, __b, 7);
+}
+
+__mmask32 test_mm256_mask_cmp_epu8_mask(__mmask64 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epu8_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.b.256(<32 x i8> {{.*}}, <32 x i8> {{.*}}, i8 7, i32 {{.*}})
+  return (__mmask64)_mm256_mask_cmp_epu8_mask(__u, __a, __b, 7);
+}
+
+__mmask16 test_mm256_cmp_epi16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 7, i16 -1)
+  return (__mmask32)_mm256_cmp_epi16_mask(__a, __b, 7);
+}
+
+__mmask16 test_mm256_mask_cmp_epi16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epi16_mask
+  // CHECK: @llvm.x86.avx512.mask.cmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 7, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmp_epi16_mask(__u, __a, __b, 7);
+}
+
+__mmask16 test_mm256_cmp_epu16_mask(__m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_cmp_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 7, i16 -1)
+  return (__mmask32)_mm256_cmp_epu16_mask(__a, __b, 7);
+}
+
+__mmask16 test_mm256_mask_cmp_epu16_mask(__mmask32 __u, __m256i __a, __m256i __b) {
+  // CHECK-LABEL: @test_mm256_mask_cmp_epu16_mask
+  // CHECK: @llvm.x86.avx512.mask.ucmp.w.256(<16 x i16> {{.*}}, <16 x i16> {{.*}}, i8 7, i16 {{.*}})
+  return (__mmask32)_mm256_mask_cmp_epu16_mask(__u, __a, __b, 7);
+}
diff --git a/test/CodeGen/bmi2-builtins.c b/test/CodeGen/bmi2-builtins.c
index 201cac6..5aa54fd 100644
--- a/test/CodeGen/bmi2-builtins.c
+++ b/test/CodeGen/bmi2-builtins.c
@@ -24,9 +24,9 @@
 unsigned int test_mulx_u32(unsigned int __X, unsigned int __Y,
                                  unsigned int *__P) {
   // CHECK: @test_mulx_u32
-  // CHECK-NOT: mul i64
+  // CHECK-NOT: mul nuw i64
   // B32: @test_mulx_u32
-  // B32: mul i64
+  // B32: mul nuw i64
   return _mulx_u32(__X, __Y, __P);
 }
 
@@ -48,6 +48,6 @@
 unsigned long long test_mulx_u64(unsigned long long __X, unsigned long long __Y,
                                  unsigned long long *__P) {
   // CHECK: @test_mulx_u64
-  // CHECK: mul i128
+  // CHECK: mul nuw i128
   return _mulx_u64(__X, __Y, __P);
 }
diff --git a/test/CodeGen/bool_test.c b/test/CodeGen/bool_test.c
index c836b98..cf62dba 100644
--- a/test/CodeGen/bool_test.c
+++ b/test/CodeGen/bool_test.c
@@ -15,4 +15,4 @@
 // CHECK: store i32 [[TOMEM]]
 // CHECK: ret void
 
-// CHECK: metadata !{i32 0, i32 2}
+// CHECK:  i32 0, i32 2}
diff --git a/test/CodeGen/builtin-expect.c b/test/CodeGen/builtin-expect.c
index 664c6b6..21c3ade 100644
--- a/test/CodeGen/builtin-expect.c
+++ b/test/CodeGen/builtin-expect.c
@@ -1,10 +1,14 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s -O0 | FileCheck %s --check-prefix=CHECK_O0
 
 int x;
 int y(void);
 void foo();
 void FUNC() {
+// CHECK-LABEL: define void @FUNC()
 // CHECK: [[call:%.*]] = call i32 @y
+// CHECK_O0: [[call:%.*]] = call i32 @y
+// CHECK_O0-NOT: call i64 @llvm.expect
   if (__builtin_expect (x, y()))
     foo ();
 }
@@ -17,21 +21,25 @@
     (void) __builtin_expect((isigprocmask(), 0), bar());
 }
 
+// CHECK-LABEL: define i32 @main()
 // CHECK: call void @isigprocmask()
 // CHECK: [[C:%.*]] = call i64 (...)* @bar()
+// CHECK_O0: call void @isigprocmask()
+// CHECK_O0: [[C:%.*]] = call i64 (...)* @bar()
+// CHECK_O0-NOT: call i64 @llvm.expect
 
 
-// CHECK: @test1
+// CHECK-LABEL: define i32 @test1
 int test1(int x) {
-// CHECK: @llvm.expect
+// CHECK_O0-NOT: call i64 @llvm.expect
   if (__builtin_expect (x, 1))
     return 0;
   return x;
 }
 
-// CHECK: @test2
+// CHECK: define i32 @test2
 int test2(int x) {
-// CHECK: @llvm.expect
+// CHECK_O0-NOT: call i64 @llvm.expect
   switch(__builtin_expect(x, 5)) {
   default:
     return 0;
diff --git a/test/CodeGen/builtin-longjmp.c b/test/CodeGen/builtin-longjmp.c
new file mode 100644
index 0000000..75c91b8
--- /dev/null
+++ b/test/CodeGen/builtin-longjmp.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=SUPPORTED
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=SUPPORTED
+// RUN: %clang_cc1 -triple powerpc-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=SUPPORTED
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=SUPPORTED
+// RUN: %clang_cc1 -triple arm-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=UNSUPPORTED
+// RUN: %clang_cc1 -triple aarch64-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=UNSUPPORTED
+// RUN: %clang_cc1 -triple mips-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=UNSUPPORTED
+// RUN: %clang_cc1 -triple mips64-unknown-unknown -emit-llvm < %s| FileCheck %s -check-prefix=UNSUPPORTED
+
+// Check that __builtin_longjmp and __builtin_setjmp are lowerd into
+// IR intrinsics on those architectures that can handle them.
+// Check that they are lowered to the libcalls on other architectures.
+
+typedef void *jmp_buf;
+jmp_buf buf;
+
+// SUPPORTED:   define{{.*}} void @do_jump()
+// SUPPORTED:   call{{.*}} void @llvm.eh.sjlj.longjmp
+// UNSUPPORTED: define{{.*}} void @do_jump()
+// UNSUPPORTED: call{{.*}} void @longjmp
+
+// SUPPORTED:   define{{.*}} void @do_setjmp()
+// SUPPORTED:   call{{.*}} i32 @llvm.eh.sjlj.setjmp
+// UNSUPPORTED: define{{.*}} void @do_setjmp()
+// UNSUPPORTED: call{{.*}} i32 @setjmp
+
+void do_jump(void) {
+  __builtin_longjmp(buf, 1);
+}
+
+void f(void);
+
+void do_setjmp(void) {
+  if (!__builtin_setjmp(buf))
+    f();
+}
diff --git a/test/CodeGen/builtin-nan-legacy.c b/test/CodeGen/builtin-nan-legacy.c
new file mode 100644
index 0000000..cd0f0fd
--- /dev/null
+++ b/test/CodeGen/builtin-nan-legacy.c
@@ -0,0 +1,13 @@
+// RUN: %clang -target mipsel-unknown-linux -mnan=legacy -emit-llvm -S %s -o - | FileCheck %s
+// CHECK: float 0x7FF4000000000000, float 0x7FF8000000000000
+// CHECK: double 0x7FF4000000000000, double 0x7FF8000000000000
+
+float f[] = {
+  __builtin_nan(""),
+  __builtin_nans(""),
+};
+
+double d[] = {
+  __builtin_nan(""),
+  __builtin_nans(""),
+};
diff --git a/test/CodeGen/builtin-recursive.cc b/test/CodeGen/builtin-recursive.cc
deleted file mode 100644
index 81e9b9a..0000000
--- a/test/CodeGen/builtin-recursive.cc
+++ /dev/null
@@ -1,10 +0,0 @@
-// RUN: %clang_cc1 -nostdsysteminc -nobuiltininc -isystem Inputs -emit-llvm-only %s
-
-// This used to cause a read past the end of a global variable.
-
-#include <stdio.h>
-
-void testcase(void) {
-  vprintf(0, 0);
-}
-
diff --git a/test/CodeGen/builtin-recursive.cpp b/test/CodeGen/builtin-recursive.cpp
new file mode 100644
index 0000000..7553a6e
--- /dev/null
+++ b/test/CodeGen/builtin-recursive.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -nostdsysteminc -nobuiltininc -isystem %S/Inputs -emit-llvm-only %s
+
+// This used to cause a read past the end of a global variable.
+
+#include <stdio.h>
+
+void testcase(void) {
+  vprintf(0, 0);
+}
+
diff --git a/test/CodeGen/builtins-arm-msvc-compat-error.c b/test/CodeGen/builtins-arm-msvc-compat-error.c
new file mode 100644
index 0000000..29469de
--- /dev/null
+++ b/test/CodeGen/builtins-arm-msvc-compat-error.c
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -triple thumbv7-windows -fms-extensions -verify %s
+
+void emit_error(unsigned int opcode) {
+  __emit(opcode); // expected-error {{argument to '__emit' must be a constant integer}}
+}
+
diff --git a/test/CodeGen/builtins-arm-msvc-compat-only.c b/test/CodeGen/builtins-arm-msvc-compat-only.c
new file mode 100644
index 0000000..db82ca4
--- /dev/null
+++ b/test/CodeGen/builtins-arm-msvc-compat-only.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple thumbv7-windows -fms-extensions -emit-llvm -o - %s \
+// RUN:     | FileCheck %s -check-prefix CHECK-MSVC
+// RUN: %clang_cc1 -triple armv7-eabi -emit-llvm %s -o /dev/null 2>&1 \
+// RUN:     | FileCheck %s -check-prefix CHECK-EABI
+// REQUIRES: arm-registered-target
+
+void emit() {
+  __emit(0xdefe);
+}
+
+// CHECK-MSVC: call void asm sideeffect ".inst.n 0xDEFE", ""()
+// CHECK-EABI: warning: implicit declaration of function '__emit' is invalid in C99
+
+void emit_truncated() {
+  __emit(0x11110000); // movs r0, r0
+}
+
+// CHECK-MSVC: call void asm sideeffect ".inst.n 0x0", ""()
+
diff --git a/test/CodeGen/builtins-nvptx.c b/test/CodeGen/builtins-nvptx.c
index cee9061..5f91f7a 100644
--- a/test/CodeGen/builtins-nvptx.c
+++ b/test/CodeGen/builtins-nvptx.c
@@ -155,6 +155,8 @@
   float t3 = __nvvm_sqrt_rn_f(f1);
 // CHECK: call float @llvm.nvvm.rcp.rn.f
   float t4 = __nvvm_rcp_rn_f(f2);
+// CHECK: call float @llvm.nvvm.add.rn.f
+  float t5 = __nvvm_add_rn_f(f1, f2);
 
 // CHECK: call double @llvm.nvvm.fmax.d
   double td1 = __nvvm_fmax_d(d1, d2);
diff --git a/test/CodeGen/builtins-x86.c b/test/CodeGen/builtins-x86.c
index e9ae834..e965f0c 100644
--- a/test/CodeGen/builtins-x86.c
+++ b/test/CodeGen/builtins-x86.c
@@ -355,8 +355,6 @@
 #ifdef USE_SSE4
   tmp_V16c = __builtin_ia32_pblendvb128(tmp_V16c, tmp_V16c, tmp_V16c);
   tmp_V8s = __builtin_ia32_pblendw128(tmp_V8s, tmp_V8s, imm_i_0_256);
-  tmp_V2d = __builtin_ia32_blendpd(tmp_V2d, tmp_V2d, imm_i_0_256);
-  tmp_V4f = __builtin_ia32_blendps(tmp_V4f, tmp_V4f, imm_i_0_256);
   tmp_V2d = __builtin_ia32_blendvpd(tmp_V2d, tmp_V2d, tmp_V2d);
   tmp_V4f = __builtin_ia32_blendvps(tmp_V4f, tmp_V4f, tmp_V4f);
   tmp_V8s = __builtin_ia32_packusdw128(tmp_V4i, tmp_V4i);
@@ -403,16 +401,14 @@
   tmp_V4f = __builtin_ia32_vpermilvarps(tmp_V4f, tmp_V4i);
   tmp_V4d = __builtin_ia32_vpermilvarpd256(tmp_V4d, tmp_V4LLi);
   tmp_V8f = __builtin_ia32_vpermilvarps256(tmp_V8f, tmp_V8i);
-  tmp_V4d = __builtin_ia32_blendpd256(tmp_V4d, tmp_V4d, 0x7);
-  tmp_V8f = __builtin_ia32_blendps256(tmp_V8f, tmp_V8f, 0x7);
   tmp_V4d = __builtin_ia32_blendvpd256(tmp_V4d, tmp_V4d, tmp_V4d);
   tmp_V8f = __builtin_ia32_blendvps256(tmp_V8f, tmp_V8f, tmp_V8f);
   tmp_V8f = __builtin_ia32_dpps256(tmp_V8f, tmp_V8f, 0x7);
   tmp_V4d = __builtin_ia32_cmppd256(tmp_V4d, tmp_V4d, 0);
   tmp_V8f = __builtin_ia32_cmpps256(tmp_V8f, tmp_V8f, 0);
-  tmp_V2d = __builtin_ia32_vextractf128_pd256(tmp_V4d, 0x7);
-  tmp_V4f = __builtin_ia32_vextractf128_ps256(tmp_V8f, 0x7);
-  tmp_V4i = __builtin_ia32_vextractf128_si256(tmp_V8i, 0x7);
+  tmp_V2d = __builtin_ia32_vextractf128_pd256(tmp_V4d, 0x1);
+  tmp_V4f = __builtin_ia32_vextractf128_ps256(tmp_V8f, 0x1);
+  tmp_V4i = __builtin_ia32_vextractf128_si256(tmp_V8i, 0x1);
   tmp_V4d = __builtin_ia32_cvtdq2pd256(tmp_V4i);
   tmp_V8f = __builtin_ia32_cvtdq2ps256(tmp_V8i);
   tmp_V4f = __builtin_ia32_cvtpd2ps256(tmp_V4d);
@@ -424,9 +420,9 @@
   tmp_V4d = __builtin_ia32_vperm2f128_pd256(tmp_V4d, tmp_V4d, 0x7);
   tmp_V8f = __builtin_ia32_vperm2f128_ps256(tmp_V8f, tmp_V8f, 0x7);
   tmp_V8i = __builtin_ia32_vperm2f128_si256(tmp_V8i, tmp_V8i, 0x7);
-  tmp_V4d = __builtin_ia32_vinsertf128_pd256(tmp_V4d, tmp_V2d, 0x7);
-  tmp_V8f = __builtin_ia32_vinsertf128_ps256(tmp_V8f, tmp_V4f, 0x7);
-  tmp_V8i = __builtin_ia32_vinsertf128_si256(tmp_V8i, tmp_V4i, 0x7);
+  tmp_V4d = __builtin_ia32_vinsertf128_pd256(tmp_V4d, tmp_V2d, 0x1);
+  tmp_V8f = __builtin_ia32_vinsertf128_ps256(tmp_V8f, tmp_V4f, 0x1);
+  tmp_V8i = __builtin_ia32_vinsertf128_si256(tmp_V8i, tmp_V4i, 0x1);
   tmp_V4d = __builtin_ia32_sqrtpd256(tmp_V4d);
   tmp_V8f = __builtin_ia32_sqrtps256(tmp_V8f);
   tmp_V8f = __builtin_ia32_rsqrtps256(tmp_V8f);
@@ -497,7 +493,7 @@
   tmp_V2f = __builtin_ia32_pswapdsf(tmp_V2f);
   tmp_V2i = __builtin_ia32_pswapdsi(tmp_V2i);
 
-  tmp_V4i = __builtin_ia32_sha1rnds4(tmp_V4i, tmp_V4i, imm_i);
+  tmp_V4i = __builtin_ia32_sha1rnds4(tmp_V4i, tmp_V4i, imm_i_0_4);
   tmp_V4i = __builtin_ia32_sha1nexte(tmp_V4i, tmp_V4i);
   tmp_V4i = __builtin_ia32_sha1msg1(tmp_V4i, tmp_V4i);
   tmp_V4i = __builtin_ia32_sha1msg2(tmp_V4i, tmp_V4i);
diff --git a/test/CodeGen/c-strings.c b/test/CodeGen/c-strings.c
index d82bc25..36934e8 100644
--- a/test/CodeGen/c-strings.c
+++ b/test/CodeGen/c-strings.c
@@ -6,7 +6,7 @@
 
 // CHECK: @align = global i8 [[ALIGN:[0-9]+]]
 // ITANIUM: @.str = private unnamed_addr constant [6 x i8] c"hello\00"
-// MSABI: @"\01??_C@_05CJBACGMB@hello?$AA@" = linkonce_odr unnamed_addr constant [6 x i8] c"hello\00", align 1
+// MSABI: @"\01??_C@_05CJBACGMB@hello?$AA@" = linkonce_odr unnamed_addr constant [6 x i8] c"hello\00", comdat, align 1
 // ITANIUM: @f1.x = internal global i8* getelementptr inbounds ([6 x i8]* @.str, i32 0, i32 0)
 // MSABI: @f1.x = internal global i8* getelementptr inbounds ([6 x i8]* @"\01??_C@_05CJBACGMB@hello?$AA@", i32 0, i32 0)
 // CHECK: @f2.x = internal global [6 x i8] c"hello\00", align [[ALIGN]]
diff --git a/test/CodeGen/c11atomics-ios.c b/test/CodeGen/c11atomics-ios.c
index ad004fa..ad57550 100644
--- a/test/CodeGen/c11atomics-ios.c
+++ b/test/CodeGen/c11atomics-ios.c
@@ -6,7 +6,7 @@
 
 // This work was done in pursuit of <rdar://13338582>.
 
-// CHECK-LABEL: define arm_aapcscc void @testFloat(float*
+// CHECK-LABEL: define void @testFloat(float*
 void testFloat(_Atomic(float) *fp) {
 // CHECK:      [[FP:%.*]] = alloca float*
 // CHECK-NEXT: [[X:%.*]] = alloca float
@@ -37,7 +37,7 @@
 // CHECK-NEXT: ret void
 }
 
-// CHECK: define arm_aapcscc void @testComplexFloat([[CF:{ float, float }]]*
+// CHECK: define void @testComplexFloat([[CF:{ float, float }]]*
 void testComplexFloat(_Atomic(_Complex float) *fp) {
 // CHECK:      [[FP:%.*]] = alloca [[CF]]*, align 4
 // CHECK-NEXT: [[X:%.*]] = alloca [[CF]], align 8
@@ -93,7 +93,7 @@
 }
 
 typedef struct { short x, y, z, w; } S;
-// CHECK: define arm_aapcscc void @testStruct([[S:.*]]*
+// CHECK: define void @testStruct([[S:.*]]*
 void testStruct(_Atomic(S) *fp) {
 // CHECK:      [[FP:%.*]] = alloca [[S]]*, align 4
 // CHECK-NEXT: [[X:%.*]] = alloca [[S]], align 8
@@ -143,7 +143,7 @@
 }
 
 typedef struct { short x, y, z; } PS;
-// CHECK: define arm_aapcscc void @testPromotedStruct([[APS:.*]]*
+// CHECK: define void @testPromotedStruct([[APS:.*]]*
 void testPromotedStruct(_Atomic(PS) *fp) {
 // CHECK:      [[FP:%.*]] = alloca [[APS]]*, align 4
 // CHECK-NEXT: [[X:%.*]] = alloca [[APS]], align 8
diff --git a/test/CodeGen/c11atomics.c b/test/CodeGen/c11atomics.c
index f4c9522..376c582 100644
--- a/test/CodeGen/c11atomics.c
+++ b/test/CodeGen/c11atomics.c
@@ -57,7 +57,7 @@
 // CHECK: testdec
 void testdec(void)
 {
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   b--;
   // CHECK: atomicrmw sub i32* @i, i32 1 seq_cst
   i--;
@@ -65,7 +65,7 @@
   l--;
   // CHECK: atomicrmw sub i16* @s, i16 1 seq_cst
   s--;
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   --b;
   // CHECK: atomicrmw sub i32* @i, i32 1 seq_cst
   // CHECK: sub i32
@@ -80,7 +80,7 @@
 // CHECK: testaddeq
 void testaddeq(void)
 {
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   // CHECK: atomicrmw add i32* @i, i32 42 seq_cst
   // CHECK: atomicrmw add i64* @l, i64 42 seq_cst
   // CHECK: atomicrmw add i16* @s, i16 42 seq_cst
@@ -92,7 +92,7 @@
 // CHECK: testsubeq
 void testsubeq(void)
 {
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   // CHECK: atomicrmw sub i32* @i, i32 42 seq_cst
   // CHECK: atomicrmw sub i64* @l, i64 42 seq_cst
   // CHECK: atomicrmw sub i16* @s, i16 42 seq_cst
@@ -104,7 +104,7 @@
 // CHECK: testxoreq
 void testxoreq(void)
 {
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   // CHECK: atomicrmw xor i32* @i, i32 42 seq_cst
   // CHECK: atomicrmw xor i64* @l, i64 42 seq_cst
   // CHECK: atomicrmw xor i16* @s, i16 42 seq_cst
@@ -116,7 +116,7 @@
 // CHECK: testoreq
 void testoreq(void)
 {
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   // CHECK: atomicrmw or i32* @i, i32 42 seq_cst
   // CHECK: atomicrmw or i64* @l, i64 42 seq_cst
   // CHECK: atomicrmw or i16* @s, i16 42 seq_cst
@@ -128,7 +128,7 @@
 // CHECK: testandeq
 void testandeq(void)
 {
-  // CHECK: cmpxchg i8* @b
+  // CHECK: call arm_aapcscc zeroext i1 @__atomic_compare_exchange(i32 1, i8* @b
   // CHECK: atomicrmw and i32* @i, i32 42 seq_cst
   // CHECK: atomicrmw and i64* @l, i64 42 seq_cst
   // CHECK: atomicrmw and i16* @s, i16 42 seq_cst
diff --git a/test/CodeGen/catch-undef-behavior.c b/test/CodeGen/catch-undef-behavior.c
index 3d2697d..c41b37c 100644
--- a/test/CodeGen/catch-undef-behavior.c
+++ b/test/CodeGen/catch-undef-behavior.c
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -fsanitize=alignment,null,object-size,shift,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-COMMON --check-prefix=CHECK-UBSAN
-// RUN: %clang_cc1 -fsanitize-undefined-trap-on-error -fsanitize=alignment,null,object-size,shift,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-COMMON --check-prefix=CHECK-TRAP
-// RUN: %clang_cc1 -fsanitize=null -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-NULL
+// RUN: %clang_cc1 -fsanitize=alignment,null,object-size,shift,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute -fsanitize-recover=alignment,null,object-size,shift,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-COMMON --check-prefix=CHECK-UBSAN
+// RUN: %clang_cc1 -fsanitize-undefined-trap-on-error -fsanitize=alignment,null,object-size,shift,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute -fsanitize-recover=alignment,null,object-size,shift,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-COMMON --check-prefix=CHECK-TRAP
+// RUN: %clang_cc1 -fsanitize=null -fsanitize-recover=null -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-NULL
 // RUN: %clang_cc1 -fsanitize=signed-integer-overflow -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-OVERFLOW
 
 // CHECK-UBSAN: @[[INT:.*]] = private unnamed_addr constant { i16, i16, [6 x i8] } { i16 0, i16 11, [6 x i8] c"'int'\00" }
@@ -379,6 +379,6 @@
   nonnull_variadic(a, b);
 }
 
-// CHECK-UBSAN: ![[WEIGHT_MD]] = metadata !{metadata !"branch_weights", i32 1048575, i32 1}
+// CHECK-UBSAN: ![[WEIGHT_MD]] = !{!"branch_weights", i32 1048575, i32 1}
 
 // CHECK-TRAP: attributes [[NR_NUW]] = { noreturn nounwind }
diff --git a/test/CodeGen/cleanup-stack.c b/test/CodeGen/cleanup-stack.c
index 72a1a6c..6448aac 100644
--- a/test/CodeGen/cleanup-stack.c
+++ b/test/CodeGen/cleanup-stack.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple i386-unknown-unknown -O3 -emit-llvm %s -o %t
-// RUN: grep "ret i32 9" %t
+// RUN: %clang_cc1 -triple i386-unknown-unknown -O3 -emit-llvm %s -o - | FileCheck %s
+// CHECK: ret i32 9
 
 struct s0 {
   int *var;
diff --git a/test/CodeGen/clear_cache.c b/test/CodeGen/clear_cache.c
index f859d7f..ec88c90 100644
--- a/test/CodeGen/clear_cache.c
+++ b/test/CodeGen/clear_cache.c
@@ -7,6 +7,6 @@
 
 int main() {
   __builtin___clear_cache(buffer, buffer+32);
-// CHECK: @llvm.clear_cache(i8* getelementptr {{.*}}, i8* getelementptr {{.*}} (i8* getelementptr {{.*}} 32))
+// CHECK: @llvm.clear_cache(i8* getelementptr inbounds ({{.*}}, i8* getelementptr inbounds (i8* getelementptr inbounds ({{.*}} 32))
   return 0;
 }
diff --git a/test/CodeGen/complex-math.c b/test/CodeGen/complex-math.c
index 29172fa..36ef271 100644
--- a/test/CodeGen/complex-math.c
+++ b/test/CodeGen/complex-math.c
@@ -2,6 +2,7 @@
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple x86_64-pc-win64 -o - | FileCheck %s --check-prefix=X86
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple i686-unknown-unknown -o - | FileCheck %s --check-prefix=X86
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple powerpc-unknown-unknown -o - | FileCheck %s --check-prefix=PPC
+// RUN: %clang_cc1 %s -O1 -emit-llvm -triple armv7-none-linux-gnueabihf -o - | FileCheck %s --check-prefix=ARM
 
 float _Complex add_float_rr(float a, float b) {
   // X86-LABEL: @add_float_rr(
@@ -471,3 +472,10 @@
   // X86: ret
   return a != b;
 }
+
+// Check that the libcall will obtain proper calling convention on ARM
+_Complex double foo(_Complex double a, _Complex double b) {
+  // ARM-LABEL: @foo(
+  // ARM: call arm_aapcscc { double, double } @__muldc3
+  return a*b;
+}
diff --git a/test/CodeGen/compound-assign-overflow.c b/test/CodeGen/compound-assign-overflow.c
index 1533429..f126bb0 100644
--- a/test/CodeGen/compound-assign-overflow.c
+++ b/test/CodeGen/compound-assign-overflow.c
@@ -1,5 +1,5 @@
 // Verify proper type emitted for compound assignments
-// RUN: %clang_cc1 -ffreestanding -triple x86_64-apple-darwin10 -emit-llvm -o - %s  -fsanitize=signed-integer-overflow,unsigned-integer-overflow | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -triple x86_64-apple-darwin10 -emit-llvm -o - %s  -fsanitize=signed-integer-overflow,unsigned-integer-overflow -fsanitize-recover=signed-integer-overflow,unsigned-integer-overflow | FileCheck %s
 
 #include <stdint.h>
 
diff --git a/test/CodeGen/debug-info-args.c b/test/CodeGen/debug-info-args.c
index d1fa917..33cf5bc 100644
--- a/test/CodeGen/debug-info-args.c
+++ b/test/CodeGen/debug-info-args.c
@@ -2,8 +2,8 @@
 
 int somefunc(char *x, int y, double z) {
   
-  // CHECK: metadata ![[NUM:[^,]*]], null, null, null} ; [ DW_TAG_subroutine_type
-  // CHECK: ![[NUM]] = {{metadata !{metadata ![^,]*, metadata ![^,]*, metadata ![^,]*, metadata ![^,]*}}}
+  // CHECK: ![[NUM:[^,]*]], null, null, null} ; [ DW_TAG_subroutine_type
+  // CHECK: ![[NUM]] = {{!{![^,]*, ![^,]*, ![^,]*, ![^,]*}}}
   
   return y;
 }
diff --git a/test/CodeGen/debug-info-block-decl.c b/test/CodeGen/debug-info-block-decl.c
index 06c0e1a..f3f5e6b 100644
--- a/test/CodeGen/debug-info-block-decl.c
+++ b/test/CodeGen/debug-info-block-decl.c
@@ -9,8 +9,8 @@
 
 int main()
 {
-// CHECK: [[ASSIGNMENT]] = metadata !{i32 [[@LINE+2]],
-// CHECK: [[BLOCK_ENTRY]] = metadata !{i32 [[@LINE+1]],
+// CHECK: [[ASSIGNMENT]] = !MDLocation(line: [[@LINE+2]],
+// CHECK: [[BLOCK_ENTRY]] = !MDLocation(line: [[@LINE+1]],
     int (^blockptr)(void) = ^(void) {
       return 0;
     };
diff --git a/test/CodeGen/debug-info-block-out-return.c b/test/CodeGen/debug-info-block-out-return.c
index d8f9238..47b90ce 100644
--- a/test/CodeGen/debug-info-block-out-return.c
+++ b/test/CodeGen/debug-info-block-out-return.c
@@ -11,8 +11,8 @@
 // out of order or not at all (the latter would occur if they were both assigned
 // the same argument number by mistake).
 
-// CHECK: metadata !"0x101\00.block_descriptor\0016777218\00{{[0-9]+}}", {{.*}} ; [ DW_TAG_arg_variable ] [.block_descriptor]
-// CHECK: metadata !"0x101\00param\0033554434\00{{[0-9]+}}", {{.*}} ; [ DW_TAG_arg_variable ] [param]
+// CHECK: !"0x101\00.block_descriptor\0016777218\00{{[0-9]+}}", {{.*}} ; [ DW_TAG_arg_variable ] [.block_descriptor]
+// CHECK: !"0x101\00param\0033554434\00{{[0-9]+}}", {{.*}} ; [ DW_TAG_arg_variable ] [param]
 
 // Line directive so we don't have to worry about how many lines preceed the
 // test code (as the line number is mangled in with the argument number as shown
diff --git a/test/CodeGen/debug-info-enum.c b/test/CodeGen/debug-info-enum.c
index d4349ea..1f6b384 100644
--- a/test/CodeGen/debug-info-enum.c
+++ b/test/CodeGen/debug-info-enum.c
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s
 
-// CHECK: metadata [[TEST3_ENUMS:![0-9]*]], null, null, null} ; [ DW_TAG_enumeration_type ] [e]
-// CHECK: [[TEST3_ENUMS]] = metadata !{metadata [[TEST3_E:![0-9]*]]}
-// CHECK: [[TEST3_E]] = metadata !{metadata !"0x28\00E\00-1"} ; [ DW_TAG_enumerator ] [E :: -1]
+// CHECK: [[TEST3_ENUMS:![0-9]*]], null, null, null} ; [ DW_TAG_enumeration_type ] [e]
+// CHECK: [[TEST3_ENUMS]] = !{[[TEST3_E:![0-9]*]]}
+// CHECK: [[TEST3_E]] = !{!"0x28\00E\00-1"} ; [ DW_TAG_enumerator ] [E :: -1]
 
 enum e;
 void func(enum e *p) {
diff --git a/test/CodeGen/debug-info-file-change.c b/test/CodeGen/debug-info-file-change.c
new file mode 100644
index 0000000..8f869d0
--- /dev/null
+++ b/test/CodeGen/debug-info-file-change.c
@@ -0,0 +1,21 @@
+// RUN: %clang -emit-llvm -S -g %s -o - | FileCheck %s
+
+// Radar 8396182
+// There are no lexical blocks, but we need two DILexicalBlockFiles to
+// correctly represent file info.
+
+int foo() {
+  int i = 1;
+# 4 "m.c"
+# 1 "m.h" 1
+  int j = 2;
+# 2 "m.h"
+# 5 "m.c" 2
+  return i + j;
+}
+
+// CHECK: DW_TAG_lexical_block
+// CHECK: !"m.h"
+// CHECK: DW_TAG_lexical_block
+// CHECK: !"m.c"
+// CHECK-NOT: DW_TAG_lexical_block
diff --git a/test/CodeGen/debug-info-line.c b/test/CodeGen/debug-info-line.c
index 8f869d0..2e044d2 100644
--- a/test/CodeGen/debug-info-line.c
+++ b/test/CodeGen/debug-info-line.c
@@ -1,21 +1,11 @@
-// RUN: %clang -emit-llvm -S -g %s -o - | FileCheck %s
+// RUN: %clang_cc1 -w -gline-tables-only -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - | FileCheck %s
 
-// Radar 8396182
-// There are no lexical blocks, but we need two DILexicalBlockFiles to
-// correctly represent file info.
-
-int foo() {
-  int i = 1;
-# 4 "m.c"
-# 1 "m.h" 1
-  int j = 2;
-# 2 "m.h"
-# 5 "m.c" 2
-  return i + j;
+int f1(int a, int b) {
+  // CHECK: icmp {{.*}}, !dbg [[DBG_F1:!.*]]
+#line 100
+  return a  //
+         && //
+         b;
 }
 
-// CHECK: DW_TAG_lexical_block
-// CHECK: !"m.h"
-// CHECK: DW_TAG_lexical_block
-// CHECK: !"m.c"
-// CHECK-NOT: DW_TAG_lexical_block
+// CHECK: [[DBG_F1]] = !MDLocation(line: 100,
diff --git a/test/CodeGen/debug-info-line3.c b/test/CodeGen/debug-info-line3.c
index d01b023..d2efcf7 100644
--- a/test/CodeGen/debug-info-line3.c
+++ b/test/CodeGen/debug-info-line3.c
@@ -13,4 +13,4 @@
 }
 
 // CHECK: ret void, !dbg [[LINE:.*]]
-// CHECK: [[LINE]] = metadata !{i32 6,
+// CHECK: [[LINE]] = !MDLocation(line: 6,
diff --git a/test/CodeGen/debug-info-line4.c b/test/CodeGen/debug-info-line4.c
index 004176c..2b3e0fe 100644
--- a/test/CodeGen/debug-info-line4.c
+++ b/test/CodeGen/debug-info-line4.c
@@ -8,4 +8,4 @@
 }
 
 // Without column information we wouldn't change locations for b.
-// CHECK: metadata !{i32 4, i32 20,
+// CHECK:  !MDLocation(line: 4, column: 20,
diff --git a/test/CodeGen/debug-info-same-line.c b/test/CodeGen/debug-info-same-line.c
new file mode 100644
index 0000000..dddabda
--- /dev/null
+++ b/test/CodeGen/debug-info-same-line.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -g -o - | FileCheck %s
+// Here two temporary nodes are identical (but should not get uniqued) while
+// building the full debug type.
+typedef struct { long x; } foo; typedef struct {  foo *x; } bar;
+// CHECK: [ DW_TAG_structure_type ] [line 4, size 64,
+// CHECK: [ DW_TAG_structure_type ] [line 4, size 64,
+bar b;
diff --git a/test/CodeGen/debug-info-scope-file.c b/test/CodeGen/debug-info-scope-file.c
index 3479ade..226fb27 100644
--- a/test/CodeGen/debug-info-scope-file.c
+++ b/test/CodeGen/debug-info-scope-file.c
@@ -7,8 +7,8 @@
 // CHECK: ret void, !dbg [[F2_LINE:![0-9]*]]
 // CHECK: [[F1:![0-9]*]] = {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [f1]
 // CHECK: [[F2:![0-9]*]] = {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [f2]
-// CHECK: [[F1_LINE]] = {{.*}}, metadata [[F1]], null}
-// CHECK: [[F2_LINE]] = {{.*}}, metadata [[F2]], null}
+// CHECK: [[F1_LINE]] = !MDLocation({{.*}}, scope: [[F1]])
+// CHECK: [[F2_LINE]] = !MDLocation({{.*}}, scope: [[F2]])
 
 void f1() {
 }
diff --git a/test/CodeGen/debug-info-typedef.c b/test/CodeGen/debug-info-typedef.c
index 73c7bcd..3db7d53 100644
--- a/test/CodeGen/debug-info-typedef.c
+++ b/test/CodeGen/debug-info-typedef.c
@@ -7,5 +7,5 @@
 
 MyType a;
 
-// CHECK: metadata !{metadata !"0x16\00MyType\002\00{{.*}}", metadata ![[HEADER:[0-9]+]], null{{.*}}} ; [ DW_TAG_typedef ] [MyType] [line 2, size 0, align 0, offset 0] [from int]
-// CHECK: ![[HEADER]] = metadata !{metadata !"b.h",
+// CHECK:  !"0x16\00MyType\002\00{{.*}}", ![[HEADER:[0-9]+]], null{{.*}}} ; [ DW_TAG_typedef ] [MyType] [line 2, size 0, align 0, offset 0] [from int]
+// CHECK: ![[HEADER]] = !{!"b.h",
diff --git a/test/CodeGen/debug-info-version.c b/test/CodeGen/debug-info-version.c
index dd303c1..5fe2e4e 100644
--- a/test/CodeGen/debug-info-version.c
+++ b/test/CodeGen/debug-info-version.c
@@ -4,5 +4,5 @@
   return 0;
 }
 
-// CHECK: metadata !{i32 2, metadata !"Debug Info Version", i32 2}
-// NO_DEBUG-NOT: metadata !"Debug Info Version"
+// CHECK:  i32 2, !"Debug Info Version", i32 2}
+// NO_DEBUG-NOT: !"Debug Info Version"
diff --git a/test/CodeGen/debug-info-vla.c b/test/CodeGen/debug-info-vla.c
index 104c251..7d321cf 100644
--- a/test/CodeGen/debug-info-vla.c
+++ b/test/CodeGen/debug-info-vla.c
@@ -2,7 +2,10 @@
 
 void testVLAwithSize(int s)
 {
-// CHECK: metadata !{metadata !"0x100\00vla\00[[@LINE+1]]\008192", metadata {{.*}}, metadata {{.*}}, metadata {{.*}}} ; [ DW_TAG_auto_variable ] [vla] [line [[@LINE+1]]]
+// CHECK: dbg.declare
+// CHECK: dbg.declare({{.*}}, metadata ![[VAR:.*]], metadata ![[EXPR:.*]])
+// CHECK: ![[VAR]] = {{.*}} ; [ DW_TAG_auto_variable ] [vla] [line [[@LINE+2]]]
+// CHECK: ![[EXPR]] = {{.*}} ; [ DW_TAG_expression ] [DW_OP_deref]
   int vla[s];
   int i;
   for (i = 0; i < s; i++) {
diff --git a/test/CodeGen/dependent-lib.c b/test/CodeGen/dependent-lib.c
index 20913d3..b3abc2f 100644
--- a/test/CodeGen/dependent-lib.c
+++ b/test/CodeGen/dependent-lib.c
@@ -3,13 +3,13 @@
 // RUN: %clang_cc1 %s --dependent-lib=msvcrt -triple i686-pc-linux -emit-llvm -o - | FileCheck -check-prefix LINUX %s
 
 // CHECK: !llvm.module.flags = !{{{.*}}}
-// CHECK: !{{[0-9]+}} = metadata !{i32 6, metadata !"Linker Options", metadata ![[link_opts:[0-9]+]]}
-// CHECK: ![[link_opts]] = metadata !{metadata ![[msvcrt:[0-9]+]]}
-// CHECK: ![[msvcrt]] = metadata !{metadata !"/DEFAULTLIB:msvcrt.lib"}
+// CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[link_opts:[0-9]+]]}
+// CHECK: ![[link_opts]] = !{![[msvcrt:[0-9]+]]}
+// CHECK: ![[msvcrt]] = !{!"/DEFAULTLIB:msvcrt.lib"}
 
 // LINUX: !llvm.module.flags = !{{{.*}}}
-// LINUX: !{{[0-9]+}} = metadata !{i32 6, metadata !"Linker Options", metadata ![[link_opts:[0-9]+]]}
-// LINUX: ![[link_opts]] = metadata !{metadata ![[msvcrt:[0-9]+]]}
-// LINUX: ![[msvcrt]] = metadata !{metadata !"-lmsvcrt"}
+// LINUX: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[link_opts:[0-9]+]]}
+// LINUX: ![[link_opts]] = !{![[msvcrt:[0-9]+]]}
+// LINUX: ![[msvcrt]] = !{!"-lmsvcrt"}
 
 int f();
diff --git a/test/CodeGen/dwarf-version.c b/test/CodeGen/dwarf-version.c
index 26dfbcb..cb95f28 100644
--- a/test/CodeGen/dwarf-version.c
+++ b/test/CodeGen/dwarf-version.c
@@ -10,6 +10,6 @@
   return 0;
 }
 
-// VER2: metadata !{i32 2, metadata !"Dwarf Version", i32 2}
-// VER3: metadata !{i32 2, metadata !"Dwarf Version", i32 3}
-// VER4: metadata !{i32 2, metadata !"Dwarf Version", i32 4}
+// VER2: !{i32 2, !"Dwarf Version", i32 2}
+// VER3: !{i32 2, !"Dwarf Version", i32 3}
+// VER4: !{i32 2, !"Dwarf Version", i32 4}
diff --git a/test/CodeGen/enum.c b/test/CodeGen/enum.c
index 0e239f1..ef50f9e 100644
--- a/test/CodeGen/enum.c
+++ b/test/CodeGen/enum.c
@@ -1,5 +1,7 @@
-// RUN: %clang_cc1 -triple i386-unknown-unknown %s -O3 -emit-llvm -o - | grep 'ret i32 6'
-// RUN: %clang_cc1 -triple i386-unknown-unknown -x c++ %s -O3 -emit-llvm -o - | grep 'ret i32 7'
+// RUN: %clang_cc1 -triple i386-unknown-unknown %s -O3 -emit-llvm -o - | FileCheck -check-prefix=CHECK-C %s
+// RUN: %clang_cc1 -triple i386-unknown-unknown -x c++ %s -O3 -emit-llvm -o - | FileCheck -check-prefix=CHECK-CXX %s
+// CHECK-C: ret i32 6
+// CHECK-CXX: ret i32 7
 
 // This test case illustrates a peculiarity of the promotion of
 // enumeration types in C and C++. In particular, the enumeration type
@@ -19,4 +21,3 @@
 
   return r;
 }
-
diff --git a/test/CodeGen/exceptions-seh-finally.c b/test/CodeGen/exceptions-seh-finally.c
new file mode 100644
index 0000000..1bb60d8
--- /dev/null
+++ b/test/CodeGen/exceptions-seh-finally.c
@@ -0,0 +1,291 @@
+// RUN: %clang_cc1 %s -triple x86_64-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s
+
+void abort(void) __attribute__((noreturn));
+void might_crash(void);
+void cleanup(void);
+int check_condition(void);
+void basic_finally(void) {
+  __try {
+    might_crash();
+  } __finally {
+    cleanup();
+  }
+}
+
+// CHECK-LABEL: define void @basic_finally()
+// CHECK: invoke void @might_crash()
+// CHECK:     to label %[[invoke_cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[invoke_cont]]
+// CHECK: store i8 0, i8* %[[abnormal:[^ ]*]]
+// CHECK: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK: call void @cleanup()
+// CHECK: load i8* %[[abnormal]]
+// CHECK: icmp eq
+// CHECK: br i1 %{{.*}}, label %[[finallycont:[^ ]*]], label %[[resumecont:[^ ]*]]
+//
+// CHECK: [[finallycont]]
+// CHECK-NEXT: ret void
+//
+// CHECK: [[lpad]]
+// CHECK-NEXT: landingpad
+// CHECK-NEXT: cleanup
+// CHECK: store i8 1, i8* %[[abnormal]]
+// CHECK: br label %[[finally]]
+//
+// CHECK: [[resumecont]]
+// CHECK: br label %[[ehresume:[^ ]*]]
+//
+// CHECK: [[ehresume]]
+// CHECK: resume { i8*, i32 }
+
+// Mostly check that we don't double emit 'r' which would crash.
+void decl_in_finally(void) {
+  __try {
+    might_crash();
+  } __finally {
+    int r;
+  }
+}
+
+// Ditto, don't crash double emitting 'l'.
+void label_in_finally(void) {
+  __try {
+    might_crash();
+  } __finally {
+l:
+    cleanup();
+    if (check_condition())
+      goto l;
+  }
+}
+
+// CHECK-LABEL: define void @label_in_finally()
+// CHECK: invoke void @might_crash()
+// CHECK:     to label %[[invoke_cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[invoke_cont]]
+// CHECK: store i8 0, i8* %[[abnormal:[^ ]*]]
+// CHECK: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK: br label %[[l:[^ ]*]]
+//
+// CHECK: [[l]]
+// CHECK: call void @cleanup()
+// CHECK: call i32 @check_condition()
+// CHECK: br i1 {{.*}}, label
+// CHECK: br label %[[l]]
+
+int crashed;
+void use_abnormal_termination(void) {
+  __try {
+    might_crash();
+  } __finally {
+    crashed = __abnormal_termination();
+  }
+}
+
+// CHECK-LABEL: define void @use_abnormal_termination()
+// CHECK: invoke void @might_crash()
+// CHECK:     to label %[[invoke_cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[invoke_cont]]
+// CHECK: store i8 0, i8* %[[abnormal:[^ ]*]]
+// CHECK: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK: load i8* %[[abnormal]]
+// CHECK: zext i8 %{{.*}} to i32
+// CHECK: store i32 %{{.*}}, i32* @crashed
+// CHECK: load i8* %[[abnormal]]
+// CHECK: icmp eq
+// CHECK: br i1 %{{.*}}, label %[[finallycont:[^ ]*]], label %[[resumecont:[^ ]*]]
+//
+// CHECK: [[finallycont]]
+// CHECK-NEXT: ret void
+//
+// CHECK: [[lpad]]
+// CHECK-NEXT: landingpad
+// CHECK-NEXT: cleanup
+// CHECK: store i8 1, i8* %[[abnormal]]
+// CHECK: br label %[[finally]]
+//
+// CHECK: [[resumecont]]
+// CHECK: br label %[[ehresume:[^ ]*]]
+//
+// CHECK: [[ehresume]]
+// CHECK: resume { i8*, i32 }
+
+void noreturn_noop_finally() {
+  __try {
+    __noop();
+  } __finally {
+    abort();
+  }
+}
+
+// CHECK-LABEL: define void @noreturn_noop_finally()
+// CHECK: store i8 0, i8* %
+// CHECK: br label %[[finally:[^ ]*]]
+// CHECK: [[finally]]
+// CHECK: call void @abort()
+// CHECK-NEXT: unreachable
+// CHECK-NOT: load
+
+void noreturn_finally() {
+  __try {
+    might_crash();
+  } __finally {
+    abort();
+  }
+}
+
+// CHECK-LABEL: define void @noreturn_finally()
+// CHECK: invoke void @might_crash()
+// CHECK:     to label %[[cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[cont]]
+// CHECK: store i8 0, i8* %
+// CHECK: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK: call void @abort()
+// CHECK-NEXT: unreachable
+//
+// CHECK: [[lpad]]
+// CHECK: landingpad
+// CHECK-NEXT: cleanup
+// CHECK: store i8 1, i8* %
+// CHECK: br label %[[finally]]
+
+int finally_with_return() {
+  __try {
+    return 42;
+  } __finally {
+  }
+}
+// CHECK-LABEL: define i32 @finally_with_return()
+// CHECK: store i8 0, i8* %
+// CHECK-NEXT: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK-NEXT: br label %[[finallycont:[^ ]*]]
+//
+// CHECK: [[finallycont]]
+// CHECK-NEXT: ret i32 42
+
+int nested___finally___finally() {
+  __try {
+    __try {
+    } __finally {
+      return 1;
+    }
+  } __finally {
+    // Intentionally no return here.
+  }
+  return 0;
+}
+// CHECK-LABEL: define i32 @nested___finally___finally
+// CHECK: store i8 0, i8* %
+// CHECK-NEXT: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK-NEXT: store i32 1, i32* %
+// CHECK-NEXT: store i32 1, i32* %
+// CHECK-NEXT: br label %[[cleanup:[^ ]*]]
+//
+// The finally's unreachable continuation block:
+// CHECK: store i32 0, i32* %
+// CHECK-NEXT: br label %[[cleanup]]
+//
+// CHECK: [[cleanup]]
+// CHECK-NEXT: store i8 0, i8* %
+// CHECK-NEXT: br label %[[outerfinally:[^ ]*]]
+//
+// CHECK: [[outerfinally]]
+// CHECK-NEXT: br label %[[finallycont:[^ ]*]]
+//
+// CHECK: [[finallycont]]
+// CHECK-NEXT: %[[dest:[^ ]*]] = load i32* %
+// CHECK-NEXT: switch i32 %[[dest]]
+// CHECK-NEXT: i32 0, label %[[cleanupcont:[^ ]*]]
+//
+// CHECK: [[cleanupcont]]
+// CHECK-NEXT: store i32 0, i32* %
+// CHECK-NEXT: br label %[[return:[^ ]*]]
+//
+// CHECK: [[return]]
+// CHECK-NEXT: %[[reg:[^ ]*]] = load i32* %
+// CHECK-NEXT: ret i32 %[[reg]]
+
+int nested___finally___finally_with_eh_edge() {
+  __try {
+    __try {
+      might_crash();
+    } __finally {
+      return 899;
+    }
+  } __finally {
+    // Intentionally no return here.
+  }
+  return 912;
+}
+// CHECK-LABEL: define i32 @nested___finally___finally_with_eh_edge
+// CHECK: invoke void @might_crash() #3
+// CHECK-NEXT: to label %[[invokecont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[invokecont]]
+// CHECK-NEXT: store i8 0, i8* %[[abnormal:[^ ]*]]
+// CHECK-NEXT: br label %[[finally:[^ ]*]]
+
+// CHECK: [[finally]]
+// CHECK-NEXT: store i32 899, i32* %
+// CHECK-NEXT: store i32 1, i32* %
+// CHECK-NEXT: br label %[[cleanup:[^ ]*]]
+//
+// The inner finally's unreachable continuation block:
+// CHECK: store i32 0, i32* %
+// CHECK-NEXT: br label %[[cleanup]]
+//
+// CHECK: [[cleanup]]
+// CHECK-NEXT: store i8 0, i8* %
+// CHECK-NEXT: br label %[[outerfinally:[^ ]*]]
+//
+// CHECK: [[outerfinally]]
+// CHECK-NEXT: %[[abnormallocal:[^ ]*]] = load i8* %[[abnormal]]
+// CHECK-NEXT: %[[reg:[^ ]*]] = icmp eq i8 %[[abnormallocal]], 0
+// CHECK-NEXT: br i1 %[[reg]], label %[[finallycont:[^ ]*]], label %[[finallyresume:[^ ]*]]
+//
+// CHECK: [[finallycont]]
+// CHECK-NEXT: %[[dest:[^ ]*]] = load i32* %
+// CHECK-NEXT: switch i32 %[[dest]]
+// CHECK-NEXT: i32 0, label %[[cleanupcont:[^ ]*]]
+//
+// CHECK: [[cleanupcont]]
+// CHECK-NEXT: store i32 912, i32* %
+// CHECK-NEXT: br label %[[return:[^ ]*]]
+//
+//
+// CHECK: [[lpad]]
+// CHECK-NEXT: landingpad
+// CHECK-NEXT: cleanup
+// CHECK: store i8 1, i8* %[[abnormal]]
+// CHECK: br label %[[finally]]
+//
+// The inner finally's unreachable resume block:
+// CHECK: store i8 1, i8* %[[abnormal]]
+// CHECK-NEXT: br label %[[outerfinally]]
+//
+// CHECK: [[finallyresume]]
+// CHECK-NEXT: br label %[[ehresume:[^ ]*]]
+//
+// CHECK: [[return]]
+// CHECK-NEXT: %[[reg:[^ ]*]] = load i32* %
+// CHECK-NEXT: ret i32 %[[reg]]
+//
+// The ehresume block, not reachable either.
+// CHECK: [[ehresume]]
+// CHECK: resume
diff --git a/test/CodeGen/exceptions-seh-leave.c b/test/CodeGen/exceptions-seh-leave.c
new file mode 100644
index 0000000..7901c8c
--- /dev/null
+++ b/test/CodeGen/exceptions-seh-leave.c
@@ -0,0 +1,239 @@
+// RUN: %clang_cc1 %s -triple x86_64-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s
+
+void g();
+
+//////////////////////////////////////////////////////////////////////////////
+// __leave with __except
+
+// Nothing in the __try block can trap, so __try.cont isn't created.
+int __leave_with___except_simple() {
+  int myres = 0;
+  __try {
+    myres = 15;
+    __leave;
+    myres = 23;
+  } __except (1) {
+    return 0;
+  }
+  return 1;
+}
+// CHECK-LABEL: define i32 @__leave_with___except_simple()
+// CHECK: store i32 15, i32* %myres
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+// CHECK: [[tryleave]]
+// CHECK-NEXT: ret i32 1
+
+
+// The "normal" case.
+int __leave_with___except() {
+  int myres = 0;
+  __try {
+    g();
+    __leave;
+    myres = 23;
+  } __except (1) {
+    return 0;
+  }
+  return 1;
+}
+// CHECK-LABEL: define i32 @__leave_with___except()
+// CHECK: invoke void bitcast (void (...)* @g to void ()*)()
+// CHECK-NEXT:       to label %[[cont:.*]] unwind label %{{.*}}
+// For __excepts, instead of an explicit __try.__leave label, we could use
+// use invoke.cont as __leave jump target instead.  However, not doing this
+// keeps the CodeGen code simpler, __leave is very rare, and SimplifyCFG will
+// simplify this anyways.
+// CHECK: [[cont]]
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+// CHECK: [[tryleave]]
+// CHECK-NEXT: br label %
+
+
+//////////////////////////////////////////////////////////////////////////////
+// __leave with __finally
+
+void abort(void) __attribute__((noreturn));
+
+// Nothing in the __try block can trap, so __finally.cont and friends aren't
+// created.
+int __leave_with___finally_simple() {
+  int myres = 0;
+  __try {
+    myres = 15;
+    __leave;
+    myres = 23;
+  } __finally {
+    return 0;
+  }
+  return 1;
+}
+// CHECK-LABEL: define i32 @__leave_with___finally_simple()
+// CHECK: store i32 15, i32* %myres
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+// CHECK: [[tryleave]]
+// CHECK-NEXT: store i8 0, i8* %
+// CHECK-NEXT: br label %
+
+// __finally block doesn't return, __finally.cont doesn't exist.
+int __leave_with___finally_noreturn() {
+  int myres = 0;
+  __try {
+    myres = 15;
+    __leave;
+    myres = 23;
+  } __finally {
+    abort();
+  }
+  return 1;
+}
+// CHECK-LABEL: define i32 @__leave_with___finally_noreturn()
+// CHECK: store i32 15, i32* %myres
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+// CHECK: [[tryleave]]
+// CHECK-NEXT: store i8 0, i8* %
+// CHECK-NEXT: br label %
+
+// The "normal" case.
+int __leave_with___finally() {
+  int myres = 0;
+  __try {
+    g();
+    __leave;
+    myres = 23;
+  } __finally {
+    return 0;
+  }
+  return 1;
+}
+// CHECK-LABEL: define i32 @__leave_with___finally()
+// CHECK: invoke void bitcast (void (...)* @g to void ()*)()
+// CHECK-NEXT:       to label %[[cont:.*]] unwind label %{{.*}}
+// For __finally, there needs to be an explicit __try.__leave, because
+// abnormal.termination.slot needs to be set there.
+// CHECK: [[cont]]
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+// CHECK: [[tryleave]]
+// CHECK-NEXT: store i8 0, i8* %
+// CHECK-NEXT: br label %
+
+
+//////////////////////////////////////////////////////////////////////////////
+// Mixed, nested cases.
+
+// FIXME: Test with outer __finally once PR22553 is fixed.
+
+int nested___except___finally() {
+  int myres = 0;
+  __try {
+    __try {
+      g();
+    } __finally {
+      g();
+      __leave;  // Refers to the outer __try, not the __finally!
+      myres = 23;
+      return 0;
+    }
+
+    myres = 51;
+  } __except (1) {
+  }
+  return 1;
+}
+// The order of basic blocks in the below doesn't matter.
+// CHECK-LABEL: define i32 @nested___except___finally()
+
+// CHECK-LABEL: invoke void bitcast (void (...)* @g to void ()*)()
+// CHECK-NEXT:       to label %[[g1_cont:.*]] unwind label %[[g1_lpad:.*]]
+
+// CHECK: [[g1_cont]]
+// CHECK-NEXT: store i8 0, i8* %[[abnormal:[^ ]*]]
+// CHECK-NEXT: br label %[[finally:[^ ]*]]
+
+// CHECK: [[finally]]
+// CHECK-NEXT: invoke void bitcast (void (...)* @g to void ()*)()
+// CHECK-NEXT:       to label %[[g2_cont:.*]] unwind label %[[g2_lpad:.*]]
+
+// CHECK: [[g2_cont]]
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+
+// Unused __finally continuation block
+// CHECK: store i32 51, i32* %
+// CHECK-NEXT: br label %[[tryleave]]
+
+// CHECK: [[tryleave]]
+// CHECK-NEXT: br label %[[trycont:[^ ]*]]
+
+// CHECK: [[g1_lpad]]
+// CHECK: store i8 1, i8* %
+// CHECK-NEXT:  br label %[[finally]]
+
+// CHECK: [[g2_lpad]]
+// CHECK-NOT: %[[abnormal]]
+// CHECK: br label %[[except:[^ ]*]]
+
+// CHECK: [[except]]
+// CHECK-NEXT: br label %[[trycont]]
+
+// CHECK: [[trycont]]
+// CHECK-NEXT: ret i32 1
+
+int nested___except___except() {
+  int myres = 0;
+  __try {
+    __try {
+      g();
+      myres = 16;
+    } __except (1) {
+      g();
+      __leave;  // Refers to the outer __try, not the __except we're in!
+      myres = 23;
+      return 0;
+    }
+
+    myres = 51;
+  } __except (1) {
+  }
+  return 1;
+}
+// The order of basic blocks in the below doesn't matter.
+// CHECK-LABEL: define i32 @nested___except___except()
+
+// CHECK-LABEL: invoke void bitcast (void (...)* @g to void ()*)()
+// CHECK-NEXT:       to label %[[g1_cont:.*]] unwind label %[[g1_lpad:.*]]
+
+// CHECK: [[g1_cont]]
+// CHECK: store i32 16, i32* %myres
+// CHECK-NEXT: br label %[[trycont:[^ ]*]]
+
+// CHECK: [[g1_lpad]]
+// CHECK:  br label %[[except:[^ ]*]]
+
+// CHECK: [[except]]
+// CHECK-NEXT: invoke void bitcast (void (...)* @g to void ()*)() #3
+// CHECK-NEXT:       to label %[[g2_cont:.*]] unwind label %[[g2_lpad:.*]]
+
+// CHECK: [[g2_cont]]
+// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
+// CHECK-NOT: store i32 23
+
+// CHECK: [[g2_lpad]]
+// CHECK: br label %[[outerexcept:[^ ]*]]
+
+// CHECK: [[outerexcept]]
+// CHECK-NEXT: br label %[[trycont4:[^ ]*]]
+
+// CHECK: [[trycont4]]
+// CHECK-NEXT: ret i32 1
+
+// CHECK: [[trycont]]
+// CHECK-NEXT: store i32 51, i32* %myres
+// CHECK-NEXT: br label %[[tryleave]]
+
+// CHECK: [[tryleave]]
+// CHECK-NEXT: br label %[[trycont4]]
diff --git a/test/CodeGen/exceptions-seh.c b/test/CodeGen/exceptions-seh.c
index 0a82e37..ebe97be 100644
--- a/test/CodeGen/exceptions-seh.c
+++ b/test/CodeGen/exceptions-seh.c
@@ -1,19 +1,183 @@
-// RUN: not %clang_cc1 -triple i686-pc-win32 -fexceptions -fms-extensions -emit-llvm -o - %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 %s -triple x86_64-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s
 
-// This is a codegen test because we only emit the diagnostic when we start
-// generating code.
+// FIXME: Perform this outlining automatically CodeGen.
+void try_body(int numerator, int denominator, int *myres) {
+  *myres = numerator / denominator;
+}
+// CHECK-LABEL: define void @try_body(i32 %numerator, i32 %denominator, i32* %myres)
+// CHECK: sdiv i32
+// CHECK: store i32 %{{.*}}, i32*
+// CHECK: ret void
 
-int SaveDiv(int numerator, int denominator, int *res) {
+int safe_div(int numerator, int denominator, int *res) {
   int myres = 0;
+  int success = 1;
   __try {
-    myres = numerator / denominator;
-    __leave;
+    try_body(numerator, denominator, &myres);
   } __except (1) {
-    return 0;
+    success = -42;
   }
   *res = myres;
-  return 1;
+  return success;
 }
-// CHECK-NOT: error:
-// CHECK: error: cannot compile this SEH __try yet
-// CHECK-NOT: error:
+// CHECK-LABEL: define i32 @safe_div(i32 %numerator, i32 %denominator, i32* %res)
+// CHECK: invoke void @try_body(i32 %{{.*}}, i32 %{{.*}}, i32* %{{.*}}) #[[NOINLINE:[0-9]+]]
+// CHECK:       to label %{{.*}} unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[lpad]]
+// CHECK: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*)
+// CHECK-NEXT: catch i8* null
+// CHECK-NOT: br i1
+// CHECK: br label %[[except:[^ ]*]]
+// CHECK: [[except]]
+// CHECK-NEXT: store i32 -42, i32* %[[success:[^ ]*]]
+//
+// CHECK: %[[res:[^ ]*]] = load i32* %[[success]]
+// CHECK: ret i32 %[[res]]
+
+void j(void);
+
+// FIXME: Implement local variable captures in filter expressions.
+int filter_expr_capture(void) {
+  int r = 42;
+  __try {
+    j();
+  } __except(/*r =*/ -1) {
+    r = 13;
+  }
+  return r;
+}
+
+// CHECK-LABEL: define i32 @filter_expr_capture()
+// FIXMECHECK: %[[captures]] = call i8* @llvm.frameallocate(i32 4)
+// CHECK: store i32 42, i32* %[[r:[^ ,]*]]
+// CHECK: invoke void @j() #[[NOINLINE]]
+//
+// CHECK: landingpad
+// CHECK-NEXT: catch i8* bitcast (i32 (i8*, i8*)* @"\01?filt$0@0@filter_expr_capture@@" to i8*)
+// CHECK: store i32 13, i32* %[[r]]
+//
+// CHECK: %[[rv:[^ ]*]] = load i32* %[[r]]
+// CHECK: ret i32 %[[rv]]
+
+// CHECK-LABEL: define internal i32 @"\01?filt$0@0@filter_expr_capture@@"(i8* %exception_pointers, i8* %frame_pointer)
+// FIXMECHECK: %[[captures]] = call i8* @llvm.framerecover(i8* bitcast (i32 ()* @filter_expr_capture, i8* %frame_pointer)
+// FIXMECHECK: store i32 -1, i32* %{{.*}}
+// CHECK: ret i32 -1
+
+int nested_try(void) {
+  int r = 42;
+  __try {
+    __try {
+      j();
+      r = 0;
+    } __except(_exception_code() == 123) {
+      r = 123;
+    }
+  } __except(_exception_code() == 456) {
+    r = 456;
+  }
+  return r;
+}
+// CHECK-LABEL: define i32 @nested_try()
+// CHECK: store i32 42, i32* %[[r:[^ ,]*]]
+// CHECK: invoke void @j() #[[NOINLINE]]
+// CHECK:       to label %[[cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[cont]]
+// CHECK: store i32 0, i32* %[[r]]
+// CHECK: br label %[[inner_try_cont:[^ ]*]]
+//
+// CHECK: [[lpad]]
+// CHECK: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*)
+// CHECK: catch i8* bitcast (i32 (i8*, i8*)* @"\01?filt$1@0@nested_try@@" to i8*)
+// CHECK: catch i8* bitcast (i32 (i8*, i8*)* @"\01?filt$0@0@nested_try@@" to i8*)
+// CHECK: store i8* %{{.*}}, i8** %[[ehptr_slot:[^ ]*]]
+// CHECK: store i32 %{{.*}}, i32* %[[sel_slot:[^ ]*]]
+//
+// CHECK: load i32* %[[sel_slot]]
+// CHECK: call i32 @llvm.eh.typeid.for(i8* bitcast (i32 (i8*, i8*)* @"\01?filt$1@0@nested_try@@" to i8*))
+// CHECK: icmp eq i32
+// CHECK: br i1
+//
+// CHECK: load i32* %[[sel_slot]]
+// CHECK: call i32 @llvm.eh.typeid.for(i8* bitcast (i32 (i8*, i8*)* @"\01?filt$0@0@nested_try@@" to i8*))
+// CHECK: icmp eq i32
+// CHECK: br i1
+//
+// CHECK: store i32 456, i32* %[[r]]
+// CHECK: br label %[[outer_try_cont:[^ ]*]]
+//
+// CHECK: [[outer_try_cont]]
+// CHECK: %[[r_load:[^ ]*]] = load i32* %[[r]]
+// CHECK: ret i32 %[[r_load]]
+//
+// CHECK: store i32 123, i32* %[[r]]
+// CHECK: br label %[[inner_try_cont]]
+//
+// CHECK: [[inner_try_cont]]
+// CHECK: br label %[[outer_try_cont]]
+
+// FIXME: This lowering of __finally can't actually work, it will have to
+// change.
+static unsigned g = 0;
+void basic_finally(void) {
+  ++g;
+  __try {
+    j();
+  } __finally {
+    --g;
+  }
+}
+// CHECK-LABEL: define void @basic_finally()
+// CHECK: load i32* @g
+// CHECK: add i32 %{{.*}}, 1
+// CHECK: store i32 %{{.*}}, i32* @g
+//
+// CHECK: invoke void @j()
+// CHECK:       to label %[[cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[cont]]
+// CHECK: br label %[[finally:[^ ]*]]
+//
+// CHECK: [[finally]]
+// CHECK: load i32* @g
+// CHECK: add i32 %{{.*}}, -1
+// CHECK: store i32 %{{.*}}, i32* @g
+// CHECK: icmp eq
+// CHECK: br i1 %{{.*}}, label
+//
+// CHECK: ret void
+//
+// CHECK: [[lpad]]
+// CHECK: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*)
+// CHECK-NEXT: cleanup
+// CHECK: br label %[[finally]]
+//
+// CHECK: resume
+
+int returns_int(void);
+int except_return(void) {
+  __try {
+    return returns_int();
+  } __except(1) {
+    return 42;
+  }
+}
+// CHECK-LABEL: define i32 @except_return()
+// CHECK: %[[tmp:[^ ]*]] = invoke i32 @returns_int()
+// CHECK:       to label %[[cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[cont]]
+// CHECK: store i32 %[[tmp]], i32* %[[rv:[^ ]*]]
+// CHECK: br label %[[retbb:[^ ]*]]
+//
+// CHECK: [[lpad]]
+// CHECK: store i32 42, i32* %[[rv]]
+// CHECK: br label %[[retbb]]
+//
+// CHECK: [[retbb]]
+// CHECK: %[[r:[^ ]*]] = load i32* %[[rv]]
+// CHECK: ret i32 %[[r]]
+
+// CHECK: attributes #[[NOINLINE]] = { {{.*noinline.*}} }
diff --git a/test/CodeGen/finite-math.c b/test/CodeGen/finite-math.c
index b0ee157..fd8fcf6 100644
--- a/test/CodeGen/finite-math.c
+++ b/test/CodeGen/finite-math.c
@@ -1,11 +1,15 @@
-// RUN: %clang_cc1 -ffinite-math-only -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -ffinite-math-only -emit-llvm -o - %s | FileCheck %s -check-prefix=CHECK -check-prefix=FINITE
+// RUN: %clang_cc1 -fno-signed-zeros -emit-llvm -o - %s | FileCheck %s -check-prefix=CHECK  -check-prefix=NSZ
+
 float f0, f1, f2;
 
 void foo(void) {
   // CHECK-LABEL: define void @foo()
 
-  // CHECK: fadd nnan ninf
+  // FINITE: fadd nnan ninf
+  // NSZ: fadd nsz
   f0 = f1 + f2;
 
   // CHECK: ret
 }
+
diff --git a/test/CodeGen/funique-sections.c b/test/CodeGen/funique-sections.c
new file mode 100644
index 0000000..1473fe5
--- /dev/null
+++ b/test/CodeGen/funique-sections.c
@@ -0,0 +1,13 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-pc-linux -S -ffunction-sections -fdata-sections -fno-unique-section-names  -o - < %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-pc-linux -S -ffunction-sections -fdata-sections -o - < %s | FileCheck %s --check-prefix=UNIQUE
+
+const int hello = 123;
+void world() {}
+
+// CHECK: .section .text,"ax",@progbits,unique
+// CHECK: .section .rodata,"a",@progbits,unique
+
+// UNIQUE: .section .text.world,"ax",@progbits
+// UNIQUE: .section .rodata.hello,"a",@progbits
diff --git a/test/CodeGen/inline-asm-matching-constraint.c b/test/CodeGen/inline-asm-matching-constraint.c
new file mode 100644
index 0000000..45c387f
--- /dev/null
+++ b/test/CodeGen/inline-asm-matching-constraint.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple powerpc64le-linux-gnu | FileCheck %s
+// Sadly since this requires a register constraint to trigger we have to set
+// a target here.
+void a(void) {
+  register unsigned long __sc_0 __asm__("r0");
+  __asm__ __volatile__("mfcr %0" : "=&r"(__sc_0) : "0"(__sc_0));
+}
+
+// Check that we can generate code for this correctly. The matching input
+// constraint should not have an early clobber on it.
+// CHECK: call i64 asm sideeffect "mfcr $0", "=&{r0},{r0}"
diff --git a/test/CodeGen/inline.c b/test/CodeGen/inline.c
index 96c9a86..612f17c 100644
--- a/test/CodeGen/inline.c
+++ b/test/CodeGen/inline.c
@@ -17,8 +17,8 @@
 // CHECK1-LABEL: define void @testA
 // CHECK1-LABEL: define void @testB
 // CHECK1-LABEL: define void @testC
-// CHECK1-LABEL: define available_externally void @gnu_ei_inline()
 // CHECK1-LABEL: define available_externally i32 @ei()
+// CHECK1-LABEL: define available_externally void @gnu_ei_inline()
 
 // RUN: echo "C99 tests:"
 // RUN: %clang_cc1 %s -triple i386-unknown-unknown -O1 -disable-llvm-optzns -emit-llvm -o - -std=gnu99 | FileCheck %s --check-prefix=CHECK2
@@ -39,8 +39,8 @@
 // CHECK2-LABEL: define void @testA
 // CHECK2-LABEL: define void @testB
 // CHECK2-LABEL: define void @testC
-// CHECK2-LABEL: define available_externally void @gnu_ei_inline()
 // CHECK2-LABEL: define available_externally i32 @foo()
+// CHECK2-LABEL: define available_externally void @gnu_ei_inline()
 
 // RUN: echo "C++ tests:"
 // RUN: %clang_cc1 -x c++ %s -triple i386-unknown-unknown -O1 -disable-llvm-optzns -emit-llvm -o - -std=c++98 | FileCheck %s --check-prefix=CHECK3
@@ -58,8 +58,8 @@
 // CHECK4-NOT: unreferenced1
 // CHECK4-LABEL: define weak_odr void @unreferenced2()
 // CHECK4-LABEL: define void @gnu_inline()
-// CHECK4-LABEL: define available_externally void @gnu_ei_inline()
 // CHECK4-LABEL: define linkonce_odr i32 @foo()
+// CHECK4-LABEL: define available_externally void @gnu_ei_inline()
 
 extern __inline int ei() { return 123; }
 
diff --git a/test/CodeGen/kr-func-promote.c b/test/CodeGen/kr-func-promote.c
index fcdbac3..8e55dc9 100644
--- a/test/CodeGen/kr-func-promote.c
+++ b/test/CodeGen/kr-func-promote.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -triple i386-unknown-unknown %s -emit-llvm -o - | grep "i32 @a(i32)"
+// RUN: %clang_cc1 -triple i386-unknown-unknown %s -emit-llvm -o - | FileCheck %s
+// CHECK: i32 @a(i32)
 
 int a();
 int a(x) short x; {return x;}
diff --git a/test/CodeGen/lineno-dbginfo.c b/test/CodeGen/lineno-dbginfo.c
index 20f1949..28c7243 100644
--- a/test/CodeGen/lineno-dbginfo.c
+++ b/test/CodeGen/lineno-dbginfo.c
@@ -1,6 +1,6 @@
 // RUN: echo "#include <stddef.h>" > %t.h
 // RUN: %clang_cc1 -S -g -include %t.h %s -emit-llvm -o - | FileCheck %s
 
-// CHECK: metadata !"0x34\00outer\00outer\00\00[[@LINE+1]]\000\001"
+// CHECK: !"0x34\00outer\00outer\00\00[[@LINE+1]]\000\001"
 int outer = 42;
 
diff --git a/test/CodeGen/linetable-endscope.c b/test/CodeGen/linetable-endscope.c
index 236f605..9a737cf 100644
--- a/test/CodeGen/linetable-endscope.c
+++ b/test/CodeGen/linetable-endscope.c
@@ -11,7 +11,7 @@
 void foo(char c)
 {
   int i;
-  // CHECK: ![[CONV]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[CONV]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   i = c;
-  // CHECK: ![[RET]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
diff --git a/test/CodeGen/may-alias.c b/test/CodeGen/may-alias.c
index 4d6f721..520b7ab 100644
--- a/test/CodeGen/may-alias.c
+++ b/test/CodeGen/may-alias.c
@@ -27,16 +27,16 @@
   // PATH: store i32 3, i32* {{%.*}}, !tbaa [[TAG_test1_x:!.*]]
   p2->x = 3;
 }
-// CHECK: metadata !{metadata !"any pointer", metadata [[TYPE_CHAR:!.*]],
-// CHECK: [[TYPE_CHAR]] = metadata !{metadata !"omnipotent char", metadata [[TAG_CXX_TBAA:!.*]],
-// CHECK: [[TAG_CXX_TBAA]] = metadata !{metadata !"Simple C/C++ TBAA"}
-// CHECK: [[TAG_CHAR]] = metadata !{metadata [[TYPE_CHAR]], metadata [[TYPE_CHAR]], i64 0}
-// CHECK: [[TAG_INT]] = metadata !{metadata [[TYPE_INT:!.*]], metadata [[TYPE_INT]], i64 0}
-// CHECK: [[TYPE_INT]] = metadata !{metadata !"int", metadata [[TYPE_CHAR]]
+// CHECK:  !"any pointer", [[TYPE_CHAR:!.*]],
+// CHECK: [[TYPE_CHAR]] = !{!"omnipotent char", [[TAG_CXX_TBAA:!.*]],
+// CHECK: [[TAG_CXX_TBAA]] = !{!"Simple C/C++ TBAA"}
+// CHECK: [[TAG_CHAR]] = !{[[TYPE_CHAR]], [[TYPE_CHAR]], i64 0}
+// CHECK: [[TAG_INT]] = !{[[TYPE_INT:!.*]], [[TYPE_INT]], i64 0}
+// CHECK: [[TYPE_INT]] = !{!"int", [[TYPE_CHAR]]
 
-// PATH: [[TYPE_CHAR:!.*]] = metadata !{metadata !"omnipotent char", metadata !{{.*}}
-// PATH: [[TAG_CHAR]] = metadata !{metadata [[TYPE_CHAR]], metadata [[TYPE_CHAR]], i64 0}
-// PATH: [[TAG_INT]] = metadata !{metadata [[TYPE_INT:!.*]], metadata [[TYPE_INT]], i64 0}
-// PATH: [[TYPE_INT]] = metadata !{metadata !"int", metadata [[TYPE_CHAR]]
-// PATH: [[TAG_test1_x]] = metadata !{metadata [[TYPE_test1:!.*]], metadata [[TYPE_INT]], i64 0}
-// PATH: [[TYPE_test1]] = metadata !{metadata !"Test1", metadata [[TYPE_INT]], i64 0}
+// PATH: [[TYPE_CHAR:!.*]] = !{!"omnipotent char", !{{.*}}
+// PATH: [[TAG_CHAR]] = !{[[TYPE_CHAR]], [[TYPE_CHAR]], i64 0}
+// PATH: [[TAG_INT]] = !{[[TYPE_INT:!.*]], [[TYPE_INT]], i64 0}
+// PATH: [[TYPE_INT]] = !{!"int", [[TYPE_CHAR]]
+// PATH: [[TAG_test1_x]] = !{[[TYPE_test1:!.*]], [[TYPE_INT]], i64 0}
+// PATH: [[TYPE_test1]] = !{!"Test1", [[TYPE_INT]], i64 0}
diff --git a/test/CodeGen/merge-statics.c b/test/CodeGen/merge-statics.c
index 6716935..4baf902 100644
--- a/test/CodeGen/merge-statics.c
+++ b/test/CodeGen/merge-statics.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 < %s -emit-llvm | grep internal | count 1
+// RUN: %clang_cc1 < %s -emit-llvm | FileCheck %s
 
 // The two decls for 'a' should merge into one llvm GlobalVariable.
 
@@ -11,3 +11,6 @@
     10
 };
 
+// CHECK-NOT: internal global
+// CHECK: @a = internal global %struct.s { i32 10 }
+// CHECK-NOT: internal-global
diff --git a/test/CodeGen/mips-constraint-regs.c b/test/CodeGen/mips-constraint-regs.c
index 0d533f5..4dfd62d 100644
--- a/test/CodeGen/mips-constraint-regs.c
+++ b/test/CodeGen/mips-constraint-regs.c
@@ -9,7 +9,7 @@
   // 'c': 16 bit address register for Mips16, GPR for all others
   // I am using 'c' to constrain both the target and one of the source
   // registers. We are looking for syntactical correctness.
-  // CHECK: %{{[0-9]+}} = call i32 asm sideeffect "addi $0,$1,$2 \0A\09\09", "=c,c,I"(i32 %{{[0-9]+}}, i32 %{{[0-9]+}}) [[NUW:#[0-9]+]], !srcloc !{{[0-9]+}}
+  // CHECK: %{{[0-9]+}} = call i32 asm sideeffect "addi $0,$1,$2 \0A\09\09", "=c,c,I,~{$1}"(i32 %{{[0-9]+}}, i32 %{{[0-9]+}}) [[NUW:#[0-9]+]], !srcloc !{{[0-9]+}}
   int __s, __v = 17;
   int __t;
   __asm__ __volatile__(
@@ -20,7 +20,7 @@
   // 'l': lo register
   // We are making it clear that destination register is lo with the
   // use of the 'l' constraint ("=l").
-  // CHECK:   %{{[0-9]+}} = call i32 asm sideeffect "mtlo $1 \0A\09\09", "=l,r,~{lo}"(i32 %{{[0-9]+}}) [[NUW]], !srcloc !{{[0-9]+}}
+  // CHECK:   %{{[0-9]+}} = call i32 asm sideeffect "mtlo $1 \0A\09\09", "=l,r,~{lo},~{$1}"(i32 %{{[0-9]+}}) [[NUW]], !srcloc !{{[0-9]+}}
   int i_temp = 44;
   int i_result;
   __asm__ __volatile__(
@@ -32,7 +32,7 @@
   // 'x': Combined lo/hi registers
   // We are specifying that destination registers are the hi/lo pair with the
   // use of the 'x' constraint ("=x").
-  // CHECK:  %{{[0-9]+}} = call i64 asm sideeffect "mthi $1 \0A\09\09mtlo $2 \0A\09\09", "=x,r,r"(i32 %{{[0-9]+}}, i32 %{{[0-9]+}}) [[NUW]], !srcloc !{{[0-9]+}}
+  // CHECK:  %{{[0-9]+}} = call i64 asm sideeffect "mthi $1 \0A\09\09mtlo $2 \0A\09\09", "=x,r,r,~{$1}"(i32 %{{[0-9]+}}, i32 %{{[0-9]+}}) [[NUW]], !srcloc !{{[0-9]+}}
   int i_hi = 3;
   int i_lo = 2;
   long long ll_result = 0;
diff --git a/test/CodeGen/mips-constraints-mem.c b/test/CodeGen/mips-constraints-mem.c
index 2c3c01a..295d67c 100644
--- a/test/CodeGen/mips-constraints-mem.c
+++ b/test/CodeGen/mips-constraints-mem.c
@@ -9,7 +9,7 @@
  // 'R': An address that can be used in a non-macro load or stor'
  // This test will result in the higher and lower nibbles being
  // switched due to the lwl/lwr instruction pairs.
- // CHECK:   %{{[0-9]+}} = call i32 asm sideeffect  "lwl $0, 1 + $1\0A\09lwr $0, 2 + $1\0A\09", "=r,*R"(i32* %{{[0-9,a-f]+}}) #1,
+ // CHECK:   %{{[0-9]+}} = call i32 asm sideeffect  "lwl $0, 1 + $1\0A\09lwr $0, 2 + $1\0A\09", "=r,*R,~{$1}"(i32* %{{[0-9,a-f]+}}) #1,
 
   int c = 0xffbbccdd;
 
diff --git a/test/CodeGen/mips-inline-asm-modifiers.c b/test/CodeGen/mips-inline-asm-modifiers.c
index 9d697e8..9437dbe 100644
--- a/test/CodeGen/mips-inline-asm-modifiers.c
+++ b/test/CodeGen/mips-inline-asm-modifiers.c
@@ -7,9 +7,9 @@
 
 typedef int v4i32 __attribute__((vector_size(16)));
 
-  // CHECK: %{{[0-9]+}} = call i32 asm ".set noreorder;\0Alw    $0,$1;\0A.set reorder;\0A", "=r,*m"(i32* getelementptr inbounds ([8 x i32]* @b, i32 {{[0-9]+}}, i32 {{[0-9]+}})) #2,
-  // CHECK: %{{[0-9]+}} = call i32 asm "lw    $0,${1:D};\0A", "=r,*m"(i32* getelementptr inbounds ([8 x i32]* @b, i32 {{[0-9]+}}, i32 {{[0-9]+}})) #2,
-  // CHECK: %{{[0-9]+}} = call <4 x i32> asm "ldi.w ${0:w},1", "=f"
+  // CHECK: %{{[0-9]+}} = call i32 asm ".set noreorder;\0Alw    $0,$1;\0A.set reorder;\0A", "=r,*m,~{$1}"(i32* getelementptr inbounds ([8 x i32]* @b, i32 {{[0-9]+}}, i32 {{[0-9]+}})) #2,
+  // CHECK: %{{[0-9]+}} = call i32 asm "lw    $0,${1:D};\0A", "=r,*m,~{$1}"(i32* getelementptr inbounds ([8 x i32]* @b, i32 {{[0-9]+}}, i32 {{[0-9]+}})) #2,
+  // CHECK: %{{[0-9]+}} = call <4 x i32> asm "ldi.w ${0:w},1", "=f,~{$1}"
 int b[8] = {0,1,2,3,4,5,6,7};
 int  main()
 {
diff --git a/test/CodeGen/mips-transparent-union.c b/test/CodeGen/mips-transparent-union.c
new file mode 100644
index 0000000..ad417dd
--- /dev/null
+++ b/test/CodeGen/mips-transparent-union.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple mips64-linux-gnu -S -o - -emit-llvm %s | FileCheck %s
+//
+// Transparent unions are passed according to the calling convention rules of
+// the first member. In this case, it is as if it were a void pointer so we
+// do not have the inreg attribute we would normally have for unions.
+//
+// This comes up in glibc's wait() function and matters for the big-endian N32
+// case where pointers are promoted to i64 and a non-transparent union would be
+// passed in the upper 32-bits of an i64.
+
+union either_pointer {
+  void *void_ptr;
+  int *int_ptr;
+} __attribute__((transparent_union));
+
+extern void foo(union either_pointer p);
+
+int data;
+
+void bar(void) {
+  return foo(&data);
+}
+
+// CHECK-LABEL: define void @bar()
+// CHECK:         call void @foo(i8* %{{[0-9]+}})
+
+// CHECK: declare void @foo(i8*)
diff --git a/test/CodeGen/mips-varargs.c b/test/CodeGen/mips-varargs.c
index e8b6e29..383831f 100644
--- a/test/CodeGen/mips-varargs.c
+++ b/test/CodeGen/mips-varargs.c
@@ -33,13 +33,11 @@
 // NEW:   [[TMP0:%.+]] = bitcast i8** %va to i64**
 // NEW:   [[AP_CUR:%.+]] = load i64** [[TMP0]], align [[PTRALIGN]]
 //
-// O32:   [[TMP1:%.+]] = getelementptr i32* [[AP_CUR]], i32 1
-// O32:   [[AP_NEXT:%.+]] = bitcast i32* [[TMP1]] to i8*
-// N32:   [[TMP1:%.+]] = getelementptr i64* [[AP_CUR]], {{i32|i64}} 1
-// N64:   [[TMP1:%.+]] = getelementptr i64* [[AP_CUR]], {{i32|i64}} 1
-// NEW:   [[AP_NEXT:%.+]] = bitcast i64* [[TMP1]] to i8*
+// O32:   [[AP_NEXT:%.+]] = getelementptr i32* [[AP_CUR]], i32 1
+// NEW:   [[AP_NEXT:%.+]] = getelementptr i64* [[AP_CUR]], {{i32|i64}} 1
 //
-// ALL:   store i8* [[AP_NEXT]], i8** %va, align [[PTRALIGN]]
+// O32:   store i32* [[AP_NEXT]], i32** [[TMP0]], align [[PTRALIGN]]
+// NEW:   store i64* [[AP_NEXT]], i64** [[TMP0]], align [[PTRALIGN]]
 //
 // O32:   [[ARG1:%.+]] = load i32* [[AP_CUR]], align 4
 // NEW:   [[TMP2:%.+]] = load i64* [[AP_CUR]], align 8
@@ -71,30 +69,25 @@
 // NEW:   [[TMP0:%.+]] = bitcast i8** %va to i64**
 // NEW:   [[AP_CUR:%.+]] = load i64** [[TMP0]], align [[PTRALIGN]]
 //
-// O32:   [[TMP1:%.+]] = getelementptr i32* [[AP_CUR]], i32 1
-// O32:   [[AP_NEXT:%.+]] = bitcast i32* [[TMP1]] to i8*
-// N32:   [[TMP1:%.+]] = getelementptr i64* [[AP_CUR]], [[INTPTR_T:i32]] 1
-// FIXME: N32 optimised this bitcast out. Why only for this ABI?
-// N64:   [[TMP1:%.+]] = getelementptr i64* [[AP_CUR]], [[INTPTR_T:i64]] 1
-// N64:   [[AP_NEXT:%.+]] = bitcast i64* [[TMP1]] to i8*
+// O32:   [[AP_NEXT1:%.+]] = getelementptr i32* [[AP_CUR]], i32 1
+// NEW:   [[AP_NEXT1:%.+]] = getelementptr i64* [[AP_CUR]], [[INTPTR_T:i32|i64]] 1
 //
-// O32:   store i8* [[AP_NEXT]], i8** %va, align [[PTRALIGN]]
+// O32:   store i32* [[AP_NEXT1]], i32** [[TMP0]], align [[PTRALIGN]]
 // FIXME: N32 optimised this store out. Why only for this ABI?
-// N64:   store i8* [[AP_NEXT]], i8** %va, align [[PTRALIGN]]
+// N64:   store i64* [[AP_NEXT1]], i64** [[TMP0]], align [[PTRALIGN]]
 //
 // O32:   [[ARG1:%.+]] = load i32* [[AP_CUR]], align 4
 // NEW:   [[TMP3:%.+]] = load i64* [[AP_CUR]], align 8
 // NEW:   [[ARG1:%.+]] = trunc i64 [[TMP3]] to i32
 //
-// O32:   [[TMP2:%.+]] = getelementptr i32* [[AP_CUR]], i32 2
-// O32:   [[AP_NEXT:%.+]] = bitcast i32* [[TMP2]] to i8*
-// NEW:   [[TMP2:%.+]] = getelementptr i64* [[AP_CUR]], [[INTPTR_T]] 2
-// NEW:   [[AP_NEXT:%.+]] = bitcast i64* [[TMP2]] to i8*
+// O32:   [[AP_NEXT2:%.+]] = getelementptr i32* [[AP_CUR]], i32 2
+// NEW:   [[AP_NEXT2:%.+]] = getelementptr i64* [[AP_CUR]], [[INTPTR_T]] 2
 //
-// ALL:   store i8* [[AP_NEXT]], i8** %va, align [[PTRALIGN]]
+// O32:   store i32* [[AP_NEXT2]], i32** [[TMP0]], align [[PTRALIGN]]
+// NEW:   store i64* [[AP_NEXT2]], i64** [[TMP0]], align [[PTRALIGN]]
 //
-// O32:   [[ARG2:%.+]] = load i32* [[TMP1]], align 4
-// NEW:   [[TMP4:%.+]] = load i64* [[TMP1]], align 8
+// O32:   [[ARG2:%.+]] = load i32* [[AP_NEXT1]], align 4
+// NEW:   [[TMP4:%.+]] = load i64* [[AP_NEXT1]], align 8
 // NEW:   [[ARG2:%.+]] = trunc i64 [[TMP4]] to i32
 //
 // ALL:   call void @llvm.va_end(i8* [[VA1]])
@@ -131,11 +124,10 @@
 // O32:   [[PTR4:%.+]] = inttoptr [[INTPTR_T]] [[PTR2]] to i8*
 //
 // O32:   [[AP_NEXT:%.+]] = getelementptr i8* [[PTR4]], [[INTPTR_T]] 8
-// N32:   [[TMP1:%.+]] = getelementptr i64* [[AP_CUR]], i32 1
-// N64:   [[TMP1:%.+]] = getelementptr i64* [[AP_CUR]], i64 1
-// NEW:   [[AP_NEXT:%.+]] = bitcast i64* [[TMP1]] to i8*
+// NEW:   [[AP_NEXT:%.+]] = getelementptr i64* [[AP_CUR]], [[INTPTR_T:i32|i64]] 1
 //
-// ALL:   store i8* [[AP_NEXT]], i8** %va, align [[PTRALIGN]]
+// O32:   store i8* [[AP_NEXT]], i8** %va, align [[PTRALIGN]]
+// NEW:   store i64* [[AP_NEXT]], i64** [[TMP0]], align [[PTRALIGN]]
 //
 // O32:   [[ARG1:%.+]] = load i64* [[PTR3]], align 8
 // NEW:   [[ARG1:%.+]] = load i64* [[AP_CUR]], align 8
@@ -144,6 +136,55 @@
 // ALL:   ret i64 [[ARG1]]
 // ALL: }
 
+char *test_ptr(char *fmt, ...) {
+  va_list va;
+
+  va_start(va, fmt);
+  char *v = va_arg(va, char *);
+  va_end(va);
+
+  return v;
+}
+
+// ALL-LABEL: define i8* @test_ptr(i8*{{.*}} %fmt, ...)
+//
+// O32:   %va = alloca i8*, align [[PTRALIGN:4]]
+// N32:   %va = alloca i8*, align [[PTRALIGN:4]]
+// N64:   %va = alloca i8*, align [[PTRALIGN:8]]
+//
+// ALL:   [[VA1:%.+]] = bitcast i8** %va to i8*
+// ALL:   call void @llvm.va_start(i8* [[VA1]])
+//
+// O32:   [[TMP0:%.+]] = bitcast i8** %va to i8***
+// O32:   [[AP_CUR:%.+]] = load i8*** [[TMP0]], align [[PTRALIGN]]
+// N32 differs because the vararg is not a N32 pointer. It's been promoted to 64-bit.
+// N32:   [[TMP0:%.+]] = bitcast i8** %va to i64**
+// N32:   [[AP_CUR:%.+]] = load i64** [[TMP0]], align [[PTRALIGN]]
+// N64:   [[TMP0:%.+]] = bitcast i8** %va to i8***
+// N64:   [[AP_CUR:%.+]] = load i8*** [[TMP0]], align [[PTRALIGN]]
+//
+// O32:   [[AP_NEXT:%.+]] = getelementptr i8** [[AP_CUR]], i32 1
+// N32 differs because the vararg is not a N32 pointer. It's been promoted to 64-bit.
+// N32:   [[AP_NEXT:%.+]] = getelementptr i64* [[AP_CUR]], {{i32|i64}} 1
+// N64:   [[AP_NEXT:%.+]] = getelementptr i8** [[AP_CUR]], {{i32|i64}} 1
+//
+// O32:   store i8** [[AP_NEXT]], i8*** [[TMP0]], align [[PTRALIGN]]
+// N32 differs because the vararg is not a N32 pointer. It's been promoted to 64-bit.
+// N32:   store i64* [[AP_NEXT]], i64** [[TMP0]], align [[PTRALIGN]]
+// N64:   store i8** [[AP_NEXT]], i8*** [[TMP0]], align [[PTRALIGN]]
+//
+// O32:   [[ARG1:%.+]] = load i8** [[AP_CUR]], align 4
+// N32 differs because the vararg is not a N32 pointer. It's been promoted to
+// 64-bit so we must truncate the excess and bitcast to a N32 pointer.
+// N32:   [[TMP2:%.+]] = load i64* [[AP_CUR]], align 8
+// N32:   [[TMP3:%.+]] = trunc i64 [[TMP2]] to i32
+// N32:   [[ARG1:%.+]] = inttoptr i32 [[TMP3]] to i8*
+// N64:   [[ARG1:%.+]] = load i8** [[AP_CUR]], align 8
+//
+// ALL:   call void @llvm.va_end(i8* [[VA1]])
+// ALL:   ret i8* [[ARG1]]
+// ALL: }
+
 int test_v4i32(char *fmt, ...) {
   va_list va;
 
diff --git a/test/CodeGen/ms-align-tentative.c b/test/CodeGen/ms-align-tentative.c
index ccd7616..eb68e69 100644
--- a/test/CodeGen/ms-align-tentative.c
+++ b/test/CodeGen/ms-align-tentative.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple i386-pc-win32 %s -emit-llvm -fms-compatibility -o - | FileCheck %s
+// RUN: %clang_cc1 -triple i386-pc-win32 -emit-llvm -fms-compatibility -o - < %s | FileCheck %s
 
 char __declspec(align(8192)) x;
 // CHECK-DAG: @x = global i8 0, align 8192
@@ -13,3 +13,13 @@
 int __declspec(align(16)) redef;
 int __declspec(align(32)) redef = 8;
 // CHECK-DAG: @redef = global i32 8, align 32
+
+struct __declspec(align(64)) S {
+  char fd;
+} s;
+// CHECK-DAG: @s = global %struct.S zeroinitializer, align 64
+
+struct Wrap {
+  struct S x;
+} w;
+// CHECK-DAG: @w = global %struct.Wrap zeroinitializer, align 64
diff --git a/test/CodeGen/ms-declspecs.c b/test/CodeGen/ms-declspecs.c
index 5dc7787..328fc83 100644
--- a/test/CodeGen/ms-declspecs.c
+++ b/test/CodeGen/ms-declspecs.c
@@ -2,8 +2,8 @@
 
 __declspec(selectany) int x1 = 1;
 const __declspec(selectany) int x2 = 2;
-// CHECK: @x1 = weak_odr global i32 1, align 4
-// CHECK: @x2 = weak_odr constant i32 2, align 4
+// CHECK: @x1 = weak_odr global i32 1, comdat, align 4
+// CHECK: @x2 = weak_odr constant i32 2, comdat, align 4
 
 struct __declspec(align(16)) S {
   char x;
diff --git a/test/CodeGen/ms-intrinsics.c b/test/CodeGen/ms-intrinsics.c
index 3974e91..4498b34 100644
--- a/test/CodeGen/ms-intrinsics.c
+++ b/test/CodeGen/ms-intrinsics.c
@@ -1,15 +1,28 @@
-// RUN: %clang_cc1 -triple i686--windows -fms-compatibility -Oz -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK -check-prefix CHECK-I386
-// RUN: %clang_cc1 -triple thumbv7--windows -fms-compatibility -Oz -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -fms-extensions -fms-compatibility -fms-compatibility-version=17.00 \
+// RUN:         -triple i686--windows -Oz -emit-llvm %s -o - \
+// RUN:         | FileCheck %s -check-prefix CHECK -check-prefix CHECK-I386
+// RUN: %clang_cc1 -ffreestanding -fms-extensions -fms-compatibility -fms-compatibility-version=17.00 \
+// RUN:         -triple thumbv7--windows -Oz -emit-llvm %s -o - \
+// RUN:         | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -fms-extensions -fms-compatibility -fms-compatibility-version=17.00 \
+// RUN:         -triple x86_64--windows -Oz -emit-llvm %s -o - \
+// RUN:         | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-X64
+
+// Intrin.h needs size_t, but -ffreestanding prevents us from getting it from
+// stddef.h.  Work around it with this typedef.
+typedef __SIZE_TYPE__ size_t;
+
+#include <Intrin.h>
 
 void *test_InterlockedExchangePointer(void * volatile *Target, void *Value) {
   return _InterlockedExchangePointer(Target, Value);
 }
 
 // CHECK: define{{.*}}i8* @test_InterlockedExchangePointer(i8** %Target, i8* %Value){{.*}}{
-// CHECK:   %[[TARGET:[0-9]+]] = bitcast i8** %Target to i32*
-// CHECK:   %[[VALUE:[0-9]+]] = ptrtoint i8* %Value to i32
-// CHECK:   %[[EXCHANGE:[0-9]+]] = atomicrmw xchg i32* %[[TARGET]], i32 %[[VALUE]] seq_cst
-// CHECK:   %[[RESULT:[0-9]+]] = inttoptr i32 %[[EXCHANGE]] to i8*
+// CHECK:   %[[TARGET:[0-9]+]] = bitcast i8** %Target to [[iPTR:i[0-9]+]]*
+// CHECK:   %[[VALUE:[0-9]+]] = ptrtoint i8* %Value to [[iPTR]]
+// CHECK:   %[[EXCHANGE:[0-9]+]] = atomicrmw xchg [[iPTR]]* %[[TARGET]], [[iPTR]] %[[VALUE]] seq_cst
+// CHECK:   %[[RESULT:[0-9]+]] = inttoptr [[iPTR]] %[[EXCHANGE]] to i8*
 // CHECK:   ret i8* %[[RESULT]]
 // CHECK: }
 
@@ -19,12 +32,12 @@
 }
 
 // CHECK: define{{.*}}i8* @test_InterlockedCompareExchangePointer(i8** %Destination, i8* %Exchange, i8* %Comparand){{.*}}{
-// CHECK:   %[[DEST:[0-9]+]] = bitcast i8** %Destination to i32*
-// CHECK:   %[[EXCHANGE:[0-9]+]] = ptrtoint i8* %Exchange to i32
-// CHECK:   %[[COMPARAND:[0-9]+]] = ptrtoint i8* %Comparand to i32
-// CHECK:   %[[XCHG:[0-9]+]] = cmpxchg volatile i32* %[[DEST:[0-9]+]], i32 %[[COMPARAND:[0-9]+]], i32 %[[EXCHANGE:[0-9]+]] seq_cst seq_cst
-// CHECK:   %[[EXTRACT:[0-9]+]] = extractvalue { i32, i1 } %[[XCHG]], 0
-// CHECK:   %[[RESULT:[0-9]+]] = inttoptr i32 %[[EXTRACT]] to i8*
+// CHECK:   %[[DEST:[0-9]+]] = bitcast i8** %Destination to [[iPTR]]*
+// CHECK:   %[[EXCHANGE:[0-9]+]] = ptrtoint i8* %Exchange to [[iPTR]]
+// CHECK:   %[[COMPARAND:[0-9]+]] = ptrtoint i8* %Comparand to [[iPTR]]
+// CHECK:   %[[XCHG:[0-9]+]] = cmpxchg volatile [[iPTR]]* %[[DEST:[0-9]+]], [[iPTR]] %[[COMPARAND:[0-9]+]], [[iPTR]] %[[EXCHANGE:[0-9]+]] seq_cst seq_cst
+// CHECK:   %[[EXTRACT:[0-9]+]] = extractvalue { [[iPTR]], i1 } %[[XCHG]], 0
+// CHECK:   %[[RESULT:[0-9]+]] = inttoptr [[iPTR]] %[[EXTRACT]] to i8*
 // CHECK:   ret i8* %[[RESULT:[0-9]+]]
 // CHECK: }
 
@@ -49,3 +62,12 @@
 // CHECK-I386: }
 #endif
 
+#if defined(__x86_64__)
+unsigned __int64 test__umulh(unsigned __int64 a, unsigned __int64 b) {
+  return __umulh(a, b);
+}
+// CHECK-X64-LABEL: define i64 @test__umulh(i64 %a, i64 %b)
+// CHECK-X64: = mul nuw i128 %
+
+#endif
+
diff --git a/test/CodeGen/ms-setjmp.c b/test/CodeGen/ms-setjmp.c
new file mode 100644
index 0000000..5073e08
--- /dev/null
+++ b/test/CodeGen/ms-setjmp.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -fms-extensions -triple i686-windows-msvc   -emit-llvm %s -o - | FileCheck --check-prefix=I386 %s
+// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -emit-llvm %s -o - | FileCheck --check-prefix=X64 %s
+
+typedef char jmp_buf[1];
+
+int _setjmp(jmp_buf env);
+int _setjmpex(jmp_buf env);
+
+jmp_buf jb;
+
+int test_setjmp() {
+  return _setjmp(jb);
+  // I386-LABEL: define i32 @test_setjmp
+  // I386:       %[[call:.*]] = call i32 (i8*, i32, ...)* @_setjmp3(i8* getelementptr inbounds ([1 x i8]* @jb, i32 0, i32 0), i32 0)
+  // I386-NEXT:  ret i32 %[[call]]
+
+  // X64-LABEL: define i32 @test_setjmp
+  // X64:       %[[addr:.*]] = call i8* @llvm.frameaddress(i32 0)
+  // X64:       %[[call:.*]] = call i32 @_setjmp(i8* getelementptr inbounds ([1 x i8]* @jb, i32 0, i32 0), i8* %[[addr]])
+  // X64-NEXT:  ret i32 %[[call]]
+}
+
+int test_setjmpex() {
+  return _setjmpex(jb);
+  // X64-LABEL: define i32 @test_setjmpex
+  // X64:       %[[addr:.*]] = call i8* @llvm.frameaddress(i32 0)
+  // X64:       %[[call:.*]] = call i32 @_setjmpex(i8* getelementptr inbounds ([1 x i8]* @jb, i32 0, i32 0), i8* %[[addr]])
+  // X64-NEXT:  ret i32 %[[call]]
+}
diff --git a/test/CodeGen/ms-volatile.c b/test/CodeGen/ms-volatile.c
new file mode 100644
index 0000000..88e1988
--- /dev/null
+++ b/test/CodeGen/ms-volatile.c
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -triple i386-pc-win32 -emit-llvm -fms-volatile -o - < %s | FileCheck %s
+struct foo {
+  volatile int x;
+};
+struct bar {
+  int x;
+};
+typedef _Complex float __declspec(align(8)) baz;
+
+void test1(struct foo *p, struct foo *q) {
+  *p = *q;
+  // CHECK-LABEL: @test1
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test2(volatile int *p, volatile int *q) {
+  *p = *q;
+  // CHECK-LABEL: @test2
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test3(struct foo *p, struct foo *q) {
+  p->x = q->x;
+  // CHECK-LABEL: @test3
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test4(volatile struct foo *p, volatile struct foo *q) {
+  p->x = q->x;
+  // CHECK-LABEL: @test4
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test5(volatile struct foo *p, volatile struct foo *q) {
+  *p = *q;
+  // CHECK-LABEL: @test5
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test6(struct bar *p, struct bar *q) {
+  *p = *q;
+  // CHECK-LABEL: @test6
+  // CHECK-NOT: load atomic volatile {{.*}}
+  // CHECK-NOT: store atomic volatile {{.*}}, {{.*}}
+}
+void test7(volatile struct bar *p, volatile struct bar *q) {
+  *p = *q;
+  // CHECK-LABEL: @test7
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test8(volatile double *p, volatile double *q) {
+  *p = *q;
+  // CHECK-LABEL: @test8
+  // CHECK: load atomic volatile {{.*}} acquire
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
+void test9(volatile baz *p, baz *q) {
+  *p = *q;
+  // CHECK-LABEL: @test9
+  // CHECK: store atomic volatile {{.*}}, {{.*}} release
+}
diff --git a/test/CodeGen/mult-alt-generic.c b/test/CodeGen/mult-alt-generic.c
index 6c9d789..303edfc 100644
--- a/test/CodeGen/mult-alt-generic.c
+++ b/test/CodeGen/mult-alt-generic.c
@@ -17,7 +17,7 @@
 // CHECK: @single_m
 void single_m()
 {
-  // CHECK: call void asm "foo $1,$0", "=*m,*m[[CLOBBERS:[a-zA-Z0-9@%{},~_ ]*\"]](i32* {{[a-zA-Z0-9@%]+}}, i32* {{[a-zA-Z0-9@%]+}})
+  // CHECK: call void asm "foo $1,$0", "=*m,*m[[CLOBBERS:[a-zA-Z0-9@%{},~_$ ]*\"]](i32* {{[a-zA-Z0-9@%]+}}, i32* {{[a-zA-Z0-9@%]+}})
   asm("foo %1,%0" : "=m" (mout0) : "m" (min1));
 }
 
diff --git a/test/CodeGen/named_reg_global.c b/test/CodeGen/named_reg_global.c
index 8117dae..d888a3f 100644
--- a/test/CodeGen/named_reg_global.c
+++ b/test/CodeGen/named_reg_global.c
@@ -44,4 +44,4 @@
 // CHECK: call void @llvm.write_register.i[[bits]](metadata !0, i[[bits]] %[[regw]])
 
 // CHECK: !llvm.named.register.sp = !{!0}
-// CHECK: !0 = metadata !{metadata !"sp"}
+// CHECK: !0 = !{!"sp"}
diff --git a/test/CodeGen/piclevels.c b/test/CodeGen/piclevels.c
index 1cd750c..54744e2 100644
--- a/test/CodeGen/piclevels.c
+++ b/test/CodeGen/piclevels.c
@@ -2,6 +2,6 @@
 // RUN: %clang_cc1 -emit-llvm -pic-level 1 %s -o - | FileCheck %s -check-prefix=CHECK-SMALLPIC
 
 // CHECK-BIGPIC: !llvm.module.flags = !{{{.*}}}
-// CHECK-BIGPIC: !{{[0-9]+}} = metadata !{i32 1, metadata !"PIC Level", i32 2}
+// CHECK-BIGPIC: !{{[0-9]+}} = !{i32 1, !"PIC Level", i32 2}
 // CHECK-SMALLPIC: !llvm.module.flags = !{{{.*}}}
-// CHECK-SMALLPIC: !{{[0-9]+}} = metadata !{i32 1, metadata !"PIC Level", i32 1}
+// CHECK-SMALLPIC: !{{[0-9]+}} = !{i32 1, !"PIC Level", i32 1}
diff --git a/test/CodeGen/pointer-signext.c b/test/CodeGen/pointer-signext.c
index e809eff..ac51ffc 100644
--- a/test/CodeGen/pointer-signext.c
+++ b/test/CodeGen/pointer-signext.c
@@ -4,8 +4,8 @@
 // cause any sign extensions.
 
 // CHECK:      [[P:%.*]] = add i64 %param, -8
-// CHECK-NEXT: [[Q:%.*]] = inttoptr i64 [[P]] to [[R:%.*\*]]
-// CHECK-NEXT: {{%.*}} = getelementptr inbounds [[R]] [[Q]], i64 0, i32 0
+// CHECK-NEXT: [[Q:%.*]] = inttoptr i64 [[P]] to [[R:%.*]]*
+// CHECK-NEXT: {{%.*}} = getelementptr inbounds [[R]]* [[Q]], i64 0, i32 0
 
 #define CR(Record, TYPE, Field) \
   ((TYPE *) ((unsigned char *) (Record) - (unsigned char *) &(((TYPE *) 0)->Field)))
diff --git a/test/CodeGen/pr5406.c b/test/CodeGen/pr5406.c
index 2d19822..0f04a8e 100644
--- a/test/CodeGen/pr5406.c
+++ b/test/CodeGen/pr5406.c
@@ -6,7 +6,7 @@
 void foo (int i, ...);
 
 
-// CHECK: call arm_aapcscc  void (i32, ...)* @foo(i32 1, [1 x i32] {{.*}})
+// CHECK: call void (i32, ...)* @foo(i32 1, [1 x i32] {{.*}})
 int main (void)
 {
   A0 a3;
diff --git a/test/CodeGen/pragma-comment.c b/test/CodeGen/pragma-comment.c
index 73cc548..0a7d3c7 100644
--- a/test/CodeGen/pragma-comment.c
+++ b/test/CodeGen/pragma-comment.c
@@ -1,23 +1,33 @@
 // RUN: %clang_cc1 %s -triple i686-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s
 // RUN: %clang_cc1 %s -triple x86_64-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s
 // RUN: %clang_cc1 %s -triple i686-pc-linux -fms-extensions -emit-llvm -o - | FileCheck -check-prefix LINUX %s
+// RUN: %clang_cc1 %s -triple x86_64-scei-ps4 -fms-extensions -emit-llvm -o - | FileCheck -check-prefix PS4 %s
 
 #pragma comment(lib, "msvcrt.lib")
 #pragma comment(lib, "kernel32")
 #pragma comment(lib, "USER32.LIB")
+#pragma comment(lib, "with space")
 
 #define BAR "2"
 #pragma comment(linker," /bar=" BAR)
+#pragma comment(linker," /foo=\"foo bar\"")
 
 // CHECK: !llvm.module.flags = !{{{.*}}}
-// CHECK: !{{[0-9]+}} = metadata !{i32 6, metadata !"Linker Options", metadata ![[link_opts:[0-9]+]]}
-// CHECK: ![[link_opts]] = metadata !{metadata ![[msvcrt:[0-9]+]], metadata ![[kernel32:[0-9]+]], metadata ![[USER32:[0-9]+]], metadata ![[bar:[0-9]+]]}
-// CHECK: ![[msvcrt]] = metadata !{metadata !"/DEFAULTLIB:msvcrt.lib"}
-// CHECK: ![[kernel32]] = metadata !{metadata !"/DEFAULTLIB:kernel32.lib"}
-// CHECK: ![[USER32]] = metadata !{metadata !"/DEFAULTLIB:USER32.LIB"}
-// CHECK: ![[bar]] = metadata !{metadata !" /bar=2"}
+// CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[link_opts:[0-9]+]]}
+// CHECK: ![[link_opts]] = !{![[msvcrt:[0-9]+]], ![[kernel32:[0-9]+]], ![[USER32:[0-9]+]], ![[space:[0-9]+]], ![[bar:[0-9]+]], ![[foo:[0-9]+]]}
+// CHECK: ![[msvcrt]] = !{!"/DEFAULTLIB:msvcrt.lib"}
+// CHECK: ![[kernel32]] = !{!"/DEFAULTLIB:kernel32.lib"}
+// CHECK: ![[USER32]] = !{!"/DEFAULTLIB:USER32.LIB"}
+// CHECK: ![[space]] = !{!"/DEFAULTLIB:\22with space.lib\22"}
+// CHECK: ![[bar]] = !{!" /bar=2"}
+// CHECK: ![[foo]] = !{!" /foo=\22foo bar\22"}
 
-// LINUX: metadata !{metadata !"-lmsvcrt.lib"}
-// LINUX: metadata !{metadata !"-lkernel32"}
-// LINUX: metadata !{metadata !"-lUSER32.LIB"}
-// LINUX: metadata !{metadata !" /bar=2"}
+// LINUX: !{!"-lmsvcrt.lib"}
+// LINUX: !{!"-lkernel32"}
+// LINUX: !{!"-lUSER32.LIB"}
+// LINUX: !{!" /bar=2"}
+
+// PS4: !{!"\01msvcrt.lib"}
+// PS4: !{!"\01kernel32"}
+// PS4: !{!"\01USER32.LIB"}
+// PS4: !{!" /bar=2"}
diff --git a/test/CodeGen/pragma-detect_mismatch.c b/test/CodeGen/pragma-detect_mismatch.c
index f15b75d..c5f3af3 100644
--- a/test/CodeGen/pragma-detect_mismatch.c
+++ b/test/CodeGen/pragma-detect_mismatch.c
@@ -6,7 +6,7 @@
 #pragma detect_mismatch("test2", BAR)
 
 // CHECK: !llvm.module.flags = !{{{.*}}}
-// CHECK: !{{[0-9]+}} = metadata !{i32 6, metadata !"Linker Options", metadata ![[link_opts:[0-9]+]]}
-// CHECK: ![[link_opts]] = metadata !{metadata ![[test:[0-9]+]], metadata ![[test2:[0-9]+]]}
-// CHECK: ![[test]] = metadata !{metadata !"/FAILIFMISMATCH:\22test=1\22"}
-// CHECK: ![[test2]] = metadata !{metadata !"/FAILIFMISMATCH:\22test2=2\22"}
+// CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[link_opts:[0-9]+]]}
+// CHECK: ![[link_opts]] = !{![[test:[0-9]+]], ![[test2:[0-9]+]]}
+// CHECK: ![[test]] = !{!"/FAILIFMISMATCH:\22test=1\22"}
+// CHECK: ![[test2]] = !{!"/FAILIFMISMATCH:\22test2=2\22"}
diff --git a/test/CodeGen/pragma-loop.cpp b/test/CodeGen/pragma-loop.cpp
index 9a9665e..dd40c1d 100644
--- a/test/CodeGen/pragma-loop.cpp
+++ b/test/CodeGen/pragma-loop.cpp
@@ -157,35 +157,35 @@
   for_template_constant_expression_test<double, 2, 4, 8>(List, Length);
 }
 
-// CHECK: ![[LOOP_1]] = metadata !{metadata ![[LOOP_1]], metadata ![[UNROLL_FULL:.*]], metadata ![[WIDTH_4:.*]], metadata ![[INTERLEAVE_4:.*]], metadata ![[INTENABLE_1:.*]]}
-// CHECK: ![[UNROLL_FULL]] = metadata !{metadata !"llvm.loop.unroll.full"}
-// CHECK: ![[WIDTH_4]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 4}
-// CHECK: ![[INTERLEAVE_4]] = metadata !{metadata !"llvm.loop.interleave.count", i32 4}
-// CHECK: ![[INTENABLE_1]] = metadata !{metadata !"llvm.loop.vectorize.enable", i1 true}
-// CHECK: ![[LOOP_2]] = metadata !{metadata ![[LOOP_2:.*]], metadata ![[UNROLL_DISABLE:.*]], metadata ![[INTERLEAVE_4:.*]], metadata ![[WIDTH_8:.*]]}
-// CHECK: ![[UNROLL_DISABLE]] = metadata !{metadata !"llvm.loop.unroll.disable"}
-// CHECK: ![[WIDTH_8]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 8}
-// CHECK: ![[LOOP_3]] = metadata !{metadata ![[LOOP_3]], metadata ![[UNROLL_8:.*]], metadata ![[INTERLEAVE_4:.*]], metadata ![[ENABLE_1:.*]]}
-// CHECK: ![[UNROLL_8]] = metadata !{metadata !"llvm.loop.unroll.count", i32 8}
-// CHECK: ![[LOOP_4]] = metadata !{metadata ![[LOOP_4]], metadata ![[INTERLEAVE_2:.*]], metadata ![[WIDTH_2:.*]]}
-// CHECK: ![[INTERLEAVE_2]] = metadata !{metadata !"llvm.loop.interleave.count", i32 2}
-// CHECK: ![[WIDTH_2]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 2}
-// CHECK: ![[LOOP_5]] = metadata !{metadata ![[LOOP_5]], metadata ![[UNROLL_DISABLE:.*]], metadata ![[WIDTH_1:.*]]}
-// CHECK: ![[WIDTH_1]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 1}
-// CHECK: ![[LOOP_6]] = metadata !{metadata ![[LOOP_6]], metadata ![[UNROLL_8:.*]], metadata ![[INTERLEAVE_2:.*]], metadata ![[WIDTH_2:.*]]}
-// CHECK: ![[LOOP_7]] = metadata !{metadata ![[LOOP_7]], metadata ![[WIDTH_5:.*]]}
-// CHECK: ![[WIDTH_5]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 5}
-// CHECK: ![[LOOP_8]] = metadata !{metadata ![[LOOP_8]], metadata ![[WIDTH_5:.*]]}
-// CHECK: ![[LOOP_9]] = metadata !{metadata ![[LOOP_9]], metadata ![[UNROLL_8:.*]], metadata ![[INTERLEAVE_8:.*]], metadata ![[WIDTH_8:.*]]}
-// CHECK: ![[INTERLEAVE_8]] = metadata !{metadata !"llvm.loop.interleave.count", i32 8}
-// CHECK: ![[LOOP_10]] = metadata !{metadata ![[LOOP_10]], metadata ![[UNROLL_8:.*]], metadata ![[INTERLEAVE_2:.*]], metadata ![[WIDTH_2:.*]]}
-// CHECK: ![[LOOP_11]] = metadata !{metadata ![[LOOP_11]], metadata ![[UNROLL_8:.*]], metadata ![[INTERLEAVE_4:.*]], metadata ![[WIDTH_2:.*]]}
-// CHECK: ![[LOOP_12]] = metadata !{metadata ![[LOOP_12]], metadata ![[UNROLL_24:.*]], metadata ![[INTERLEAVE_10:.*]], metadata ![[WIDTH_6:.*]]}
-// CHECK: ![[UNROLL_24]] = metadata !{metadata !"llvm.loop.unroll.count", i32 24}
-// CHECK: ![[INTERLEAVE_10]] = metadata !{metadata !"llvm.loop.interleave.count", i32 10}
-// CHECK: ![[WIDTH_6]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 6}
-// CHECK: ![[LOOP_13]] = metadata !{metadata ![[LOOP_13]], metadata ![[UNROLL_32:.*]], metadata ![[INTERLEAVE_16:.*]], metadata ![[WIDTH_8:.*]]}
-// CHECK: ![[UNROLL_32]] = metadata !{metadata !"llvm.loop.unroll.count", i32 32}
-// CHECK: ![[INTERLEAVE_16]] = metadata !{metadata !"llvm.loop.interleave.count", i32 16}
-// CHECK: ![[LOOP_14]] = metadata !{metadata ![[LOOP_14]], metadata ![[WIDTH_10:.*]]}
-// CHECK: ![[WIDTH_10]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 10}
+// CHECK: ![[LOOP_1]] = distinct !{![[LOOP_1]], ![[UNROLL_FULL:.*]], ![[WIDTH_4:.*]], ![[INTERLEAVE_4:.*]], ![[INTENABLE_1:.*]]}
+// CHECK: ![[UNROLL_FULL]] = !{!"llvm.loop.unroll.full"}
+// CHECK: ![[WIDTH_4]] = !{!"llvm.loop.vectorize.width", i32 4}
+// CHECK: ![[INTERLEAVE_4]] = !{!"llvm.loop.interleave.count", i32 4}
+// CHECK: ![[INTENABLE_1]] = !{!"llvm.loop.vectorize.enable", i1 true}
+// CHECK: ![[LOOP_2]] = distinct !{![[LOOP_2:.*]], ![[UNROLL_DISABLE:.*]], ![[INTERLEAVE_4:.*]], ![[WIDTH_8:.*]]}
+// CHECK: ![[UNROLL_DISABLE]] = !{!"llvm.loop.unroll.disable"}
+// CHECK: ![[WIDTH_8]] = !{!"llvm.loop.vectorize.width", i32 8}
+// CHECK: ![[LOOP_3]] = distinct !{![[LOOP_3]], ![[UNROLL_8:.*]], ![[INTERLEAVE_4:.*]], ![[ENABLE_1:.*]]}
+// CHECK: ![[UNROLL_8]] = !{!"llvm.loop.unroll.count", i32 8}
+// CHECK: ![[LOOP_4]] = distinct !{![[LOOP_4]], ![[INTERLEAVE_2:.*]], ![[WIDTH_2:.*]]}
+// CHECK: ![[INTERLEAVE_2]] = !{!"llvm.loop.interleave.count", i32 2}
+// CHECK: ![[WIDTH_2]] = !{!"llvm.loop.vectorize.width", i32 2}
+// CHECK: ![[LOOP_5]] = distinct !{![[LOOP_5]], ![[UNROLL_DISABLE:.*]], ![[WIDTH_1:.*]]}
+// CHECK: ![[WIDTH_1]] = !{!"llvm.loop.vectorize.width", i32 1}
+// CHECK: ![[LOOP_6]] = distinct !{![[LOOP_6]], ![[UNROLL_8:.*]], ![[INTERLEAVE_2:.*]], ![[WIDTH_2:.*]]}
+// CHECK: ![[LOOP_7]] = distinct !{![[LOOP_7]], ![[WIDTH_5:.*]]}
+// CHECK: ![[WIDTH_5]] = !{!"llvm.loop.vectorize.width", i32 5}
+// CHECK: ![[LOOP_8]] = distinct !{![[LOOP_8]], ![[WIDTH_5:.*]]}
+// CHECK: ![[LOOP_9]] = distinct !{![[LOOP_9]], ![[UNROLL_8:.*]], ![[INTERLEAVE_8:.*]], ![[WIDTH_8:.*]]}
+// CHECK: ![[INTERLEAVE_8]] = !{!"llvm.loop.interleave.count", i32 8}
+// CHECK: ![[LOOP_10]] = distinct !{![[LOOP_10]], ![[UNROLL_8:.*]], ![[INTERLEAVE_2:.*]], ![[WIDTH_2:.*]]}
+// CHECK: ![[LOOP_11]] = distinct !{![[LOOP_11]], ![[UNROLL_8:.*]], ![[INTERLEAVE_4:.*]], ![[WIDTH_2:.*]]}
+// CHECK: ![[LOOP_12]] = distinct !{![[LOOP_12]], ![[UNROLL_24:.*]], ![[INTERLEAVE_10:.*]], ![[WIDTH_6:.*]]}
+// CHECK: ![[UNROLL_24]] = !{!"llvm.loop.unroll.count", i32 24}
+// CHECK: ![[INTERLEAVE_10]] = !{!"llvm.loop.interleave.count", i32 10}
+// CHECK: ![[WIDTH_6]] = !{!"llvm.loop.vectorize.width", i32 6}
+// CHECK: ![[LOOP_13]] = distinct !{![[LOOP_13]], ![[UNROLL_32:.*]], ![[INTERLEAVE_16:.*]], ![[WIDTH_8:.*]]}
+// CHECK: ![[UNROLL_32]] = !{!"llvm.loop.unroll.count", i32 32}
+// CHECK: ![[INTERLEAVE_16]] = !{!"llvm.loop.interleave.count", i32 16}
+// CHECK: ![[LOOP_14]] = distinct !{![[LOOP_14]], ![[WIDTH_10:.*]]}
+// CHECK: ![[WIDTH_10]] = !{!"llvm.loop.vectorize.width", i32 10}
diff --git a/test/CodeGen/pragma-unroll.cpp b/test/CodeGen/pragma-unroll.cpp
index 05d1733..8b73fa6 100644
--- a/test/CodeGen/pragma-unroll.cpp
+++ b/test/CodeGen/pragma-unroll.cpp
@@ -86,14 +86,14 @@
   for_template_define_test<double>(List, Length, Value);
 }
 
-// CHECK: ![[LOOP_1]] = metadata !{metadata ![[LOOP_1]], metadata ![[UNROLL_FULL:.*]]}
-// CHECK: ![[UNROLL_FULL]] = metadata !{metadata !"llvm.loop.unroll.full"}
-// CHECK: ![[LOOP_2]] = metadata !{metadata ![[LOOP_2:.*]], metadata ![[UNROLL_DISABLE:.*]]}
-// CHECK: ![[UNROLL_DISABLE]] = metadata !{metadata !"llvm.loop.unroll.disable"}
-// CHECK: ![[LOOP_3]] = metadata !{metadata ![[LOOP_3]], metadata ![[UNROLL_8:.*]]}
-// CHECK: ![[UNROLL_8]] = metadata !{metadata !"llvm.loop.unroll.count", i32 8}
-// CHECK: ![[LOOP_4]] = metadata !{metadata ![[LOOP_4]], metadata ![[UNROLL_4:.*]]}
-// CHECK: ![[UNROLL_4]] = metadata !{metadata !"llvm.loop.unroll.count", i32 4}
-// CHECK: ![[LOOP_5]] = metadata !{metadata ![[LOOP_5]], metadata ![[UNROLL_8:.*]]}
-// CHECK: ![[LOOP_6]] = metadata !{metadata ![[LOOP_6]], metadata ![[UNROLL_8:.*]]}
-// CHECK: ![[LOOP_7]] = metadata !{metadata ![[LOOP_7]], metadata ![[UNROLL_8:.*]]}
+// CHECK: ![[LOOP_1]] = distinct !{![[LOOP_1]], ![[UNROLL_FULL:.*]]}
+// CHECK: ![[UNROLL_FULL]] = !{!"llvm.loop.unroll.full"}
+// CHECK: ![[LOOP_2]] = distinct !{![[LOOP_2:.*]], ![[UNROLL_DISABLE:.*]]}
+// CHECK: ![[UNROLL_DISABLE]] = !{!"llvm.loop.unroll.disable"}
+// CHECK: ![[LOOP_3]] = distinct !{![[LOOP_3]], ![[UNROLL_8:.*]]}
+// CHECK: ![[UNROLL_8]] = !{!"llvm.loop.unroll.count", i32 8}
+// CHECK: ![[LOOP_4]] = distinct !{![[LOOP_4]], ![[UNROLL_4:.*]]}
+// CHECK: ![[UNROLL_4]] = !{!"llvm.loop.unroll.count", i32 4}
+// CHECK: ![[LOOP_5]] = distinct !{![[LOOP_5]], ![[UNROLL_8:.*]]}
+// CHECK: ![[LOOP_6]] = distinct !{![[LOOP_6]], ![[UNROLL_8:.*]]}
+// CHECK: ![[LOOP_7]] = distinct !{![[LOOP_7]], ![[UNROLL_8:.*]]}
diff --git a/test/CodeGen/private-extern.c b/test/CodeGen/private-extern.c
index 2d34d54..26b3fce 100644
--- a/test/CodeGen/private-extern.c
+++ b/test/CodeGen/private-extern.c
@@ -1,6 +1,7 @@
-// RUN: %clang_cc1 -emit-llvm -o %t %s
-// RUN: grep '@g0 = external hidden constant i32' %t
-// RUN: grep '@g1 = hidden constant i32 1' %t
+// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
+
+// CHECK-DAG: @g0 = external hidden constant i32
+// CHECK-DAG: @g1 = hidden constant i32 1
 
 __private_extern__ const int g0;
 __private_extern__ const int g1 = 1;
diff --git a/test/CodeGen/sanitize-address-field-padding.cpp b/test/CodeGen/sanitize-address-field-padding.cpp
index 0683089..d4eea1b 100644
--- a/test/CodeGen/sanitize-address-field-padding.cpp
+++ b/test/CodeGen/sanitize-address-field-padding.cpp
@@ -229,6 +229,7 @@
 
 void MakeTrivialCopy(ClassWithTrivialCopy *s1, ClassWithTrivialCopy *s2) {
   *s1 = *s2;
+  ClassWithTrivialCopy s3(*s2);
 }
 
 // CHECK-LABEL: define void @_Z15MakeTrivialCopyP20ClassWithTrivialCopyS0_
diff --git a/test/CodeGen/sanitize-init-order.cpp b/test/CodeGen/sanitize-init-order.cpp
index 6fd215d..ee53f7b 100644
--- a/test/CodeGen/sanitize-init-order.cpp
+++ b/test/CodeGen/sanitize-init-order.cpp
@@ -38,13 +38,13 @@
 // Check that ASan init-order checking ignores structs with trivial default
 // constructor.
 // CHECK: !llvm.asan.globals = !{![[GLOB_1:[0-9]+]], ![[GLOB_2:[0-9]+]], ![[GLOB_3:[0-9]]], ![[GLOB_4:[0-9]]]}
-// CHECK: ![[GLOB_1]] = metadata !{%struct.PODStruct* {{.*}}, i1 false, i1 false}
-// CHECK: ![[GLOB_2]] = metadata !{%struct.PODWithDtor* {{.*}}, i1 false, i1 false}
-// CHECK: ![[GLOB_3]] = metadata !{%struct.PODWithCtorAndDtor* {{.*}}, i1 true, i1 false}
-// CHECK: ![[GLOB_4]] = metadata !{{{.*}}class.NS::PODWithCtor{{.*}}, i1 true, i1 false}
+// CHECK: ![[GLOB_1]] = !{%struct.PODStruct* {{.*}}, i1 false, i1 false}
+// CHECK: ![[GLOB_2]] = !{%struct.PODWithDtor* {{.*}}, i1 false, i1 false}
+// CHECK: ![[GLOB_3]] = !{%struct.PODWithCtorAndDtor* {{.*}}, i1 true, i1 false}
+// CHECK: ![[GLOB_4]] = !{{{.*}}class.NS::PODWithCtor{{.*}}, i1 true, i1 false}
 
 // BLACKLIST: !llvm.asan.globals = !{![[GLOB_1:[0-9]+]], ![[GLOB_2:[0-9]+]], ![[GLOB_3:[0-9]]], ![[GLOB_4:[0-9]]]}
-// BLACKLIST: ![[GLOB_1]] = metadata !{%struct.PODStruct* {{.*}}, i1 false, i1 false}
-// BLACKLIST: ![[GLOB_2]] = metadata !{%struct.PODWithDtor* {{.*}}, i1 false, i1 false}
-// BLACKLIST: ![[GLOB_3]] = metadata !{%struct.PODWithCtorAndDtor* {{.*}}, i1 false, i1 false}
-// BLACKLIST: ![[GLOB_4]] = metadata !{{{.*}}class.NS::PODWithCtor{{.*}}, i1 false, i1 false}
+// BLACKLIST: ![[GLOB_1]] = !{%struct.PODStruct* {{.*}}, i1 false, i1 false}
+// BLACKLIST: ![[GLOB_2]] = !{%struct.PODWithDtor* {{.*}}, i1 false, i1 false}
+// BLACKLIST: ![[GLOB_3]] = !{%struct.PODWithCtorAndDtor* {{.*}}, i1 false, i1 false}
+// BLACKLIST: ![[GLOB_4]] = !{{{.*}}class.NS::PODWithCtor{{.*}}, i1 false, i1 false}
diff --git a/test/CodeGen/sanitize-recover.c b/test/CodeGen/sanitize-recover.c
index 3c9c895..b263f51 100644
--- a/test/CodeGen/sanitize-recover.c
+++ b/test/CodeGen/sanitize-recover.c
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsanitize=unsigned-integer-overflow %s -emit-llvm -o - | FileCheck %s --check-prefix=RECOVER
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsanitize=unsigned-integer-overflow -fno-sanitize-recover %s -emit-llvm -o - | FileCheck %s --check-prefix=ABORT
-
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsanitize=unsigned-integer-overflow -fsanitize-recover=unsigned-integer-overflow %s -emit-llvm -o - | FileCheck %s --check-prefix=RECOVER
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsanitize=unsigned-integer-overflow %s -emit-llvm -o - | FileCheck %s --check-prefix=ABORT
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsanitize=null,object-size,alignment -fsanitize-recover=object-size %s -emit-llvm -o - | FileCheck %s --check-prefix=PARTIAL
 
 // RECOVER: @test
 // ABORT: @test
@@ -15,3 +15,25 @@
   // ABORT: unreachable
   x = y + z;
 }
+
+void foo() {
+  union { int i; } u;
+  u.i=1;
+  // PARTIAL:      %[[CHECK0:.*]] = icmp ne {{.*}}* %[[PTR:.*]], null
+
+  // PARTIAL:      %[[SIZE:.*]] = call i64 @llvm.objectsize.i64.p0i8(i8* {{.*}}, i1 false)
+  // PARTIAL-NEXT: %[[CHECK1:.*]] = icmp uge i64 %[[SIZE]], 4
+
+  // PARTIAL:      %[[MISALIGN:.*]] = and i64 {{.*}}, 3
+  // PARTIAL-NEXT: %[[CHECK2:.*]] = icmp eq i64 %[[MISALIGN]], 0
+
+  // PARTIAL:      %[[CHECK02:.*]] = and i1 %[[CHECK0]], %[[CHECK2]]
+  // PARTIAL-NEXT: %[[CHECK012:.*]] = and i1 %[[CHECK02]], %[[CHECK1]]
+
+  // PARTIAL:      br i1 %[[CHECK012]], {{.*}} !prof ![[WEIGHT_MD:.*]], !nosanitize
+
+  // PARTIAL:      br i1 %[[CHECK02]], {{.*}}
+  // PARTIAL:      call void @__ubsan_handle_type_mismatch_abort(
+  // PARTIAL-NEXT: unreachable
+  // PARTIAL:      call void @__ubsan_handle_type_mismatch(
+}
diff --git a/test/CodeGen/sha-builtins.c b/test/CodeGen/sha-builtins.c
index 181dba1..2b11ded 100644
--- a/test/CodeGen/sha-builtins.c
+++ b/test/CodeGen/sha-builtins.c
@@ -7,7 +7,7 @@
 
 __m128i test_sha1rnds4(__m128i a, __m128i b) {
   // CHECK: call <4 x i32> @llvm.x86.sha1rnds4
-  return _mm_sha1rnds4_epu32(a, b, 8);
+  return _mm_sha1rnds4_epu32(a, b, 3);
 }
 __m128i test_sha1nexte(__m128i a, __m128i b) {
   // CHECK: call <4 x i32> @llvm.x86.sha1nexte
diff --git a/test/CodeGen/sse-builtins.c b/test/CodeGen/sse-builtins.c
index 238454b..3feca74 100644
--- a/test/CodeGen/sse-builtins.c
+++ b/test/CodeGen/sse-builtins.c
@@ -255,3 +255,325 @@
   // CHECK: shufflevector <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i32> <i32 0, i32 9, i32 2, i32 11, i32 4, i32 13, i32 6, i32 7>
   return _mm_blend_epi16(V1, V2, 42);
 }
+
+__m128 test_mm_cmpeq_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 0)
+  return _mm_cmpeq_ss(__a, __b);
+}
+
+__m128 test_mm_cmplt_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmplt_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 1)
+  return _mm_cmplt_ss(__a, __b);
+}
+
+__m128 test_mm_cmple_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmple_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 2)
+  return _mm_cmple_ss(__a, __b);
+}
+
+__m128 test_mm_cmpunord_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpunord_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 3)
+  return _mm_cmpunord_ss(__a, __b);
+}
+
+__m128 test_mm_cmpneq_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 4)
+  return _mm_cmpneq_ss(__a, __b);
+}
+
+__m128 test_mm_cmpnlt_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpnlt_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 5)
+  return _mm_cmpnlt_ss(__a, __b);
+}
+
+__m128 test_mm_cmpnle_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpnle_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 6)
+  return _mm_cmpnle_ss(__a, __b);
+}
+
+__m128 test_mm_cmpord_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpord_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 7)
+  return _mm_cmpord_ss(__a, __b);
+}
+
+__m128 test_mm_cmpgt_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 1)
+  return _mm_cmpgt_ss(__a, __b);
+}
+
+__m128 test_mm_cmpge_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpge_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 2)
+  return _mm_cmpge_ss(__a, __b);
+}
+
+__m128 test_mm_cmpngt_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpngt_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 5)
+  return _mm_cmpngt_ss(__a, __b);
+}
+
+__m128 test_mm_cmpnge_ss(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpnge_ss
+  // CHECK: @llvm.x86.sse.cmp.ss(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 6)
+  return _mm_cmpnge_ss(__a, __b);
+}
+
+__m128 test_mm_cmpeq_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 0)
+  return _mm_cmpeq_ps(__a, __b);
+}
+
+__m128 test_mm_cmplt_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmplt_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 1)
+  return _mm_cmplt_ps(__a, __b);
+}
+
+__m128 test_mm_cmple_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmple_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 2)
+  return _mm_cmple_ps(__a, __b);
+}
+
+__m128 test_mm_cmpunord_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpunord_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 3)
+  return _mm_cmpunord_ps(__a, __b);
+}
+
+__m128 test_mm_cmpneq_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 4)
+  return _mm_cmpneq_ps(__a, __b);
+}
+
+__m128 test_mm_cmpnlt_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpnlt_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 5)
+  return _mm_cmpnlt_ps(__a, __b);
+}
+
+__m128 test_mm_cmpnle_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpnle_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 6)
+  return _mm_cmpnle_ps(__a, __b);
+}
+
+__m128 test_mm_cmpord_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpord_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 7)
+  return _mm_cmpord_ps(__a, __b);
+}
+
+__m128 test_mm_cmpgt_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 1)
+  return _mm_cmpgt_ps(__a, __b);
+}
+
+__m128 test_mm_cmpge_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpge_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 2)
+  return _mm_cmpge_ps(__a, __b);
+}
+
+__m128 test_mm_cmpngt_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpngt_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 5)
+  return _mm_cmpngt_ps(__a, __b);
+}
+
+__m128 test_mm_cmpnge_ps(__m128 __a, __m128 __b) {
+  // CHECK-LABEL: @test_mm_cmpnge_ps
+  // CHECK: @llvm.x86.sse.cmp.ps(<4 x float> %{{.*}}, <4 x float> %{{.*}}, i8 6)
+  return _mm_cmpnge_ps(__a, __b);
+}
+
+__m128d test_mm_cmpeq_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 0)
+  return _mm_cmpeq_sd(__a, __b);
+}
+
+__m128d test_mm_cmplt_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmplt_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 1)
+  return _mm_cmplt_sd(__a, __b);
+}
+
+__m128d test_mm_cmple_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmple_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 2)
+  return _mm_cmple_sd(__a, __b);
+}
+
+__m128d test_mm_cmpunord_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpunord_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 3)
+  return _mm_cmpunord_sd(__a, __b);
+}
+
+__m128d test_mm_cmpneq_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 4)
+  return _mm_cmpneq_sd(__a, __b);
+}
+
+__m128d test_mm_cmpnlt_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpnlt_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 5)
+  return _mm_cmpnlt_sd(__a, __b);
+}
+
+__m128d test_mm_cmpnle_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpnle_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 6)
+  return _mm_cmpnle_sd(__a, __b);
+}
+
+__m128d test_mm_cmpord_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpord_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 7)
+  return _mm_cmpord_sd(__a, __b);
+}
+
+__m128d test_mm_cmpgt_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 1)
+  return _mm_cmpgt_sd(__a, __b);
+}
+
+__m128d test_mm_cmpge_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpge_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 2)
+  return _mm_cmpge_sd(__a, __b);
+}
+
+__m128d test_mm_cmpngt_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpngt_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 5)
+  return _mm_cmpngt_sd(__a, __b);
+}
+
+__m128d test_mm_cmpnge_sd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpnge_sd
+  // CHECK: @llvm.x86.sse2.cmp.sd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 6)
+  return _mm_cmpnge_sd(__a, __b);
+}
+
+__m128d test_mm_cmpeq_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpeq_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 0)
+  return _mm_cmpeq_pd(__a, __b);
+}
+
+__m128d test_mm_cmplt_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmplt_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 1)
+  return _mm_cmplt_pd(__a, __b);
+}
+
+__m128d test_mm_cmple_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmple_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 2)
+  return _mm_cmple_pd(__a, __b);
+}
+
+__m128d test_mm_cmpunord_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpunord_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 3)
+  return _mm_cmpunord_pd(__a, __b);
+}
+
+__m128d test_mm_cmpneq_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpneq_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 4)
+  return _mm_cmpneq_pd(__a, __b);
+}
+
+__m128d test_mm_cmpnlt_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpnlt_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 5)
+  return _mm_cmpnlt_pd(__a, __b);
+}
+
+__m128d test_mm_cmpnle_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpnle_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 6)
+  return _mm_cmpnle_pd(__a, __b);
+}
+
+__m128d test_mm_cmpord_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpord_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 7)
+  return _mm_cmpord_pd(__a, __b);
+}
+
+__m128d test_mm_cmpgt_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpgt_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 1)
+  return _mm_cmpgt_pd(__a, __b);
+}
+
+__m128d test_mm_cmpge_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpge_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 2)
+  return _mm_cmpge_pd(__a, __b);
+}
+
+__m128d test_mm_cmpngt_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpngt_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 5)
+  return _mm_cmpngt_pd(__a, __b);
+}
+
+__m128d test_mm_cmpnge_pd(__m128d __a, __m128d __b) {
+  // CHECK-LABEL: @test_mm_cmpnge_pd
+  // CHECK: @llvm.x86.sse2.cmp.pd(<2 x double> %{{.*}}, <2 x double> %{{.*}}, i8 6)
+  return _mm_cmpnge_pd(__a, __b);
+}
+
+__m128 test_mm_slli_si128(__m128 a) {
+  // CHECK-LABEL: @test_mm_slli_si128
+  // CHECK: shufflevector <16 x i8> {{.*}}, <16 x i8> {{.*}}, <16 x i32> <i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26>
+  return _mm_slli_si128(a, 5);
+}
+
+__m128 test_mm_bslli_si128(__m128 a) {
+  // CHECK-LABEL: @test_mm_bslli_si128
+  // CHECK: shufflevector <16 x i8> {{.*}}, <16 x i8> {{.*}}, <16 x i32> <i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26>
+  return _mm_bslli_si128(a, 5);
+}
+
+__m128 test_mm_srli_si128(__m128 a) {
+  // CHECK-LABEL: @test_mm_srli_si128
+  // CHECK: shufflevector <16 x i8> {{.*}}, <16 x i8> {{.*}}, <16 x i32> <i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20>
+  return _mm_srli_si128(a, 5);
+}
+
+__m128 test_mm_bsrli_si128(__m128 a) {
+  // CHECK-LABEL: @test_mm_bsrli_si128
+  // CHECK: shufflevector <16 x i8> {{.*}}, <16 x i8> {{.*}}, <16 x i32> <i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20>
+  return _mm_bsrli_si128(a, 5);
+}
+
+__m128i test_mm_alignr_epi8(__m128i a, __m128i b) {
+  // CHECK: shufflevector <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i32> <i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17>
+  return _mm_alignr_epi8(a, b, 2);
+}
+
+__m128i test2_mm_alignr_epi8(__m128i a, __m128i b) {
+  // CHECK: shufflevector <16 x i8> %{{.*}}, <16 x i8> zeroinitializer, <16 x i32> <i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16>
+  return _mm_alignr_epi8(a, b, 17);
+}
diff --git a/test/CodeGen/sse.c b/test/CodeGen/sse.c
new file mode 100644
index 0000000..17cce69
--- /dev/null
+++ b/test/CodeGen/sse.c
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -O3 -ffreestanding -triple x86_64-apple-macosx10.8.0 -target-feature +sse4.1 -emit-llvm %s -o - | FileCheck %s
+
+#include <emmintrin.h>
+
+// Byte-shifts look reversed due to xmm register layout
+__m128 test_mm_slli_si128(__m128 a) {
+  // CHECK-LABEL: @test_mm_slli_si128
+  // CHECK: shufflevector <16 x i8> <{{.*}}, i8 0, i8 0, i8 0, i8 0, i8 0>, <16 x i8> {{.*}}, <16 x i32> <i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26>
+  return _mm_slli_si128(a, 5);
+}
+
+__m128 test_mm_slli_si128_0(__m128 a) {
+  // CHECK-LABEL: @test_mm_slli_si128_0
+  // CHECK-NOT: shufflevector
+  return _mm_slli_si128(a, 0);
+}
+
+__m128 test_mm_slli_si128_16(__m128 a) {
+  // CHECK-LABEL: @test_mm_slli_si128_16
+  // CHECK-NOT: shufflevector
+  return _mm_slli_si128(a, 16);
+}
+
+__m128 test_mm_srli_si128(__m128 a) {
+  // CHECK-LABEL: @test_mm_srli_si128
+  // CHECK: shufflevector <16 x i8> {{.*}}, <16 x i8> <i8 0, i8 0, i8 0, i8 0, i8 0, {{.*}}>, <16 x i32> <i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20>
+  return _mm_srli_si128(a, 5);
+}
+
+__m128 test_mm_srli_si128_0(__m128 a) {
+  // CHECK-LABEL: @test_mm_srli_si128_0
+  // CHECK-NOT: shufflevector
+  return _mm_srli_si128(a, 0);
+}
+
+__m128 test_mm_srli_si128_16(__m128 a) {
+  // CHECK-LABEL: @test_mm_srli_si128_16
+  // CHECK-NOT: shufflevector
+  return _mm_srli_si128(a, 16);
+}
diff --git a/test/CodeGen/target-data.c b/test/CodeGen/target-data.c
index a727a7f..2f1c971 100644
--- a/test/CodeGen/target-data.c
+++ b/test/CodeGen/target-data.c
@@ -118,10 +118,15 @@
 // RUN: | FileCheck %s -check-prefix=R600D
 // R600D: target datalayout = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"
 
-// RUN: %clang_cc1 -triple r600-unknown -target-cpu hawaii -o - -emit-llvm %s \
+// RUN: %clang_cc1 -triple amdgcn-unknown -target-cpu hawaii -o - -emit-llvm %s \
 // RUN: | FileCheck %s -check-prefix=R600SI
 // R600SI: target datalayout = "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32-p24:64:64-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"
 
+// Test default -target-cpu
+// RUN: %clang_cc1 -triple amdgcn-unknown -o - -emit-llvm %s \
+// RUN: | FileCheck %s -check-prefix=R600SIDefault
+// R600SIDefault: target datalayout = "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32-p24:64:64-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"
+
 // RUN: %clang_cc1 -triple arm64-unknown -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=AARCH64
 // AARCH64: target datalayout = "e-m:e-i64:64-i128:128-n32:64-S128"
diff --git a/test/CodeGen/tbaa-class.cpp b/test/CodeGen/tbaa-class.cpp
index bdd155d..a8005d6 100644
--- a/test/CodeGen/tbaa-class.cpp
+++ b/test/CodeGen/tbaa-class.cpp
@@ -198,31 +198,31 @@
   return b1->a.f32;
 }
 
-// CHECK: [[TYPE_char:!.*]] = metadata !{metadata !"omnipotent char", metadata [[TAG_cxx_tbaa:!.*]],
-// CHECK: [[TAG_cxx_tbaa]] = metadata !{metadata !"Simple C/C++ TBAA"}
-// CHECK: [[TAG_i32]] = metadata !{metadata [[TYPE_i32:!.*]], metadata [[TYPE_i32]], i64 0}
-// CHECK: [[TYPE_i32]] = metadata !{metadata !"int", metadata [[TYPE_char]],
-// CHECK: [[TAG_i16]] = metadata !{metadata [[TYPE_i16:!.*]], metadata [[TYPE_i16]], i64 0}
-// CHECK: [[TYPE_i16]] = metadata !{metadata !"short", metadata [[TYPE_char]],
+// CHECK: [[TYPE_char:!.*]] = !{!"omnipotent char", [[TAG_cxx_tbaa:!.*]],
+// CHECK: [[TAG_cxx_tbaa]] = !{!"Simple C/C++ TBAA"}
+// CHECK: [[TAG_i32]] = !{[[TYPE_i32:!.*]], [[TYPE_i32]], i64 0}
+// CHECK: [[TYPE_i32]] = !{!"int", [[TYPE_char]],
+// CHECK: [[TAG_i16]] = !{[[TYPE_i16:!.*]], [[TYPE_i16]], i64 0}
+// CHECK: [[TYPE_i16]] = !{!"short", [[TYPE_char]],
 
-// PATH: [[TYPE_CHAR:!.*]] = metadata !{metadata !"omnipotent char", metadata
-// PATH: [[TAG_i32]] = metadata !{metadata [[TYPE_INT:!.*]], metadata [[TYPE_INT]], i64 0}
-// PATH: [[TYPE_INT]] = metadata !{metadata !"int", metadata [[TYPE_CHAR]]
-// PATH: [[TAG_A_f32]] = metadata !{metadata [[TYPE_A:!.*]], metadata [[TYPE_INT]], i64 4}
-// PATH: [[TYPE_A]] = metadata !{metadata !"_ZTS7StructA", metadata [[TYPE_SHORT:!.*]], i64 0, metadata [[TYPE_INT]], i64 4, metadata [[TYPE_SHORT]], i64 8, metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_SHORT:!.*]] = metadata !{metadata !"short", metadata [[TYPE_CHAR]]
-// PATH: [[TAG_A_f16]] = metadata !{metadata [[TYPE_A]], metadata [[TYPE_SHORT]], i64 0}
-// PATH: [[TAG_B_a_f32]] = metadata !{metadata [[TYPE_B:!.*]], metadata [[TYPE_INT]], i64 8}
-// PATH: [[TYPE_B]] = metadata !{metadata !"_ZTS7StructB", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_A]], i64 4, metadata [[TYPE_INT]], i64 20}
-// PATH: [[TAG_B_a_f16]] = metadata !{metadata [[TYPE_B]], metadata [[TYPE_SHORT]], i64 4}
-// PATH: [[TAG_B_f32]] = metadata !{metadata [[TYPE_B]], metadata [[TYPE_INT]], i64 20}
-// PATH: [[TAG_B_a_f32_2]] = metadata !{metadata [[TYPE_B]], metadata [[TYPE_INT]], i64 16}
-// PATH: [[TAG_S_f32]] = metadata !{metadata [[TYPE_S:!.*]], metadata [[TYPE_INT]], i64 4}
-// PATH: [[TYPE_S]] = metadata !{metadata !"_ZTS7StructS", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_INT]], i64 4}
-// PATH: [[TAG_S_f16]] = metadata !{metadata [[TYPE_S]], metadata [[TYPE_SHORT]], i64 0}
-// PATH: [[TAG_S2_f32_2]] = metadata !{metadata [[TYPE_S2:!.*]], metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_S2]] = metadata !{metadata !"_ZTS8StructS2", metadata [[TYPE_SHORT]], i64 8, metadata [[TYPE_INT]], i64 12}
-// PATH: [[TAG_C_b_a_f32]] = metadata !{metadata [[TYPE_C:!.*]], metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_C]] = metadata !{metadata !"_ZTS7StructC", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_B]], i64 4, metadata [[TYPE_INT]], i64 28}
-// PATH: [[TAG_D_b_a_f32]] = metadata !{metadata [[TYPE_D:!.*]], metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_D]] = metadata !{metadata !"_ZTS7StructD", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_B]], i64 4, metadata [[TYPE_INT]], i64 28, metadata [[TYPE_CHAR]], i64 32}
+// PATH: [[TYPE_CHAR:!.*]] = !{!"omnipotent char", !
+// PATH: [[TAG_i32]] = !{[[TYPE_INT:!.*]], [[TYPE_INT]], i64 0}
+// PATH: [[TYPE_INT]] = !{!"int", [[TYPE_CHAR]]
+// PATH: [[TAG_A_f32]] = !{[[TYPE_A:!.*]], [[TYPE_INT]], i64 4}
+// PATH: [[TYPE_A]] = !{!"_ZTS7StructA", [[TYPE_SHORT:!.*]], i64 0, [[TYPE_INT]], i64 4, [[TYPE_SHORT]], i64 8, [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_SHORT:!.*]] = !{!"short", [[TYPE_CHAR]]
+// PATH: [[TAG_A_f16]] = !{[[TYPE_A]], [[TYPE_SHORT]], i64 0}
+// PATH: [[TAG_B_a_f32]] = !{[[TYPE_B:!.*]], [[TYPE_INT]], i64 8}
+// PATH: [[TYPE_B]] = !{!"_ZTS7StructB", [[TYPE_SHORT]], i64 0, [[TYPE_A]], i64 4, [[TYPE_INT]], i64 20}
+// PATH: [[TAG_B_a_f16]] = !{[[TYPE_B]], [[TYPE_SHORT]], i64 4}
+// PATH: [[TAG_B_f32]] = !{[[TYPE_B]], [[TYPE_INT]], i64 20}
+// PATH: [[TAG_B_a_f32_2]] = !{[[TYPE_B]], [[TYPE_INT]], i64 16}
+// PATH: [[TAG_S_f32]] = !{[[TYPE_S:!.*]], [[TYPE_INT]], i64 4}
+// PATH: [[TYPE_S]] = !{!"_ZTS7StructS", [[TYPE_SHORT]], i64 0, [[TYPE_INT]], i64 4}
+// PATH: [[TAG_S_f16]] = !{[[TYPE_S]], [[TYPE_SHORT]], i64 0}
+// PATH: [[TAG_S2_f32_2]] = !{[[TYPE_S2:!.*]], [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_S2]] = !{!"_ZTS8StructS2", [[TYPE_SHORT]], i64 8, [[TYPE_INT]], i64 12}
+// PATH: [[TAG_C_b_a_f32]] = !{[[TYPE_C:!.*]], [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_C]] = !{!"_ZTS7StructC", [[TYPE_SHORT]], i64 0, [[TYPE_B]], i64 4, [[TYPE_INT]], i64 28}
+// PATH: [[TAG_D_b_a_f32]] = !{[[TYPE_D:!.*]], [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_D]] = !{!"_ZTS7StructD", [[TYPE_SHORT]], i64 0, [[TYPE_B]], i64 4, [[TYPE_INT]], i64 28, [[TYPE_CHAR]], i64 32}
diff --git a/test/CodeGen/tbaa-for-vptr.cpp b/test/CodeGen/tbaa-for-vptr.cpp
index ded574e..35e95a5 100644
--- a/test/CodeGen/tbaa-for-vptr.cpp
+++ b/test/CodeGen/tbaa-for-vptr.cpp
@@ -30,6 +30,6 @@
 // CHECK-LABEL: @_ZN1AC2Ev
 // CHECK: store {{.*}} !tbaa ![[NUM]]
 //
-// CHECK: [[NUM]] = metadata !{metadata [[TYPE:!.*]], metadata [[TYPE]], i64 0}
-// CHECK: [[TYPE]] = metadata !{metadata !"vtable pointer", metadata !{{.*}}
-// NOTBAA-NOT: = metadata !{metadata !"Simple C/C++ TBAA"}
+// CHECK: [[NUM]] = !{[[TYPE:!.*]], [[TYPE]], i64 0}
+// CHECK: [[TYPE]] = !{!"vtable pointer", !{{.*}}
+// NOTBAA-NOT: = !{!"Simple C/C++ TBAA"}
diff --git a/test/CodeGen/tbaa-ms-abi.cpp b/test/CodeGen/tbaa-ms-abi.cpp
index 2a9e47e..878e1b6 100644
--- a/test/CodeGen/tbaa-ms-abi.cpp
+++ b/test/CodeGen/tbaa-ms-abi.cpp
@@ -16,7 +16,7 @@
 // CHECK: store i32 42, i32* {{.*}}, !tbaa [[TAG_A_i32:!.*]]
 }
 
-// CHECK: [[TYPE_INT:!.*]] = metadata !{metadata !"int", metadata [[TYPE_CHAR:!.*]], i64 0}
-// CHECK: [[TYPE_CHAR]] = metadata !{metadata !"omnipotent char", metadata
-// CHECK: [[TAG_A_i32]] = metadata !{metadata [[TYPE_A:!.*]], metadata [[TYPE_INT]], i64 0}
-// CHECK: [[TYPE_A]] = metadata !{metadata !"?AUStructA@@", metadata [[TYPE_INT]], i64 0}
+// CHECK: [[TYPE_INT:!.*]] = !{!"int", [[TYPE_CHAR:!.*]], i64 0}
+// CHECK: [[TYPE_CHAR]] = !{!"omnipotent char", !
+// CHECK: [[TAG_A_i32]] = !{[[TYPE_A:!.*]], [[TYPE_INT]], i64 0}
+// CHECK: [[TYPE_A]] = !{!"?AUStructA@@", [[TYPE_INT]], i64 0}
diff --git a/test/CodeGen/tbaa-struct.cpp b/test/CodeGen/tbaa-struct.cpp
index 71d3ed1..2623c42 100644
--- a/test/CodeGen/tbaa-struct.cpp
+++ b/test/CodeGen/tbaa-struct.cpp
@@ -62,14 +62,14 @@
 }
 // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 6, i32 1, i1 false), !tbaa.struct [[TS5:!.*]]
 
-// CHECK: [[TS]] = metadata !{i64 0, i64 2, metadata !{{.*}}, i64 4, i64 4, metadata !{{.*}}, i64 8, i64 1, metadata !{{.*}}, i64 12, i64 4, metadata !{{.*}}}
-// CHECK: [[CHAR:!.*]] = metadata !{metadata !"omnipotent char", metadata !{{.*}}}
-// CHECK: [[TAG_INT:!.*]] = metadata !{metadata [[INT:!.*]], metadata [[INT]], i64 0}
-// CHECK: [[INT]] = metadata !{metadata !"int", metadata [[CHAR]]
-// CHECK: [[TAG_CHAR:!.*]] = metadata !{metadata [[CHAR]], metadata [[CHAR]], i64 0}
+// CHECK: [[TS]] = !{i64 0, i64 2, !{{.*}}, i64 4, i64 4, !{{.*}}, i64 8, i64 1, !{{.*}}, i64 12, i64 4, !{{.*}}}
+// CHECK: [[CHAR:!.*]] = !{!"omnipotent char", !{{.*}}}
+// CHECK: [[TAG_INT:!.*]] = !{[[INT:!.*]], [[INT]], i64 0}
+// CHECK: [[INT]] = !{!"int", [[CHAR]]
+// CHECK: [[TAG_CHAR:!.*]] = !{[[CHAR]], [[CHAR]], i64 0}
 // (offset, size) = (0,1) char; (4,2) short; (8,4) int; (12,1) char; (16,4) int; (20,4) int
-// CHECK: [[TS2]] = metadata !{i64 0, i64 1, metadata !{{.*}}, i64 4, i64 2, metadata !{{.*}}, i64 8, i64 4, metadata !{{.*}}, i64 12, i64 1, metadata !{{.*}}, i64 16, i64 4, metadata {{.*}}, i64 20, i64 4, metadata {{.*}}}
+// CHECK: [[TS2]] = !{i64 0, i64 1, !{{.*}}, i64 4, i64 2, !{{.*}}, i64 8, i64 4, !{{.*}}, i64 12, i64 1, !{{.*}}, i64 16, i64 4, {{.*}}, i64 20, i64 4, {{.*}}}
 // (offset, size) = (0,8) char; (0,2) char; (4,8) char
-// CHECK: [[TS3]] = metadata !{i64 0, i64 8, metadata !{{.*}}, i64 0, i64 2, metadata !{{.*}}, i64 4, i64 8, metadata !{{.*}}}
-// CHECK: [[TS4]] = metadata !{i64 0, i64 1, metadata [[TAG_CHAR]], i64 1, i64 4, metadata [[TAG_INT]], i64 1, i64 1, metadata [[TAG_CHAR]], i64 2, i64 1, metadata [[TAG_CHAR]]}
-// CHECK: [[TS5]] = metadata !{i64 0, i64 1, metadata [[TAG_CHAR]], i64 4, i64 4, metadata [[TAG_INT]], i64 4, i64 1, metadata [[TAG_CHAR]], i64 5, i64 1, metadata [[TAG_CHAR]]}
+// CHECK: [[TS3]] = !{i64 0, i64 8, !{{.*}}, i64 0, i64 2, !{{.*}}, i64 4, i64 8, !{{.*}}}
+// CHECK: [[TS4]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 1, i64 4, [[TAG_INT]], i64 1, i64 1, [[TAG_CHAR]], i64 2, i64 1, [[TAG_CHAR]]}
+// CHECK: [[TS5]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 4, i64 4, [[TAG_INT]], i64 4, i64 1, [[TAG_CHAR]], i64 5, i64 1, [[TAG_CHAR]]}
diff --git a/test/CodeGen/tbaa.cpp b/test/CodeGen/tbaa.cpp
index 92d31e5..4a723f1 100644
--- a/test/CodeGen/tbaa.cpp
+++ b/test/CodeGen/tbaa.cpp
@@ -236,37 +236,37 @@
   return S->f32;
 }
 
-// CHECK: [[TYPE_char:!.*]] = metadata !{metadata !"omnipotent char", metadata [[TAG_cxx_tbaa:!.*]],
-// CHECK: [[TAG_cxx_tbaa]] = metadata !{metadata !"Simple C/C++ TBAA"}
-// CHECK: [[TAG_i32]] = metadata !{metadata [[TYPE_i32:!.*]], metadata [[TYPE_i32]], i64 0}
-// CHECK: [[TYPE_i32]] = metadata !{metadata !"int", metadata [[TYPE_char]],
-// CHECK: [[TAG_i16]] = metadata !{metadata [[TYPE_i16:!.*]], metadata [[TYPE_i16]], i64 0}
-// CHECK: [[TYPE_i16]] = metadata !{metadata !"short", metadata [[TYPE_char]],
-// CHECK: [[TAG_char]] = metadata !{metadata [[TYPE_char]], metadata [[TYPE_char]], i64 0}
+// CHECK: [[TYPE_char:!.*]] = !{!"omnipotent char", [[TAG_cxx_tbaa:!.*]],
+// CHECK: [[TAG_cxx_tbaa]] = !{!"Simple C/C++ TBAA"}
+// CHECK: [[TAG_i32]] = !{[[TYPE_i32:!.*]], [[TYPE_i32]], i64 0}
+// CHECK: [[TYPE_i32]] = !{!"int", [[TYPE_char]],
+// CHECK: [[TAG_i16]] = !{[[TYPE_i16:!.*]], [[TYPE_i16]], i64 0}
+// CHECK: [[TYPE_i16]] = !{!"short", [[TYPE_char]],
+// CHECK: [[TAG_char]] = !{[[TYPE_char]], [[TYPE_char]], i64 0}
 
-// PATH: [[TYPE_CHAR:!.*]] = metadata !{metadata !"omnipotent char", metadata
-// PATH: [[TAG_i32]] = metadata !{metadata [[TYPE_INT:!.*]], metadata [[TYPE_INT]], i64 0}
-// PATH: [[TYPE_INT]] = metadata !{metadata !"int", metadata [[TYPE_CHAR]]
-// PATH: [[TAG_A_f32]] = metadata !{metadata [[TYPE_A:!.*]], metadata [[TYPE_INT]], i64 4}
-// PATH: [[TYPE_A]] = metadata !{metadata !"_ZTS7StructA", metadata [[TYPE_SHORT:!.*]], i64 0, metadata [[TYPE_INT]], i64 4, metadata [[TYPE_SHORT]], i64 8, metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_SHORT:!.*]] = metadata !{metadata !"short", metadata [[TYPE_CHAR]]
-// PATH: [[TAG_A_f16]] = metadata !{metadata [[TYPE_A]], metadata [[TYPE_SHORT]], i64 0}
-// PATH: [[TAG_B_a_f32]] = metadata !{metadata [[TYPE_B:!.*]], metadata [[TYPE_INT]], i64 8}
-// PATH: [[TYPE_B]] = metadata !{metadata !"_ZTS7StructB", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_A]], i64 4, metadata [[TYPE_INT]], i64 20}
-// PATH: [[TAG_B_a_f16]] = metadata !{metadata [[TYPE_B]], metadata [[TYPE_SHORT]], i64 4}
-// PATH: [[TAG_B_f32]] = metadata !{metadata [[TYPE_B]], metadata [[TYPE_INT]], i64 20}
-// PATH: [[TAG_B_a_f32_2]] = metadata !{metadata [[TYPE_B]], metadata [[TYPE_INT]], i64 16}
-// PATH: [[TAG_S_f32]] = metadata !{metadata [[TYPE_S:!.*]], metadata [[TYPE_INT]], i64 4}
-// PATH: [[TYPE_S]] = metadata !{metadata !"_ZTS7StructS", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_INT]], i64 4}
-// PATH: [[TAG_S_f16]] = metadata !{metadata [[TYPE_S]], metadata [[TYPE_SHORT]], i64 0}
-// PATH: [[TAG_S2_f32]] = metadata !{metadata [[TYPE_S2:!.*]], metadata [[TYPE_INT]], i64 4}
-// PATH: [[TYPE_S2]] = metadata !{metadata !"_ZTS8StructS2", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_INT]], i64 4}
-// PATH: [[TAG_S2_f16]] = metadata !{metadata [[TYPE_S2]], metadata [[TYPE_SHORT]], i64 0}
-// PATH: [[TAG_C_b_a_f32]] = metadata !{metadata [[TYPE_C:!.*]], metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_C]] = metadata !{metadata !"_ZTS7StructC", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_B]], i64 4, metadata [[TYPE_INT]], i64 28}
-// PATH: [[TAG_D_b_a_f32]] = metadata !{metadata [[TYPE_D:!.*]], metadata [[TYPE_INT]], i64 12}
-// PATH: [[TYPE_D]] = metadata !{metadata !"_ZTS7StructD", metadata [[TYPE_SHORT]], i64 0, metadata [[TYPE_B]], i64 4, metadata [[TYPE_INT]], i64 28, metadata [[TYPE_CHAR]], i64 32}
-// PATH: [[TAG_five_b]] = metadata !{metadata [[TYPE_five:!.*]], metadata [[TYPE_CHAR]], i64 1}
-// PATH: [[TYPE_five]] = metadata !{metadata !"_ZTS4five", metadata [[TYPE_CHAR]], i64 0, metadata [[TYPE_INT]], i64 1, metadata [[TYPE_CHAR]], i64 1, metadata [[TYPE_CHAR]], i64 2}
-// PATH: [[TAG_six_b]] = metadata !{metadata [[TYPE_six:!.*]], metadata [[TYPE_CHAR]], i64 4}
-// PATH: [[TYPE_six]] = metadata !{metadata !"_ZTS3six", metadata [[TYPE_CHAR]], i64 0, metadata [[TYPE_INT]], i64 4, metadata [[TYPE_CHAR]], i64 4, metadata [[TYPE_CHAR]], i64 5}
+// PATH: [[TYPE_CHAR:!.*]] = !{!"omnipotent char", !
+// PATH: [[TAG_i32]] = !{[[TYPE_INT:!.*]], [[TYPE_INT]], i64 0}
+// PATH: [[TYPE_INT]] = !{!"int", [[TYPE_CHAR]]
+// PATH: [[TAG_A_f32]] = !{[[TYPE_A:!.*]], [[TYPE_INT]], i64 4}
+// PATH: [[TYPE_A]] = !{!"_ZTS7StructA", [[TYPE_SHORT:!.*]], i64 0, [[TYPE_INT]], i64 4, [[TYPE_SHORT]], i64 8, [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_SHORT:!.*]] = !{!"short", [[TYPE_CHAR]]
+// PATH: [[TAG_A_f16]] = !{[[TYPE_A]], [[TYPE_SHORT]], i64 0}
+// PATH: [[TAG_B_a_f32]] = !{[[TYPE_B:!.*]], [[TYPE_INT]], i64 8}
+// PATH: [[TYPE_B]] = !{!"_ZTS7StructB", [[TYPE_SHORT]], i64 0, [[TYPE_A]], i64 4, [[TYPE_INT]], i64 20}
+// PATH: [[TAG_B_a_f16]] = !{[[TYPE_B]], [[TYPE_SHORT]], i64 4}
+// PATH: [[TAG_B_f32]] = !{[[TYPE_B]], [[TYPE_INT]], i64 20}
+// PATH: [[TAG_B_a_f32_2]] = !{[[TYPE_B]], [[TYPE_INT]], i64 16}
+// PATH: [[TAG_S_f32]] = !{[[TYPE_S:!.*]], [[TYPE_INT]], i64 4}
+// PATH: [[TYPE_S]] = !{!"_ZTS7StructS", [[TYPE_SHORT]], i64 0, [[TYPE_INT]], i64 4}
+// PATH: [[TAG_S_f16]] = !{[[TYPE_S]], [[TYPE_SHORT]], i64 0}
+// PATH: [[TAG_S2_f32]] = !{[[TYPE_S2:!.*]], [[TYPE_INT]], i64 4}
+// PATH: [[TYPE_S2]] = !{!"_ZTS8StructS2", [[TYPE_SHORT]], i64 0, [[TYPE_INT]], i64 4}
+// PATH: [[TAG_S2_f16]] = !{[[TYPE_S2]], [[TYPE_SHORT]], i64 0}
+// PATH: [[TAG_C_b_a_f32]] = !{[[TYPE_C:!.*]], [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_C]] = !{!"_ZTS7StructC", [[TYPE_SHORT]], i64 0, [[TYPE_B]], i64 4, [[TYPE_INT]], i64 28}
+// PATH: [[TAG_D_b_a_f32]] = !{[[TYPE_D:!.*]], [[TYPE_INT]], i64 12}
+// PATH: [[TYPE_D]] = !{!"_ZTS7StructD", [[TYPE_SHORT]], i64 0, [[TYPE_B]], i64 4, [[TYPE_INT]], i64 28, [[TYPE_CHAR]], i64 32}
+// PATH: [[TAG_five_b]] = !{[[TYPE_five:!.*]], [[TYPE_CHAR]], i64 1}
+// PATH: [[TYPE_five]] = !{!"_ZTS4five", [[TYPE_CHAR]], i64 0, [[TYPE_INT]], i64 1, [[TYPE_CHAR]], i64 1, [[TYPE_CHAR]], i64 2}
+// PATH: [[TAG_six_b]] = !{[[TYPE_six:!.*]], [[TYPE_CHAR]], i64 4}
+// PATH: [[TYPE_six]] = !{!"_ZTS3six", [[TYPE_CHAR]], i64 0, [[TYPE_INT]], i64 4, [[TYPE_CHAR]], i64 4, [[TYPE_CHAR]], i64 5}
diff --git a/test/CodeGen/ubsan-type-blacklist.cpp b/test/CodeGen/ubsan-type-blacklist.cpp
index e2bbb6a..b3137e7 100644
--- a/test/CodeGen/ubsan-type-blacklist.cpp
+++ b/test/CodeGen/ubsan-type-blacklist.cpp
@@ -1,7 +1,7 @@
 // Verify ubsan vptr does not check down-casts on blacklisted types.
 // RUN: echo "type:_ZTI3Foo" > %t-type.blacklist
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=vptr -emit-llvm %s -o - | FileCheck %s --check-prefix=DEFAULT
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=vptr -fsanitize-blacklist=%t-type.blacklist -emit-llvm %s -o - | FileCheck %s --check-prefix=TYPE
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=vptr -fsanitize-recover=vptr -emit-llvm %s -o - | FileCheck %s --check-prefix=DEFAULT
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=vptr -fsanitize-recover=vptr -fsanitize-blacklist=%t-type.blacklist -emit-llvm %s -o - | FileCheck %s --check-prefix=TYPE
 
 class Bar {
 public:
diff --git a/test/CodeGen/vla-2.c b/test/CodeGen/vla-2.c
index 0a74907..894913d 100644
--- a/test/CodeGen/vla-2.c
+++ b/test/CodeGen/vla-2.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -std=gnu99 %s -emit-llvm -o - | grep ".*alloca.*align 16"
+// RUN: %clang_cc1 -std=gnu99 %s -emit-llvm -o - | FileCheck %s
+// CHECK: alloca {{.*}}, align 16
 
 extern void bar(int[]);
 
diff --git a/test/CodeGen/vla-3.c b/test/CodeGen/vla-3.c
index 4927b46..66acf58 100644
--- a/test/CodeGen/vla-3.c
+++ b/test/CodeGen/vla-3.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -std=gnu99 %s -emit-llvm -o - | grep ".*alloca.*align 16"
+// RUN: %clang_cc1 -std=gnu99 %s -emit-llvm -o - | FileCheck %s
+// CHECK: alloca {{.*}}, align 16
 
 void adr(char *);
 
diff --git a/test/CodeGen/vlt_to_pointer.c b/test/CodeGen/vlt_to_pointer.c
new file mode 100644
index 0000000..22c620a
--- /dev/null
+++ b/test/CodeGen/vlt_to_pointer.c
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+int c[1][3*2];
+// CHECK: @{{.+}} = {{.*}} global [1 x [6 x {{i[0-9]+}}]] zeroinitializer
+
+// CHECK-LABEL: @f
+int f(int * const m, int (**v)[*m * 2])
+{
+    return &(c[0][*m]) == &((*v)[0][*m]);
+    // CHECK: icmp
+    // CHECK: ret i{{[0-9]+}}
+}
+
+// CHECK-LABEL: @test
+int test(int n, int (*(*fn)(void))[n]) {
+  return (*fn())[0];
+}
+
+// CHECK-LABEL: @main
+int main()
+{
+    int m = 3;
+    int (*d)[3*2] = c;
+    int (*fn[m])(void);
+    return f(&m, &d) + test(m, &fn);
+
+    // CHECK: call {{.+}} @f(
+    // CHECK: ret i{{[0-9]+}}
+}
+
diff --git a/test/CodeGen/windows-on-arm-stack-probe-size.c b/test/CodeGen/windows-on-arm-stack-probe-size.c
new file mode 100644
index 0000000..d25e15d
--- /dev/null
+++ b/test/CodeGen/windows-on-arm-stack-probe-size.c
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -triple thumbv7-windows-itanium -mstack-probe-size=8096 -O2 -emit-llvm %s -o - \
+// RUN:     | FileCheck %s -check-prefix CHECK-8096
+
+// RUN: %clang_cc1 -triple thumbv7-windows-itanium -mstack-probe-size=4096 -O2 -emit-llvm %s -o - \
+// RUN:     | FileCheck %s -check-prefix CHECK-4096
+
+// RUN: %clang_cc1 -triple thumbv7-windows-itanium -O2 -emit-llvm %s -o - \
+// RUN:     | FileCheck %s -check-prefix CHECK
+
+__declspec(dllimport) void initialise(signed char buffer[4096]);
+
+__declspec(dllexport) signed char function(unsigned index) {
+  signed char buffer[4096];
+  initialise(buffer);
+  return buffer[index];
+}
+
+// CHECK-8096: attributes #0 = {
+// CHECK-8096: "stack-probe-size"="8096"
+// CHECK-8096: }
+
+// CHECK-4096: attributes #0 = {
+// CHECK-4096-NOT: "stack-probe-size"=
+// CHECK-4096: }
+
+// CHECK: attributes #0 = {
+// CHECK-NOT: "stack-probe-size"=
+// CHECK: }
diff --git a/test/CodeGen/windows-struct-abi.c b/test/CodeGen/windows-struct-abi.c
new file mode 100644
index 0000000..4b4a6f1
--- /dev/null
+++ b/test/CodeGen/windows-struct-abi.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -triple i686-windows-itanium -emit-llvm -o - %s | FileCheck %s
+
+struct f1 {
+  float f;
+};
+
+struct f1 return_f1(void) { while (1); }
+
+// CHECK: define i32 @return_f1()
+
+void receive_f1(struct f1 a0) { }
+
+// CHECK: define void @receive_f1(%struct.f1* byval align 4 %a0)
+
+struct f2 {
+  float f;
+  float g;
+};
+
+struct f2 return_f2(void) { while (1); }
+
+// CHECK: define i64 @return_f2()
+
+void receive_f2(struct f2 a0) { }
+
+// CHECK: define void @receive_f2(%struct.f2* byval align 4 %a0)
+
+struct f4 {
+  float f;
+  float g;
+  float h;
+  float i;
+};
+
+struct f4 return_f4(void) { while (1); }
+
+// CHECK: define void @return_f4(%struct.f4* noalias sret %agg.result)
+
+void receive_f4(struct f4 a0) { }
+
+// CHECK: define void @receive_f4(%struct.f4* byval align 4 %a0)
+
diff --git a/test/CodeGen/x86-atomic-long_double.c b/test/CodeGen/x86-atomic-long_double.c
new file mode 100644
index 0000000..22c7bd4
--- /dev/null
+++ b/test/CodeGen/x86-atomic-long_double.c
@@ -0,0 +1,469 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -target-cpu core2 %s -S -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple i686-linux-gnu -target-cpu core2 %s -S -emit-llvm -o - | FileCheck -check-prefix=CHECK32 %s
+
+long double testinc(_Atomic long double *addr) {
+  // CHECK-LABEL: @testinc
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VALUE:%.+]] = load atomic i128* [[INT_ADDR]] seq_cst, align 16
+  // CHECK: [[INT_LOAD_ADDR:%.+]] = bitcast x86_fp80* [[LD_ADDR:%.+]] to i128*
+  // CHECK: store i128 [[INT_VALUE]], i128* [[INT_LOAD_ADDR]], align 16
+  // CHECK: [[LD_VALUE:%.+]] = load x86_fp80* [[LD_ADDR]], align 16
+  // CHECK: br label %[[ATOMIC_OP:.+]]
+  // CHECK: [[ATOMIC_OP]]
+  // CHECK: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK: [[INC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 16
+  // CHECK: [[OLD_INT_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i128*
+  // CHECK: [[OLD_INT:%.+]] = load i128* [[OLD_INT_ADDR]], align 16
+  // CHECK: [[NEW_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[NEW_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[INC_VALUE]], x86_fp80* [[NEW_VALUE_ADDR]], align 16
+  // CHECK: [[NEW_INT_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR]] to i128*
+  // CHECK: [[NEW_INT:%.+]] = load i128* [[NEW_INT_ADDR]], align 16
+  // CHECK: [[OBJ_INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[RES:%.+]] = cmpxchg i128* [[OBJ_INT_ADDR]], i128 [[OLD_INT]], i128 [[NEW_INT]] seq_cst seq_cst
+  // CHECK: [[OLD_VALUE:%.+]] = extractvalue { i128, i1 } [[RES]], 0
+  // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
+  // CHECK: [[OLD_VALUE_RES_INT_PTR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_RES_PTR:%.+]] to i128*
+  // CHECK: store i128 [[OLD_VALUE]], i128* [[OLD_VALUE_RES_INT_PTR]], align 16
+  // CHECK: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_RES_PTR]], align 16
+  // CHECK: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK: [[ATOMIC_CONT]]
+  // CHECK: ret x86_fp80 [[INC_VALUE]]
+  // CHECK32-LABEL: @testinc
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[VOID_PTR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[TEMP_LD_PTR:%.+]] = bitcast x86_fp80* [[TEMP_LD_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_PTR]], i8* [[TEMP_LD_PTR]], i32 5)
+  // CHECK32: [[LD_VALUE:%.+]] = load x86_fp80* [[TEMP_LD_ADDR]], align 4
+  // CHECK32: br label %[[ATOMIC_OP:.+]]
+  // CHECK32: [[ATOMIC_OP]]
+  // CHECK32: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK32: [[INC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK32: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: [[DESIRED_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[DESIRED_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[INC_VALUE]], x86_fp80* [[DESIRED_VALUE_ADDR]], align 4
+  // CHECK32: [[OBJ:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[EXPECTED:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i8*
+  // CHECK32: [[DESIRED:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR]] to i8*
+  // CHECK32: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i32 12, i8* [[OBJ]], i8* [[EXPECTED]], i8* [[DESIRED]], i32 7, i32 7)
+  // CHECK32: [[LD_VALUE:%.+]] = load x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK32: [[ATOMIC_CONT]]
+  // CHECK32: ret x86_fp80 [[INC_VALUE]]
+
+  return ++*addr;
+}
+
+long double testdec(_Atomic long double *addr) {
+  // CHECK-LABEL: @testdec
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VALUE:%.+]] = load atomic i128* [[INT_ADDR]] seq_cst, align 16
+  // CHECK: [[INT_LOAD_ADDR:%.+]] = bitcast x86_fp80* [[LD_ADDR:%.+]] to i128*
+  // CHECK: store i128 [[INT_VALUE]], i128* [[INT_LOAD_ADDR]], align 16
+  // CHECK: [[ORIG_LD_VALUE:%.+]] = load x86_fp80* [[LD_ADDR]], align 16
+  // CHECK: br label %[[ATOMIC_OP:.+]]
+  // CHECK: [[ATOMIC_OP]]
+  // CHECK: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[ORIG_LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK: [[DEC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 16
+  // CHECK: [[OLD_INT_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i128*
+  // CHECK: [[OLD_INT:%.+]] = load i128* [[OLD_INT_ADDR]], align 16
+  // CHECK: [[NEW_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[NEW_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[DEC_VALUE]], x86_fp80* [[NEW_VALUE_ADDR]], align 16
+  // CHECK: [[NEW_INT_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR]] to i128*
+  // CHECK: [[NEW_INT:%.+]] = load i128* [[NEW_INT_ADDR]], align 16
+  // CHECK: [[OBJ_INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[RES:%.+]] = cmpxchg i128* [[OBJ_INT_ADDR]], i128 [[OLD_INT]], i128 [[NEW_INT]] seq_cst seq_cst
+  // CHECK: [[OLD_VALUE:%.+]] = extractvalue { i128, i1 } [[RES]], 0
+  // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
+  // CHECK: [[OLD_VALUE_RES_INT_PTR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_RES_PTR:%.+]] to i128*
+  // CHECK: store i128 [[OLD_VALUE]], i128* [[OLD_VALUE_RES_INT_PTR]], align 16
+  // CHECK: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_RES_PTR]], align 16
+  // CHECK: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK: [[ATOMIC_CONT]]
+  // CHECK: ret x86_fp80 [[ORIG_LD_VALUE]]
+  // CHECK32-LABEL: @testdec
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[VOID_PTR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[TEMP_LD_PTR:%.+]] = bitcast x86_fp80* [[TEMP_LD_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_PTR]], i8* [[TEMP_LD_PTR]], i32 5)
+  // CHECK32: [[ORIG_LD_VALUE:%.+]] = load x86_fp80* [[TEMP_LD_ADDR]], align 4
+  // CHECK32: br label %[[ATOMIC_OP:.+]]
+  // CHECK32: [[ATOMIC_OP]]
+  // CHECK32: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[ORIG_LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK32: [[DEC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK32: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: [[DESIRED_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[DESIRED_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[DEC_VALUE]], x86_fp80* [[DESIRED_VALUE_ADDR]], align 4
+  // CHECK32: [[OBJ:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[EXPECTED:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i8*
+  // CHECK32: [[DESIRED:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR]] to i8*
+  // CHECK32: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i32 12, i8* [[OBJ]], i8* [[EXPECTED]], i8* [[DESIRED]], i32 7, i32 7)
+  // CHECK32: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK32: [[ATOMIC_CONT]]
+  // CHECK32: ret x86_fp80 [[ORIG_LD_VALUE]]
+
+  return (*addr)--;
+}
+
+long double testcompassign(_Atomic long double *addr) {
+  *addr -= 25;
+  // CHECK-LABEL: @testcompassign
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VALUE:%.+]] = load atomic i128* [[INT_ADDR]] seq_cst, align 16
+  // CHECK: [[INT_LOAD_ADDR:%.+]] = bitcast x86_fp80* [[LD_ADDR:%.+]] to i128*
+  // CHECK: store i128 [[INT_VALUE]], i128* [[INT_LOAD_ADDR]], align 16
+  // CHECK: [[LD_VALUE:%.+]] = load x86_fp80* [[LD_ADDR]], align 16
+  // CHECK: br label %[[ATOMIC_OP:.+]]
+  // CHECK: [[ATOMIC_OP]]
+  // CHECK: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK: [[SUB_VALUE:%.+]] = fsub x86_fp80 [[OLD_VALUE]],
+  // CHECK: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 16
+  // CHECK: [[OLD_INT_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i128*
+  // CHECK: [[OLD_INT:%.+]] = load i128* [[OLD_INT_ADDR]], align 16
+  // CHECK: [[NEW_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[NEW_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[SUB_VALUE]], x86_fp80* [[NEW_VALUE_ADDR]], align 16
+  // CHECK: [[NEW_INT_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR]] to i128*
+  // CHECK: [[NEW_INT:%.+]] = load i128* [[NEW_INT_ADDR]], align 16
+  // CHECK: [[OBJ_INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[RES:%.+]] = cmpxchg i128* [[OBJ_INT_ADDR]], i128 [[OLD_INT]], i128 [[NEW_INT]] seq_cst seq_cst
+  // CHECK: [[OLD_VALUE:%.+]] = extractvalue { i128, i1 } [[RES]], 0
+  // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
+  // CHECK: [[OLD_VALUE_RES_INT_PTR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_RES_PTR:%.+]] to i128*
+  // CHECK: store i128 [[OLD_VALUE]], i128* [[OLD_VALUE_RES_INT_PTR]], align 16
+  // CHECK: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_RES_PTR]], align 16
+  // CHECK: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK: [[ATOMIC_CONT]]
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 8
+  // CHECK: [[ADDR_INT:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VAL:%.+]] = load atomic i128* [[ADDR_INT]] seq_cst, align 16
+  // CHECK: [[INT_LD_TEMP:%.+]] = bitcast x86_fp80* [[LD_TEMP:%.+]] to i128*
+  // CHECK: store i128 [[INT_VAL]], i128* [[INT_LD_TEMP:%.+]], align 16
+  // CHECK: [[RET_VAL:%.+]] = load x86_fp80* [[LD_TEMP]], align 16
+  // CHECK: ret x86_fp80 [[RET_VAL]]
+  // CHECK32-LABEL: @testcompassign
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[VOID_PTR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[TEMP_LD_PTR:%.+]] = bitcast x86_fp80* [[TEMP_LD_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_PTR]], i8* [[TEMP_LD_PTR]], i32 5)
+  // CHECK32: [[LD_VALUE:%.+]] = load x86_fp80* [[TEMP_LD_ADDR]], align 4
+  // CHECK32: br label %[[ATOMIC_OP:.+]]
+  // CHECK32: [[ATOMIC_OP]]
+  // CHECK32: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK32: [[INC_VALUE:%.+]] = fsub x86_fp80 [[OLD_VALUE]],
+  // CHECK32: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: [[DESIRED_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[DESIRED_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[INC_VALUE]], x86_fp80* [[DESIRED_VALUE_ADDR]], align 4
+  // CHECK32: [[OBJ:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[EXPECTED:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i8*
+  // CHECK32: [[DESIRED:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR]] to i8*
+  // CHECK32: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i32 12, i8* [[OBJ]], i8* [[EXPECTED]], i8* [[DESIRED]], i32 7, i32 7)
+  // CHECK32: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK32: [[ATOMIC_CONT]]
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 4
+  // CHECK32: [[VOID_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[VOID_GET_ADDR:%.+]] = bitcast x86_fp80* [[GET_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_ADDR]], i8* [[VOID_GET_ADDR]], i32 5)
+  // CHECK32: [[RET_VAL:%.+]] = load x86_fp80* [[GET_ADDR]], align 4
+  // CHECK32: ret x86_fp80 [[RET_VAL]]
+  return *addr;
+}
+
+long double testassign(_Atomic long double *addr) {
+  // CHECK-LABEL: @testassign
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[STORE_TEMP_VOID_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[STORE_TEMP_VOID_PTR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 {{.+}}, x86_fp80* [[STORE_TEMP_PTR]], align 16
+  // CHECK: [[STORE_TEMP_INT_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR]] to i128*
+  // CHECK: [[STORE_TEMP_INT:%.+]] = load i128* [[STORE_TEMP_INT_PTR]], align 16
+  // CHECK: [[ADDR_INT:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: store atomic i128 [[STORE_TEMP_INT]], i128* [[ADDR_INT]] seq_cst, align 16
+  // CHECK32-LABEL: @testassign
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[STORE_TEMP_VOID_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[STORE_TEMP_VOID_PTR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 {{.+}}, x86_fp80* [[STORE_TEMP_PTR]], align 4
+  // CHECK32: [[ADDR_VOID:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[STORE_TEMP_VOID_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR]] to i8*
+  // CHECK32: call void @__atomic_store(i32 12, i8* [[ADDR_VOID]], i8* [[STORE_TEMP_VOID_PTR]], i32 5)
+  *addr = 115;
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 8
+  // CHECK: [[ADDR_INT:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VAL:%.+]] = load atomic i128* [[ADDR_INT]] seq_cst, align 16
+  // CHECK: [[INT_LD_TEMP:%.+]] = bitcast x86_fp80* [[LD_TEMP:%.+]] to i128*
+  // CHECK: store i128 [[INT_VAL]], i128* [[INT_LD_TEMP:%.+]], align 16
+  // CHECK: [[RET_VAL:%.+]] = load x86_fp80* [[LD_TEMP]], align 16
+  // CHECK: ret x86_fp80 [[RET_VAL]]
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 4
+  // CHECK32: [[VOID_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[VOID_LD_TEMP:%.+]] = bitcast x86_fp80* [[LD_TEMP:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_ADDR]], i8* [[VOID_LD_TEMP]], i32 5)
+  // CHECK32: [[RET_VAL:%.+]] = load x86_fp80* [[LD_TEMP]], align 4
+  // CHECK32: ret x86_fp80 [[RET_VAL]]
+
+  return *addr;
+}
+
+long double test_volatile_inc(volatile _Atomic long double *addr) {
+  // CHECK-LABEL: @test_volatile_inc
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VALUE:%.+]] = load atomic volatile i128* [[INT_ADDR]] seq_cst, align 16
+  // CHECK: [[INT_LOAD_ADDR:%.+]] = bitcast x86_fp80* [[LD_ADDR:%.+]] to i128*
+  // CHECK: store i128 [[INT_VALUE]], i128* [[INT_LOAD_ADDR]], align 16
+  // CHECK: [[LD_VALUE:%.+]] = load x86_fp80* [[LD_ADDR]], align 16
+  // CHECK: br label %[[ATOMIC_OP:.+]]
+  // CHECK: [[ATOMIC_OP]]
+  // CHECK: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK: [[INC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 16
+  // CHECK: [[OLD_INT_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i128*
+  // CHECK: [[OLD_INT:%.+]] = load i128* [[OLD_INT_ADDR]], align 16
+  // CHECK: [[NEW_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[NEW_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[INC_VALUE]], x86_fp80* [[NEW_VALUE_ADDR]], align 16
+  // CHECK: [[NEW_INT_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR]] to i128*
+  // CHECK: [[NEW_INT:%.+]] = load i128* [[NEW_INT_ADDR]], align 16
+  // CHECK: [[OBJ_INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[RES:%.+]] = cmpxchg volatile i128* [[OBJ_INT_ADDR]], i128 [[OLD_INT]], i128 [[NEW_INT]] seq_cst seq_cst
+  // CHECK: [[OLD_VALUE:%.+]] = extractvalue { i128, i1 } [[RES]], 0
+  // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
+  // CHECK: [[OLD_VALUE_RES_INT_PTR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_RES_PTR:%.+]] to i128*
+  // CHECK: store i128 [[OLD_VALUE]], i128* [[OLD_VALUE_RES_INT_PTR]], align 16
+  // CHECK: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_RES_PTR]], align 16
+  // CHECK: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK: [[ATOMIC_CONT]]
+  // CHECK: ret x86_fp80 [[INC_VALUE]]
+  // CHECK32-LABEL: @test_volatile_inc
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[VOID_PTR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[TEMP_LD_PTR:%.+]] = bitcast x86_fp80* [[TEMP_LD_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_PTR]], i8* [[TEMP_LD_PTR]], i32 5)
+  // CHECK32: [[LD_VALUE:%.+]] = load x86_fp80* [[TEMP_LD_ADDR]], align 4
+  // CHECK32: br label %[[ATOMIC_OP:.+]]
+  // CHECK32: [[ATOMIC_OP]]
+  // CHECK32: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK32: [[INC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK32: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: [[DESIRED_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[DESIRED_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[INC_VALUE]], x86_fp80* [[DESIRED_VALUE_ADDR]], align 4
+  // CHECK32: [[OBJ:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[EXPECTED:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i8*
+  // CHECK32: [[DESIRED:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR]] to i8*
+  // CHECK32: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i32 12, i8* [[OBJ]], i8* [[EXPECTED]], i8* [[DESIRED]], i32 7, i32 7)
+  // CHECK32: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK32: [[ATOMIC_CONT]]
+  // CHECK32: ret x86_fp80 [[INC_VALUE]]
+  return ++*addr;
+}
+
+long double test_volatile_dec(volatile _Atomic long double *addr) {
+  // CHECK-LABEL: @test_volatile_dec
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VALUE:%.+]] = load atomic volatile i128* [[INT_ADDR]] seq_cst, align 16
+  // CHECK: [[INT_LOAD_ADDR:%.+]] = bitcast x86_fp80* [[LD_ADDR:%.+]] to i128*
+  // CHECK: store i128 [[INT_VALUE]], i128* [[INT_LOAD_ADDR]], align 16
+  // CHECK: [[ORIG_LD_VALUE:%.+]] = load x86_fp80* [[LD_ADDR]], align 16
+  // CHECK: br label %[[ATOMIC_OP:.+]]
+  // CHECK: [[ATOMIC_OP]]
+  // CHECK: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[ORIG_LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK: [[DEC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 16
+  // CHECK: [[OLD_INT_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i128*
+  // CHECK: [[OLD_INT:%.+]] = load i128* [[OLD_INT_ADDR]], align 16
+  // CHECK: [[NEW_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[NEW_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[DEC_VALUE]], x86_fp80* [[NEW_VALUE_ADDR]], align 16
+  // CHECK: [[NEW_INT_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR]] to i128*
+  // CHECK: [[NEW_INT:%.+]] = load i128* [[NEW_INT_ADDR]], align 16
+  // CHECK: [[OBJ_INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[RES:%.+]] = cmpxchg volatile i128* [[OBJ_INT_ADDR]], i128 [[OLD_INT]], i128 [[NEW_INT]] seq_cst seq_cst
+  // CHECK: [[OLD_VALUE:%.+]] = extractvalue { i128, i1 } [[RES]], 0
+  // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
+  // CHECK: [[OLD_VALUE_RES_INT_PTR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_RES_PTR:%.+]] to i128*
+  // CHECK: store i128 [[OLD_VALUE]], i128* [[OLD_VALUE_RES_INT_PTR]], align 16
+  // CHECK: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_RES_PTR]], align 16
+  // CHECK: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK: [[ATOMIC_CONT]]
+  // CHECK: ret x86_fp80 [[ORIG_LD_VALUE]]
+  // CHECK32-LABEL: @test_volatile_dec
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[VOID_PTR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[TEMP_LD_PTR:%.+]] = bitcast x86_fp80* [[TEMP_LD_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_PTR]], i8* [[TEMP_LD_PTR]], i32 5)
+  // CHECK32: [[ORIG_LD_VALUE:%.+]] = load x86_fp80* [[TEMP_LD_ADDR]], align 4
+  // CHECK32: br label %[[ATOMIC_OP:.+]]
+  // CHECK32: [[ATOMIC_OP]]
+  // CHECK32: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[ORIG_LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK32: [[DEC_VALUE:%.+]] = fadd x86_fp80 [[OLD_VALUE]],
+  // CHECK32: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: [[DESIRED_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[DESIRED_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[DEC_VALUE]], x86_fp80* [[DESIRED_VALUE_ADDR]], align 4
+  // CHECK32: [[OBJ:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[EXPECTED:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i8*
+  // CHECK32: [[DESIRED:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR]] to i8*
+  // CHECK32: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i32 12, i8* [[OBJ]], i8* [[EXPECTED]], i8* [[DESIRED]], i32 7, i32 7)
+  // CHECK32: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK32: [[ATOMIC_CONT]]
+  // CHECK32: ret x86_fp80 [[ORIG_LD_VALUE]]
+  return (*addr)--;
+}
+
+long double test_volatile_compassign(volatile _Atomic long double *addr) {
+  *addr -= 25;
+  // CHECK-LABEL: @test_volatile_compassign
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VALUE:%.+]] = load atomic volatile i128* [[INT_ADDR]] seq_cst, align 16
+  // CHECK: [[INT_LOAD_ADDR:%.+]] = bitcast x86_fp80* [[LD_ADDR:%.+]] to i128*
+  // CHECK: store i128 [[INT_VALUE]], i128* [[INT_LOAD_ADDR]], align 16
+  // CHECK: [[LD_VALUE:%.+]] = load x86_fp80* [[LD_ADDR]], align 16
+  // CHECK: br label %[[ATOMIC_OP:.+]]
+  // CHECK: [[ATOMIC_OP]]
+  // CHECK: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK: [[SUB_VALUE:%.+]] = fsub x86_fp80 [[OLD_VALUE]],
+  // CHECK: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 16
+  // CHECK: [[OLD_INT_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i128*
+  // CHECK: [[OLD_INT:%.+]] = load i128* [[OLD_INT_ADDR]], align 16
+  // CHECK: [[NEW_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[NEW_VALUE_VOID_ADDR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 [[SUB_VALUE]], x86_fp80* [[NEW_VALUE_ADDR]], align 16
+  // CHECK: [[NEW_INT_ADDR:%.+]] = bitcast x86_fp80* [[NEW_VALUE_ADDR]] to i128*
+  // CHECK: [[NEW_INT:%.+]] = load i128* [[NEW_INT_ADDR]], align 16
+  // CHECK: [[OBJ_INT_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[RES:%.+]] = cmpxchg volatile i128* [[OBJ_INT_ADDR]], i128 [[OLD_INT]], i128 [[NEW_INT]] seq_cst seq_cst
+  // CHECK: [[OLD_VALUE:%.+]] = extractvalue { i128, i1 } [[RES]], 0
+  // CHECK: [[FAIL_SUCCESS:%.+]] = extractvalue { i128, i1 } [[RES]], 1
+  // CHECK: [[OLD_VALUE_RES_INT_PTR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_RES_PTR:%.+]] to i128*
+  // CHECK: store i128 [[OLD_VALUE]], i128* [[OLD_VALUE_RES_INT_PTR]], align 16
+  // CHECK: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_RES_PTR]], align 16
+  // CHECK: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK: [[ATOMIC_CONT]]
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 8
+  // CHECK: [[ADDR_INT:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VAL:%.+]] = load atomic volatile i128* [[ADDR_INT]] seq_cst, align 16
+  // CHECK: [[INT_LD_TEMP:%.+]] = bitcast x86_fp80* [[LD_TEMP:%.+]] to i128*
+  // CHECK: store i128 [[INT_VAL]], i128* [[INT_LD_TEMP:%.+]], align 16
+  // CHECK: [[RET_VAL:%.+]] = load x86_fp80* [[LD_TEMP]], align 16
+  // CHECK32-LABEL: @test_volatile_compassign
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[VOID_PTR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[TEMP_LD_PTR:%.+]] = bitcast x86_fp80* [[TEMP_LD_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_PTR]], i8* [[TEMP_LD_PTR]], i32 5)
+  // CHECK32: [[LD_VALUE:%.+]] = load x86_fp80* [[TEMP_LD_ADDR]], align 4
+  // CHECK32: br label %[[ATOMIC_OP:.+]]
+  // CHECK32: [[ATOMIC_OP]]
+  // CHECK32: [[OLD_VALUE:%.+]] = phi x86_fp80 [ [[LD_VALUE]], %{{.+}} ], [ [[LD_VALUE:%.+]], %[[ATOMIC_OP]] ]
+  // CHECK32: [[INC_VALUE:%.+]] = fsub x86_fp80 [[OLD_VALUE]],
+  // CHECK32: [[OLD_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[OLD_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[OLD_VALUE]], x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: [[DESIRED_VALUE_VOID_ADDR:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[DESIRED_VALUE_VOID_ADDR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 [[INC_VALUE]], x86_fp80* [[DESIRED_VALUE_ADDR]], align 4
+  // CHECK32: [[OBJ:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[EXPECTED:%.+]] = bitcast x86_fp80* [[OLD_VALUE_ADDR]] to i8*
+  // CHECK32: [[DESIRED:%.+]] = bitcast x86_fp80* [[DESIRED_VALUE_ADDR]] to i8*
+  // CHECK32: [[FAIL_SUCCESS:%.+]] = call zeroext i1 @__atomic_compare_exchange(i32 12, i8* [[OBJ]], i8* [[EXPECTED]], i8* [[DESIRED]], i32 7, i32 7)
+  // CHECK32: [[LD_VALUE]] = load x86_fp80* [[OLD_VALUE_ADDR]], align 4
+  // CHECK32: br i1 [[FAIL_SUCCESS]], label %[[ATOMIC_CONT:.+]], label %[[ATOMIC_OP]]
+  // CHECK32: [[ATOMIC_CONT]]
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 4
+  // CHECK32: [[VOID_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[VOID_GET_ADDR:%.+]] = bitcast x86_fp80* [[GET_ADDR:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_ADDR]], i8* [[VOID_GET_ADDR]], i32 5)
+  // CHECK32: [[RET_VAL:%.+]] = load x86_fp80* [[GET_ADDR]], align 4
+  // CHECK32: ret x86_fp80 [[RET_VAL]]
+  return *addr;
+}
+
+long double test_volatile_assign(volatile _Atomic long double *addr) {
+  // CHECK-LABEL: @test_volatile_assign
+  // CHECK: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 8
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 8
+  // CHECK: [[STORE_TEMP_VOID_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR:%.+]] to i8*
+  // CHECK: call void @llvm.memset.p0i8.i64(i8* [[STORE_TEMP_VOID_PTR]], i8 0, i64 16, i32 16, i1 false)
+  // CHECK: store x86_fp80 {{.+}}, x86_fp80* [[STORE_TEMP_PTR]], align 16
+  // CHECK: [[STORE_TEMP_INT_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR]] to i128*
+  // CHECK: [[STORE_TEMP_INT:%.+]] = load i128* [[STORE_TEMP_INT_PTR]], align 16
+  // CHECK: [[ADDR_INT:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: store atomic volatile i128 [[STORE_TEMP_INT]], i128* [[ADDR_INT]] seq_cst, align 16
+  // CHECK32-LABEL: @test_volatile_assign
+  // CHECK32: store x86_fp80* %{{.+}}, x86_fp80** [[ADDR_ADDR:%.+]], align 4
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** [[ADDR_ADDR]], align 4
+  // CHECK32: [[STORE_TEMP_VOID_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR:%.+]] to i8*
+  // CHECK32: call void @llvm.memset.p0i8.i64(i8* [[STORE_TEMP_VOID_PTR]], i8 0, i64 12, i32 4, i1 false)
+  // CHECK32: store x86_fp80 {{.+}}, x86_fp80* [[STORE_TEMP_PTR]], align 4
+  // CHECK32: [[ADDR_VOID:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[STORE_TEMP_VOID_PTR:%.+]] = bitcast x86_fp80* [[STORE_TEMP_PTR]] to i8*
+  // CHECK32: call void @__atomic_store(i32 12, i8* [[ADDR_VOID]], i8* [[STORE_TEMP_VOID_PTR]], i32 5)
+  *addr = 115;
+  // CHECK: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 8
+  // CHECK: [[ADDR_INT:%.+]] = bitcast x86_fp80* [[ADDR]] to i128*
+  // CHECK: [[INT_VAL:%.+]] = load atomic volatile i128* [[ADDR_INT]] seq_cst, align 16
+  // CHECK: [[INT_LD_TEMP:%.+]] = bitcast x86_fp80* [[LD_TEMP:%.+]] to i128*
+  // CHECK: store i128 [[INT_VAL]], i128* [[INT_LD_TEMP:%.+]], align 16
+  // CHECK: [[RET_VAL:%.+]] = load x86_fp80* [[LD_TEMP]], align 16
+  // CHECK: ret x86_fp80 [[RET_VAL]]
+  // CHECK32: [[ADDR:%.+]] = load x86_fp80** %{{.+}}, align 4
+  // CHECK32: [[VOID_ADDR:%.+]] = bitcast x86_fp80* [[ADDR]] to i8*
+  // CHECK32: [[VOID_LD_TEMP:%.+]] = bitcast x86_fp80* [[LD_TEMP:%.+]] to i8*
+  // CHECK32: call void @__atomic_load(i32 12, i8* [[VOID_ADDR]], i8* [[VOID_LD_TEMP]], i32 5)
+  // CHECK32: [[RET_VAL:%.+]] = load x86_fp80* [[LD_TEMP]], align 4
+  // CHECK32: ret x86_fp80 [[RET_VAL]]
+
+  return *addr;
+}
diff --git a/test/CodeGen/x86_64-arguments-nacl.c b/test/CodeGen/x86_64-arguments-nacl.c
index 1c3f5b0..cbfad1a 100644
--- a/test/CodeGen/x86_64-arguments-nacl.c
+++ b/test/CodeGen/x86_64-arguments-nacl.c
@@ -90,31 +90,3 @@
 {
   func(ss);
 }
-
-
-typedef struct {
-  int a;
-  int b;
-} s1;
-// CHECK-LABEL: define i32 @f48(%struct.s1* byval %s)
-int __attribute__((pnaclcall)) f48(s1 s) { return s.a; }
-
-// CHECK-LABEL: define void @f49(%struct.s1* noalias sret %agg.result)
-s1 __attribute__((pnaclcall)) f49() { s1 s; s.a = s.b = 1; return s; }
-
-union simple_union {
-  int a;
-  char b;
-};
-// Unions should be passed as byval structs
-// CHECK-LABEL: define void @f50(%union.simple_union* byval %s)
-void __attribute__((pnaclcall)) f50(union simple_union s) {}
-
-typedef struct {
-  int b4 : 4;
-  int b3 : 3;
-  int b8 : 8;
-} bitfield1;
-// Bitfields should be passed as byval structs
-// CHECK-LABEL: define void @f51(%struct.bitfield1* byval %bf1)
-void __attribute__((pnaclcall)) f51(bitfield1 bf1) {}
diff --git a/test/CodeGen/x86_64-arguments-win32.c b/test/CodeGen/x86_64-arguments-win32.c
index 5aea7fc..7731ead 100644
--- a/test/CodeGen/x86_64-arguments-win32.c
+++ b/test/CodeGen/x86_64-arguments-win32.c
@@ -14,3 +14,18 @@
 
 // CHECK-LABEL: define void @f4(i16 %a)
 void f4(unsigned short a) {}
+
+// For ABI compatibility with ICC, _Complex should be passed/returned
+// as if it were a struct with two elements.
+
+// CHECK-LABEL: define void @f5(i64 %a.coerce)
+void f5(_Complex float a) {}
+
+// CHECK-LABEL: define void @f6({ double, double }* %a)
+void f6(_Complex double a) {}
+
+// CHECK-LABEL: define i64 @f7()
+_Complex float f7() { return 1.0; }
+
+// CHECK-LABEL: define void @f8({ double, double }* noalias sret %agg.result)
+_Complex double f8() { return 1.0; }
diff --git a/test/CodeGen/x86_64-arguments.c b/test/CodeGen/x86_64-arguments.c
index 5d01d3b..e82e7b0 100644
--- a/test/CodeGen/x86_64-arguments.c
+++ b/test/CodeGen/x86_64-arguments.c
@@ -184,6 +184,28 @@
   return X;
 }
 
+// PR22563 - We should unwrap simple structs and arrays to pass
+// and return them in the appropriate vector registers if possible.
+
+typedef float v8f32 __attribute__((__vector_size__(32)));
+struct v8f32wrapper {
+  v8f32 v;
+};
+
+struct v8f32wrapper f27a(struct v8f32wrapper X) {
+  // AVX-LABEL: define <8 x float> @f27a(<8 x float> %X.coerce)
+  return X;
+}
+
+struct v8f32wrapper_wrapper {
+  v8f32 v[1];
+};
+
+struct v8f32wrapper_wrapper f27b(struct v8f32wrapper_wrapper X) {
+  // AVX-LABEL: define <8 x float> @f27b(<8 x float> %X.coerce)
+  return X;
+}
+
 // rdar://5711709
 struct f28c {
   double x;
diff --git a/test/CodeGen/xcore-stringtype.c b/test/CodeGen/xcore-stringtype.c
index 4315bc1..1297ca0 100644
--- a/test/CodeGen/xcore-stringtype.c
+++ b/test/CodeGen/xcore-stringtype.c
@@ -23,9 +23,9 @@
 
 
 // test BuiltinType
-// CHECK: !{{[0-9]+}} = metadata !{void (i1, i8, i8, i8, i16, i16, i16, i32, i32, i32,
+// CHECK: !{{[0-9]+}} = !{void (i1, i8, i8, i8, i16, i16, i16, i32, i32, i32,
 // CHECK:      i32, i32, i32, i64, i64, i64, float, double, double)*
-// CHECK:      @builtinType, metadata !"f{0}(b,uc,uc,sc,ss,us,ss,si,ui,si,sl,
+// CHECK:      @builtinType, !"f{0}(b,uc,uc,sc,ss,us,ss,si,ui,si,sl,
 // CHECK:      ul,sl,sll,ull,sll,ft,d,ld)"}
 void builtinType(_Bool B, char C, unsigned char UC, signed char SC, short S,
                  unsigned short US, signed short SS, int I, unsigned int UI,
@@ -36,14 +36,14 @@
 
 
 // test FunctionType & Qualifiers
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @gI, metadata !"f{0}()"}
-// CHECK: !{{[0-9]+}} = metadata !{void (...)* @eI, metadata !"f{0}()"}
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @gV, metadata !"f{0}(0)"}
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @eV, metadata !"f{0}(0)"}
-// CHECK: !{{[0-9]+}} = metadata !{void (i32, ...)* @gVA, metadata !"f{0}(si,va)"}
-// CHECK: !{{[0-9]+}} = metadata !{void (i32, ...)* @eVA, metadata !"f{0}(si,va)"}
-// CHECK: !{{[0-9]+}} = metadata !{i32* (i32*)* @gQ, metadata !"f{crv:p(cv:si)}(p(cv:si))"}
-// CHECK: !{{[0-9]+}} = metadata !{i32* (i32*)* @eQ, metadata !"f{crv:p(cv:si)}(p(cv:si))"}
+// CHECK: !{{[0-9]+}} = !{void ()* @gI, !"f{0}()"}
+// CHECK: !{{[0-9]+}} = !{void (...)* @eI, !"f{0}()"}
+// CHECK: !{{[0-9]+}} = !{void ()* @gV, !"f{0}(0)"}
+// CHECK: !{{[0-9]+}} = !{void ()* @eV, !"f{0}(0)"}
+// CHECK: !{{[0-9]+}} = !{void (i32, ...)* @gVA, !"f{0}(si,va)"}
+// CHECK: !{{[0-9]+}} = !{void (i32, ...)* @eVA, !"f{0}(si,va)"}
+// CHECK: !{{[0-9]+}} = !{i32* (i32*)* @gQ, !"f{crv:p(cv:si)}(p(cv:si))"}
+// CHECK: !{{[0-9]+}} = !{i32* (i32*)* @eQ, !"f{crv:p(cv:si)}(p(cv:si))"}
 extern void eI();
 void gI() {eI();};
 extern void eV(void);
@@ -57,10 +57,10 @@
 
 
 // test PointerType
-// CHECK: !{{[0-9]+}} = metadata !{i32* (i32*, i32* (i32*)*)*
-// CHECK:       @pointerType, metadata !"f{p(si)}(p(si),p(f{p(si)}(p(si))))"}
-// CHECK: !{{[0-9]+}} = metadata !{i32** @EP, metadata !"p(si)"}
-// CHECK: !{{[0-9]+}} = metadata !{i32** @GP, metadata !"p(si)"}
+// CHECK: !{{[0-9]+}} = !{i32* (i32*, i32* (i32*)*)*
+// CHECK:       @pointerType, !"f{p(si)}(p(si),p(f{p(si)}(p(si))))"}
+// CHECK: !{{[0-9]+}} = !{i32** @EP, !"p(si)"}
+// CHECK: !{{[0-9]+}} = !{i32** @GP, !"p(si)"}
 extern int* EP;
 int* GP;
 int* pointerType(int *I, int * (*FP)(int *)) {
@@ -68,19 +68,19 @@
 }
 
 // test ArrayType
-// CHECK: !{{[0-9]+}} = metadata !{[2 x i32]* (i32*, i32*, [2 x i32]*, [2 x i32]*, i32*)*
-// CHECK:       @arrayType, metadata !"f{p(a(2:si))}(p(si),p(cv:si),p(a(2:si)),
+// CHECK: !{{[0-9]+}} = !{[2 x i32]* (i32*, i32*, [2 x i32]*, [2 x i32]*, i32*)*
+// CHECK:       @arrayType, !"f{p(a(2:si))}(p(si),p(cv:si),p(a(2:si)),
 // CHECK:       p(a(2:si)),p(si))"}
-// CHECK: !{{[0-9]+}} = metadata !{[0 x i32]* @EA1, metadata !"a(*:cv:si)"}
-// CHECK: !{{[0-9]+}} = metadata !{[2 x i32]* @EA2, metadata !"a(2:si)"}
-// CHECK: !{{[0-9]+}} = metadata !{[0 x [2 x i32]]* @EA3, metadata !"a(*:a(2:si))"}
-// CHECK: !{{[0-9]+}} = metadata !{[3 x [2 x i32]]* @EA4, metadata !"a(3:a(2:si))"}
-// CHECK: !{{[0-9]+}} = metadata !{[2 x i32]* @GA1, metadata !"a(2:cv:si)"}
-// CHECK: !{{[0-9]+}} = metadata !{void ([2 x i32]*)* @arrayTypeVariable1,
-// CHECK:       metadata !"f{0}(p(a(2:si)))"}
-// CHECK: !{{[0-9]+}} = metadata !{void (void ([2 x i32]*)*)* @arrayTypeVariable2,
-// CHECK:       metadata !"f{0}(p(f{0}(p(a(2:si)))))"}
-// CHECK: !{{[0-9]+}} = metadata !{[3 x [2 x i32]]* @GA2, metadata !"a(3:a(2:si))"}
+// CHECK: !{{[0-9]+}} = !{[0 x i32]* @EA1, !"a(*:cv:si)"}
+// CHECK: !{{[0-9]+}} = !{[2 x i32]* @EA2, !"a(2:si)"}
+// CHECK: !{{[0-9]+}} = !{[0 x [2 x i32]]* @EA3, !"a(*:a(2:si))"}
+// CHECK: !{{[0-9]+}} = !{[3 x [2 x i32]]* @EA4, !"a(3:a(2:si))"}
+// CHECK: !{{[0-9]+}} = !{[2 x i32]* @GA1, !"a(2:cv:si)"}
+// CHECK: !{{[0-9]+}} = !{void ([2 x i32]*)* @arrayTypeVariable1,
+// CHECK:       !"f{0}(p(a(2:si)))"}
+// CHECK: !{{[0-9]+}} = !{void (void ([2 x i32]*)*)* @arrayTypeVariable2,
+// CHECK:       !"f{0}(p(f{0}(p(a(2:si)))))"}
+// CHECK: !{{[0-9]+}} = !{[3 x [2 x i32]]* @GA2, !"a(3:a(2:si))"}
 extern int GA2[3][2];
 extern const volatile int EA1[];
 extern int EA2[2];
@@ -108,16 +108,16 @@
 
 
 // test StructureType
-// CHECK: !{{[0-9]+}} = metadata !{void (%struct.S1*)* @structureType1, metadata
+// CHECK: !{{[0-9]+}} = !{void (%struct.S1*)* @structureType1,
 // CHECK:       !"f{0}(s(S1){m(ps2){p(s(S2){m(ps3){p(s(S3){m(s1){s(S1){}}})}})}})"}
-// CHECK: !{{[0-9]+}} = metadata !{void (%struct.S2*)* @structureType2, metadata
+// CHECK: !{{[0-9]+}} = !{void (%struct.S2*)* @structureType2,
 // CHECK:       !"f{0}(s(S2){m(ps3){p(s(S3){m(s1){s(S1){m(ps2){p(s(S2){})}}}})}})"}
-// CHECK: !{{[0-9]+}} = metadata !{void (%struct.S3*)* @structureType3, metadata
+// CHECK: !{{[0-9]+}} = !{void (%struct.S3*)* @structureType3,
 // CHECK:       !"f{0}(s(S3){m(s1){s(S1){m(ps2){p(s(S2){m(ps3){p(s(S3){})}})}}}})"}
-// CHECK: !{{[0-9]+}} = metadata !{void (%struct.S4*)* @structureType4, metadata
+// CHECK: !{{[0-9]+}} = !{void (%struct.S4*)* @structureType4,
 // CHECK:       !"f{0}(s(S4){m(s1){s(S1){m(ps2){p(s(S2){m(ps3){p(s(S3){m(s1){s(S1){}}})}})}}}})"}
-// CHECK: !{{[0-9]+}} = metadata !{%struct.anon* @StructAnon, metadata !"s(){m(A){si}}"}
-// CHECK: !{{[0-9]+}} = metadata !{i32 (%struct.SB*)* @structureTypeB, metadata
+// CHECK: !{{[0-9]+}} = !{%struct.anon* @StructAnon, !"s(){m(A){si}}"}
+// CHECK: !{{[0-9]+}} = !{i32 (%struct.SB*)* @structureTypeB,
 // CHECK:       !"f{si}(s(SB){m(){b(4:si)},m(){b(2:si)},m(N4){b(4:si)},
 // CHECK:       m(N2){b(2:si)},m(){b(4:ui)},m(){b(4:si)},m(){b(4:c:si)},
 // CHECK:       m(){b(4:c:si)},m(){b(4:cv:si)}})"}
@@ -138,16 +138,16 @@
 
 
 // test UnionType
-// CHECK: !{{[0-9]+}} = metadata !{void (%union.U1*)* @unionType1, metadata
+// CHECK: !{{[0-9]+}} = !{void (%union.U1*)* @unionType1,
 // CHECK:       !"f{0}(u(U1){m(pu2){p(u(U2){m(pu3){p(u(U3){m(u1){u(U1){}}})}})}})"}
-// CHECK: !{{[0-9]+}} = metadata !{void (%union.U2*)* @unionType2, metadata
+// CHECK: !{{[0-9]+}} = !{void (%union.U2*)* @unionType2,
 // CHECK:       !"f{0}(u(U2){m(pu3){p(u(U3){m(u1){u(U1){m(pu2){p(u(U2){})}}}})}})"}
-// CHECK: !{{[0-9]+}} = metadata !{void (%union.U3*)* @unionType3, metadata
+// CHECK: !{{[0-9]+}} = !{void (%union.U3*)* @unionType3,
 // CHECK:       !"f{0}(u(U3){m(u1){u(U1){m(pu2){p(u(U2){m(pu3){p(u(U3){})}})}}}})"}
-// CHECK: !{{[0-9]+}} = metadata !{void (%union.U4*)* @unionType4, metadata
+// CHECK: !{{[0-9]+}} = !{void (%union.U4*)* @unionType4,
 // CHECK:       !"f{0}(u(U4){m(u1){u(U1){m(pu2){p(u(U2){m(pu3){p(u(U3){m(u1){u(U1){}}})}})}}}})"}
-// CHECK: !{{[0-9]+}} = metadata !{%union.anon* @UnionAnon, metadata !"u(){m(A){si}}"}
-// CHECK: !{{[0-9]+}} = metadata !{i32 (%union.UB*)* @unionTypeB, metadata
+// CHECK: !{{[0-9]+}} = !{%union.anon* @UnionAnon, !"u(){m(A){si}}"}
+// CHECK: !{{[0-9]+}} = !{i32 (%union.UB*)* @unionTypeB,
 // CHECK:       !"f{si}(u(UB){m(N2){b(2:si)},m(N4){b(4:si)},m(){b(2:si)},
 // CHECK:       m(){b(4:c:si)},m(){b(4:c:si)},m(){b(4:cv:si)},m(){b(4:si)},
 // CHECK:       m(){b(4:si)},m(){b(4:ui)}})"}
@@ -168,17 +168,17 @@
 
 
 // test EnumType
-// CHECK: !{{[0-9]+}} = metadata !{i32* @EnumAnon, metadata !"e(){m(EA){3}}"}
-// CHECK: !{{[0-9]+}} = metadata !{i32 (i32)* @enumType, metadata
+// CHECK: !{{[0-9]+}} = !{i32* @EnumAnon, !"e(){m(EA){3}}"}
+// CHECK: !{{[0-9]+}} = !{i32 (i32)* @enumType,
 // CHECK:       !"f{si}(e(E){m(A){7},m(B){6},m(C){5},m(D){0}})"}
 enum E {D, C=5, B, A};
 enum {EA=3} EnumAnon = EA;
 int enumType(enum E e) {return EnumAnon;}
 
 
-// CHECK: !{{[0-9]+}} = metadata !{i32 ()* @testReDecl, metadata !"f{si}()"}
-// CHECK: !{{[0-9]+}} = metadata !{[10 x i32]* @After, metadata !"a(10:si)"}
-// CHECK: !{{[0-9]+}} = metadata !{[10 x i32]* @Before, metadata !"a(10:si)"}
+// CHECK: !{{[0-9]+}} = !{i32 ()* @testReDecl, !"f{si}()"}
+// CHECK: !{{[0-9]+}} = !{[10 x i32]* @After, !"a(10:si)"}
+// CHECK: !{{[0-9]+}} = !{[10 x i32]* @Before, !"a(10:si)"}
 extern int After[];
 extern int Before[10];
 int testReDecl() {return After[0] + Before[0];}
diff --git a/test/CodeGenCUDA/host-device-calls-host.cu b/test/CodeGenCUDA/host-device-calls-host.cu
new file mode 100644
index 0000000..8140f61
--- /dev/null
+++ b/test/CodeGenCUDA/host-device-calls-host.cu
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 %s -triple nvptx-unknown-unknown -fcuda-allow-host-calls-from-host-device -fcuda-is-device -Wno-cuda-compat -emit-llvm -o - | FileCheck %s
+
+#include "Inputs/cuda.h"
+
+extern "C"
+void host_function() {}
+
+// CHECK-LABEL: define void @hd_function_a
+extern "C"
+__host__ __device__ void hd_function_a() {
+  // CHECK: call void @host_function
+  host_function();
+}
+
+// CHECK: declare void @host_function
+
+// CHECK-LABEL: define void @hd_function_b
+extern "C"
+__host__ __device__ void hd_function_b(bool b) { if (b) host_function(); }
+
+// CHECK-LABEL: define void @device_function_b
+extern "C"
+__device__ void device_function_b() { hd_function_b(false); }
+
+// CHECK-LABEL: define void @global_function
+extern "C"
+__global__ void global_function() {
+  // CHECK: call void @device_function_b
+  device_function_b();
+}
+
+// CHECK: !{{[0-9]+}} = !{void ()* @global_function, !"kernel", i32 1}
diff --git a/test/CodeGenCUDA/launch-bounds.cu b/test/CodeGenCUDA/launch-bounds.cu
index ed4c2bf..6f4102e 100644
--- a/test/CodeGenCUDA/launch-bounds.cu
+++ b/test/CodeGenCUDA/launch-bounds.cu
@@ -14,8 +14,8 @@
 }
 }
 
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @Kernel1, metadata !"maxntidx", i32 256}
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @Kernel1, metadata !"minctasm", i32 2}
+// CHECK: !{{[0-9]+}} = !{void ()* @Kernel1, !"maxntidx", i32 256}
+// CHECK: !{{[0-9]+}} = !{void ()* @Kernel1, !"minctasm", i32 2}
 
 // Test only max threads per block. Min cta per sm defaults to 0, and
 // CodeGen doesn't output a zero value for minctasm.
@@ -27,4 +27,4 @@
 }
 }
 
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @Kernel2, metadata !"maxntidx", i32 256}
+// CHECK: !{{[0-9]+}} = !{void ()* @Kernel2, !"maxntidx", i32 256}
diff --git a/test/CodeGenCUDA/llvm-used.cu b/test/CodeGenCUDA/llvm-used.cu
new file mode 100644
index 0000000..44666a9
--- /dev/null
+++ b/test/CodeGenCUDA/llvm-used.cu
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -fcuda-is-device -triple nvptx64-unknown-unknown | FileCheck %s
+
+
+// Make sure we emit the proper addrspacecast for llvm.used.  PR22383 exposed an
+// issue where we were generating a bitcast instead of an addrspacecast.
+
+// CHECK: @llvm.used = appending global [1 x i8*] [i8* addrspacecast (i8 addrspace(1)* bitcast ([0 x i32] addrspace(1)* @a to i8 addrspace(1)*) to i8*)], section "llvm.metadata"
+__attribute__((device)) __attribute__((__used__)) int a[] = {};
diff --git a/test/CodeGenCUDA/ptx-kernels.cu b/test/CodeGenCUDA/ptx-kernels.cu
index 11b92b5..658b348 100644
--- a/test/CodeGenCUDA/ptx-kernels.cu
+++ b/test/CodeGenCUDA/ptx-kernels.cu
@@ -13,4 +13,4 @@
   device_function();
 }
 
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @global_function, metadata !"kernel", i32 1}
+// CHECK: !{{[0-9]+}} = !{void ()* @global_function, !"kernel", i32 1}
diff --git a/test/CodeGenCXX/2010-07-23-DeclLoc.cpp b/test/CodeGenCXX/2010-07-23-DeclLoc.cpp
index b1de8f6..56c364c 100644
--- a/test/CodeGenCXX/2010-07-23-DeclLoc.cpp
+++ b/test/CodeGenCXX/2010-07-23-DeclLoc.cpp
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s
 // Require the template function declaration refer to the correct filename.
 // First, locate the function decl in metadata, and pluck out the file handle:
-// CHECK: metadata !"0x2e\00extract_dwarf_data_from_header{{[^"]+}}", metadata [[filehandle:![0-9]+]]
+// CHECK: !"0x2e\00extract_dwarf_data_from_header{{[^"]+}}", [[filehandle:![0-9]+]]
 // Second: Require that filehandle refer to the correct filename:
 // CHECK: [[filehandle]] = {{.*}}decl_should_be_here.hpp"
 typedef long unsigned int __darwin_size_t;
diff --git a/test/CodeGenCXX/PR20038.cpp b/test/CodeGenCXX/PR20038.cpp
index 7275e5a..0936dfc 100644
--- a/test/CodeGenCXX/PR20038.cpp
+++ b/test/CodeGenCXX/PR20038.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple %itanium_abi_triple -g -emit-llvm  %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple %itanium_abi_triple -g -mllvm -no-discriminators -emit-llvm  %s -o - | FileCheck %s
 
 struct C {
   ~C();
@@ -8,9 +8,7 @@
 // CHECK: call {{.*}}, !dbg [[DTOR_CALL2_LOC:![0-9]*]]
 // CHECK: [[FUN1:.*]] = {{.*}}; [ DW_TAG_subprogram ] {{.*}} [def] [fun1]
 // CHECK: [[FUN2:.*]] = {{.*}}; [ DW_TAG_subprogram ] {{.*}} [def] [fun2]
-// CHECK: [[DTOR_CALL1_LOC]] = metadata !{i32 [[@LINE+2]], i32 0, metadata [[FUN1_BLOCK:.*]], null}
-// CHECK: [[FUN1_BLOCK]] = metadata !{metadata !"0xb{{[^,]*}}", {{[^,]*}}, metadata [[FUN1]]}
+// CHECK: [[DTOR_CALL1_LOC]] = !MDLocation(line: [[@LINE+1]], scope: [[FUN1]])
 void fun1() { b && (C(), 1); }
-// CHECK: [[DTOR_CALL2_LOC]] = metadata !{i32 [[@LINE+2]], i32 0, metadata [[FUN2_BLOCK1:.*]], null}
-// CHECK: [[FUN2_BLOCK1]] = metadata !{metadata !"0xb{{[^,]*}}", {{[^,]*}}, metadata [[FUN2]]}
+// CHECK: [[DTOR_CALL2_LOC]] = !MDLocation(line: [[@LINE+1]], scope: [[FUN2]])
 bool fun2() { return (C(), b) && 0; }
diff --git a/test/CodeGenCXX/aarch64-aapcs-zerolength-bitfield.cpp b/test/CodeGenCXX/aarch64-aapcs-zerolength-bitfield.cpp
new file mode 100644
index 0000000..8b403fa
--- /dev/null
+++ b/test/CodeGenCXX/aarch64-aapcs-zerolength-bitfield.cpp
@@ -0,0 +1,249 @@
+// REQUIRES: aarch64-registered-target
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -x c++ -std=c++1z %s -verify
+// expected-no-diagnostics
+
+#include <stddef.h>
+
+struct t1
+{
+  int foo : 1;
+  char : 0;
+  char bar;
+
+};
+static_assert(offsetof(struct t1, bar) == 1);
+static_assert(sizeof(struct t1) == 4);
+
+struct t2
+{
+  int foo : 1;
+  short : 0;
+  char bar;
+};
+static_assert(offsetof(struct t2, bar) == 2);
+static_assert(sizeof(struct t2) == 4);
+
+struct t3
+{
+  int foo : 1;
+  int : 0;
+  char bar;
+};
+static_assert(offsetof(struct t3, bar) == 4);
+static_assert(sizeof(struct t3) == 8);
+
+struct t4
+{
+  int foo : 1;
+  long : 0;
+  char bar;
+};
+static_assert(offsetof(struct t4, bar) == 8);
+static_assert(sizeof(struct t4) == 16);
+
+struct t5
+{
+  int foo : 1;
+  long long : 0;
+  char bar;
+};
+static_assert(offsetof(struct t5, bar) == 8);
+static_assert(sizeof(struct t5) == 16);
+
+struct t6
+{
+  int foo : 1;
+  char : 0;
+  char bar : 1;
+  char bar2;
+};
+static_assert(offsetof(struct t6, bar2) == 2);
+static_assert(sizeof(struct t6) == 4);
+
+struct t7
+{
+  int foo : 1;
+  short : 0;
+  char bar1 : 1;
+  char bar2;
+};
+static_assert(offsetof(struct t7, bar2) == 3);
+static_assert(sizeof(struct t7) == 4);
+
+struct t8
+{
+  int foo : 1;
+  int : 0;
+  char bar1 : 1;
+  char bar2;
+};
+static_assert(offsetof(struct t8, bar2) == 5);
+static_assert(sizeof(struct t8) == 8);
+
+struct t9
+{
+  int foo : 1;
+  long : 0;
+  char bar1 : 1;
+  char bar2;
+};
+static_assert(offsetof(struct t9, bar2) == 9);
+static_assert(sizeof(struct t9) == 16);
+
+struct t10
+{
+  int foo : 1;
+  long long : 0;
+  char bar1 : 1;
+  char bar2;
+};
+static_assert(offsetof(struct t10, bar2) == 9);
+static_assert(sizeof(struct t10) == 16);
+
+struct t11
+{
+  int foo : 1;
+  long long : 0;
+  char : 0;
+  char bar1 : 1;
+  char bar2;
+};
+static_assert(offsetof(struct t11, bar2) == 9);
+static_assert(sizeof(struct t11) == 16);
+
+struct t12
+{
+  int foo : 1;
+  char : 0;
+  long long : 0;
+  char : 0;
+  char bar;
+};
+static_assert(offsetof(struct t12, bar) == 8);
+static_assert(sizeof(struct t12) == 16);
+
+struct t13
+{
+  char foo;
+  long : 0;
+  char bar;
+};
+static_assert(offsetof(struct t13, bar) == 8);
+static_assert(sizeof(struct t13) == 16);
+
+struct t14
+{
+  char foo1;
+  int : 0;
+  char foo2 : 1;
+  short foo3 : 16;
+  char : 0;
+  short foo4 : 16;
+  char bar1;
+  int : 0;
+  char bar2;
+};
+static_assert(offsetof(struct t14, bar1) == 10);
+static_assert(offsetof(struct t14, bar2) == 12);
+static_assert(sizeof(struct t14) == 16);
+
+struct t15
+{
+  char foo;
+  char : 0;
+  int : 0;
+  char bar;
+  long : 0;
+  char : 0;
+};
+static_assert(offsetof(struct t15, bar) == 4);
+static_assert(sizeof(struct t15) == 8);
+
+struct t16
+{
+  long : 0;
+  char bar;
+};
+static_assert(offsetof(struct t16, bar) == 0);
+static_assert(sizeof(struct t16) == 8);
+
+struct t17
+{
+  char foo;
+  long : 0;
+  long : 0;
+  char : 0;
+  char bar;
+};
+static_assert(offsetof(struct t17, bar) == 8);
+static_assert(sizeof(struct t17) == 16);
+
+struct t18
+{
+  long : 0;
+  long : 0;
+  char : 0;
+};
+static_assert(sizeof(struct t18) == 8);
+
+struct t19
+{
+  char foo1;
+  long foo2 : 1;
+  char : 0;
+  long foo3 : 32;
+  char bar;
+};
+static_assert(offsetof(struct t19, bar) == 6);
+static_assert(sizeof(struct t19) == 8);
+
+struct t20
+{
+  short : 0;
+  int foo : 1;
+  long : 0;
+  char bar;
+};
+static_assert(offsetof(struct t20, bar) == 8);
+static_assert(sizeof(struct t20) == 16);
+
+struct t21
+{
+  short : 0;
+  int foo1 : 1;
+  char : 0;
+  int foo2 : 16;
+  long : 0;
+  char bar1;
+  int bar2;
+  long bar3;
+  char foo3 : 8;
+  char : 0;
+  long : 0;
+  int foo4 : 32;
+  short foo5: 1;
+  long bar4;
+  short foo6: 16;
+  short foo7: 16;
+  short foo8: 16;
+};
+static_assert(offsetof(struct t21, bar1) == 8);
+static_assert(offsetof(struct t21, bar2) == 12);
+static_assert(offsetof(struct t21, bar3) == 16);
+static_assert(offsetof(struct t21, bar4) == 40);
+static_assert(sizeof(struct t21) == 56);
+
+// The rules also apply to anonymous bitfields with non-zero length.
+struct t22
+{
+  char foo;
+  short :2;
+  char bar;
+};
+static_assert(alignof(struct t22) == 2);
+static_assert(offsetof(struct t22, bar) == 2);
+
+int main() {
+  return 0;
+}
+
diff --git a/test/CodeGenCXX/apple-kext-indirect-call-2.C b/test/CodeGenCXX/apple-kext-indirect-call-2.cpp
similarity index 67%
rename from test/CodeGenCXX/apple-kext-indirect-call-2.C
rename to test/CodeGenCXX/apple-kext-indirect-call-2.cpp
index 7e25200..68ecaf0 100644
--- a/test/CodeGenCXX/apple-kext-indirect-call-2.C
+++ b/test/CodeGenCXX/apple-kext-indirect-call-2.cpp
@@ -1,9 +1,9 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fapple-kext -fno-rtti -emit-llvm -o - %s | FileCheck %s
 
 // CHECK: @_ZTV1A = unnamed_addr constant [4 x i8*] [i8* null, i8* null, i8* bitcast (i8* (%struct.A*)* @_ZNK1A3abcEv to i8*), i8* null]
-// CHECK: @_ZTV4Base = unnamed_addr constant [4 x i8*] [i8* null, i8* null, i8* bitcast (i8* (%struct.A*)* @_ZNK4Base3abcEv to i8*), i8* null]
-// CHECK: @_ZTV8Derived2 = unnamed_addr constant [5 x i8*] [i8* null, i8* null, i8* null, i8* bitcast (i8* (%struct.A*)* @_ZNK8Derived23efgEv to i8*), i8* null]
-// CHECK: @_ZTV2D2 = unnamed_addr constant [5 x i8*] [i8* null, i8* null, i8* null, i8* bitcast (i8* (%struct.A*)* @_ZNK2D23abcEv to i8*), i8* null]
+// CHECK: @_ZTV4Base = unnamed_addr constant [4 x i8*] [i8* null, i8* null, i8* bitcast (i8* (%struct.Base*)* @_ZNK4Base3abcEv to i8*), i8* null]
+// CHECK: @_ZTV8Derived2 = unnamed_addr constant [5 x i8*] [i8* null, i8* null, i8* null, i8* bitcast (i8* (%struct.Derived2*)* @_ZNK8Derived23efgEv to i8*), i8* null]
+// CHECK: @_ZTV2D2 = unnamed_addr constant [5 x i8*] [i8* null, i8* null, i8* null, i8* bitcast (i8* (%struct.D2*)* @_ZNK2D23abcEv to i8*), i8* null]
 
 struct A {
   virtual const char* abc(void) const;
@@ -33,7 +33,7 @@
 };
 
 void FUNC1(Derived* p) {
-// CHECK: [[U1:%.*]] = load i8* (%struct.A*)** getelementptr inbounds (i8* (%struct.A*)** bitcast ([4 x i8*]* @_ZTV4Base to i8* (%struct.A*)**), i64 2)
+// CHECK: [[U1:%.*]] = load i8* (%struct.Base*)** getelementptr inbounds (i8* (%struct.Base*)** bitcast ([4 x i8*]* @_ZTV4Base to i8* (%struct.Base*)**), i64 2)
 // CHECK-NEXT:  [[U2:%.*]] = call i8* [[U1]]
   char* c = p->Base::abc();
 }
@@ -49,7 +49,7 @@
 char* Derived2::efg(void) const { return 0; }
 
 void FUNC2(Derived2* p) {
-// CHECK: [[V1:%.*]] = load i8* (%struct.A*)** getelementptr inbounds (i8* (%struct.A*)** bitcast ([5 x i8*]* @_ZTV8Derived2 to i8* (%struct.A*)**), i64 3)
+// CHECK: [[V1:%.*]] = load i8* (%struct.Derived2*)** getelementptr inbounds (i8* (%struct.Derived2*)** bitcast ([5 x i8*]* @_ZTV8Derived2 to i8* (%struct.Derived2*)**), i64 3)
 // CHECK-NEXT:  [[V2:%.*]] = call i8* [[V1]]
   char* c = p->Derived2::efg();
 }
@@ -70,7 +70,7 @@
 char* D2::abc(void) const { return 0; }
 
 void FUNC3(Sub* p) {
-// CHECK: [[W1:%.*]] = load i8* (%struct.A*)** getelementptr inbounds (i8* (%struct.A*)** bitcast ([5 x i8*]* @_ZTV2D2 to i8* (%struct.A*)**), i64 3)
+// CHECK: [[W1:%.*]] = load i8* (%struct.D2*)** getelementptr inbounds (i8* (%struct.D2*)** bitcast ([5 x i8*]* @_ZTV2D2 to i8* (%struct.D2*)**), i64 3)
 // CHECK-NEXT:  [[W2:%.*]] = call i8* [[W1]]
   char* c = p->D2::abc();
 }
diff --git a/test/CodeGenCXX/apple-kext-indirect-call.C b/test/CodeGenCXX/apple-kext-indirect-call.C
deleted file mode 100644
index 2dbb0b8..0000000
--- a/test/CodeGenCXX/apple-kext-indirect-call.C
+++ /dev/null
@@ -1,14 +0,0 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fapple-kext -emit-llvm -o - %s | FileCheck %s
-
-struct Base { 
-  virtual void abc(void) const; 
-};
-
-void Base::abc(void) const {}
-
-void FUNC(Base* p) {
-  p->Base::abc();
-}
-
-// CHECK: getelementptr inbounds (void (%struct.Base*)** bitcast ([3 x i8*]* @_ZTV4Base to void (%struct.Base*)**), i64 2)
-// CHECK-NOT: call void @_ZNK4Base3abcEv
diff --git a/test/CodeGenCXX/apple-kext-indirect-call.cpp b/test/CodeGenCXX/apple-kext-indirect-call.cpp
new file mode 100644
index 0000000..2717a9d
--- /dev/null
+++ b/test/CodeGenCXX/apple-kext-indirect-call.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fapple-kext -emit-llvm -o - %s | FileCheck %s
+
+// CHECK: @_ZTV5TemplIiE = internal unnamed_addr constant [5 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTI5TemplIiE to i8*), i8* bitcast (void (%struct.Templ*)* @_ZN5TemplIiE1fEv to i8*), i8* bitcast (void (%struct.Templ*)* @_ZN5TemplIiE1gEv to i8*), i8* null]
+
+struct Base { 
+  virtual void abc(void) const; 
+};
+
+void Base::abc(void) const {}
+
+void FUNC(Base* p) {
+  p->Base::abc();
+}
+
+// CHECK: getelementptr inbounds (void (%struct.Base*)** bitcast ([4 x i8*]* @_ZTV4Base to void (%struct.Base*)**), i64 2)
+// CHECK-NOT: call void @_ZNK4Base3abcEv
+
+template<class T>
+struct Templ {
+  virtual void f() {}
+  virtual void g() {}
+};
+template<class T>
+struct SubTempl : public Templ<T> {
+  virtual void f() {} // override
+  virtual void g() {} // override
+};
+
+void f(SubTempl<int>* t) {
+  // Qualified calls go through the (qualified) vtable in apple-kext mode.
+  // Since t's this pointer points to SubTempl's vtable, the call needs
+  // to load Templ<int>'s vtable.  Hence, Templ<int>::g needs to be
+  // instantiated in this TU, for it's referenced by the vtable.
+  // (This happens only in apple-kext mode; elsewhere virtual calls can always
+  // use the vtable pointer off this instead of having to load the vtable
+  // symbol.)
+  t->Templ::f();
+}
+
+// CHECK: getelementptr inbounds (void (%struct.Templ*)** bitcast ([5 x i8*]* @_ZTV5TemplIiE to void (%struct.Templ*)**), i64 2)
+// CHECK: define internal void @_ZN5TemplIiE1fEv(%struct.Templ* %this)
+// CHECK: define internal void @_ZN5TemplIiE1gEv(%struct.Templ* %this)
diff --git a/test/CodeGenCXX/apple-kext-indirect-virtual-dtor-call.cpp b/test/CodeGenCXX/apple-kext-indirect-virtual-dtor-call.cpp
index 7ac5b58..e5d85c1 100644
--- a/test/CodeGenCXX/apple-kext-indirect-virtual-dtor-call.cpp
+++ b/test/CodeGenCXX/apple-kext-indirect-virtual-dtor-call.cpp
@@ -1,12 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fapple-kext -fno-rtti -emit-llvm -o - %s | FileCheck %s
 
-// CHECK-LABEL: define void @_ZN2B1D0Ev
-// CHECK: [[T1:%.*]] = load void (%struct.B1*)** getelementptr inbounds (void (%struct.B1*)** bitcast ([5 x i8*]* @_ZTV2B1 to void (%struct.B1*)**), i64 2)
-// CHECK-NEXT: call void [[T1]](%struct.B1* [[T2:%.*]])
-// CHECK-LABEL: define void @_Z6DELETEP2B1
-// CHECK: [[T3:%.*]] = load void (%struct.B1*)** getelementptr inbounds (void (%struct.B1*)** bitcast ([5 x i8*]* @_ZTV2B1 to void (%struct.B1*)**), i64 2)
-// CHECK-NEXT:  call void [[T3]](%struct.B1* [[T4:%.*]])
-
+// CHECK: @_ZTV5TemplIiE = internal unnamed_addr constant [7 x i8*] [i8* null, i8* null, i8* bitcast (void (%struct.Templ*)* @_ZN5TemplIiED1Ev to i8*), i8* bitcast (void (%struct.Templ*)* @_ZN5TemplIiED0Ev to i8*), i8* bitcast (void (%struct.Templ*)* @_ZN5TemplIiE1fEv to i8*), i8* bitcast (void (%struct.Templ*)* @_ZN5TemplIiE1gEv to i8*), i8* null]
 
 struct B1 { 
   virtual ~B1(); 
@@ -17,3 +11,38 @@
 void DELETE(B1 *pb1) {
   pb1->B1::~B1();
 }
+// CHECK-LABEL: define void @_ZN2B1D0Ev
+// CHECK: [[T1:%.*]] = load void (%struct.B1*)** getelementptr inbounds (void (%struct.B1*)** bitcast ([5 x i8*]* @_ZTV2B1 to void (%struct.B1*)**), i64 2)
+// CHECK-NEXT: call void [[T1]](%struct.B1* [[T2:%.*]])
+// CHECK-LABEL: define void @_Z6DELETEP2B1
+// CHECK: [[T3:%.*]] = load void (%struct.B1*)** getelementptr inbounds (void (%struct.B1*)** bitcast ([5 x i8*]* @_ZTV2B1 to void (%struct.B1*)**), i64 2)
+// CHECK-NEXT:  call void [[T3]](%struct.B1* [[T4:%.*]])
+
+template<class T>
+struct Templ {
+  virtual ~Templ(); // Out-of-line so that the destructor doesn't cause a vtable
+  virtual void f() {}
+  virtual void g() {}
+};
+template<class T>
+struct SubTempl : public Templ<T> {
+  virtual ~SubTempl() {} // override
+  virtual void f() {} // override
+  virtual void g() {} // override
+};
+
+void f(SubTempl<int>* t) {
+  // Qualified calls go through the (qualified) vtable in apple-kext mode.
+  // Since t's this pointer points to SubTempl's vtable, the call needs
+  // to load Templ<int>'s vtable.  Hence, Templ<int>::g needs to be
+  // instantiated in this TU, for it's referenced by the vtable.
+  // (This happens only in apple-kext mode; elsewhere virtual calls can always
+  // use the vtable pointer off this instead of having to load the vtable
+  // symbol.)
+  t->Templ::~Templ();
+}
+
+// CHECK: getelementptr inbounds (void (%struct.Templ*)** bitcast ([7 x i8*]* @_ZTV5TemplIiE to void (%struct.Templ*)**), i64 2)
+// CHECK: declare void @_ZN5TemplIiED0Ev(%struct.Templ*)
+// CHECK: define internal void @_ZN5TemplIiE1fEv(%struct.Templ* %this)
+// CHECK: define internal void @_ZN5TemplIiE1gEv(%struct.Templ* %this)
diff --git a/test/CodeGenCXX/apple-kext-linkage.C b/test/CodeGenCXX/apple-kext-linkage.cpp
similarity index 100%
rename from test/CodeGenCXX/apple-kext-linkage.C
rename to test/CodeGenCXX/apple-kext-linkage.cpp
diff --git a/test/CodeGenCXX/apple-kext-no-staticinit-section.C b/test/CodeGenCXX/apple-kext-no-staticinit-section.cpp
similarity index 100%
rename from test/CodeGenCXX/apple-kext-no-staticinit-section.C
rename to test/CodeGenCXX/apple-kext-no-staticinit-section.cpp
diff --git a/test/CodeGenCXX/atomicinit.cpp b/test/CodeGenCXX/atomicinit.cpp
index 91b990b..982396e 100644
--- a/test/CodeGenCXX/atomicinit.cpp
+++ b/test/CodeGenCXX/atomicinit.cpp
@@ -1,5 +1,9 @@
 // RUN: %clang_cc1 %s -emit-llvm -O1 -o - -triple=i686-apple-darwin9 -std=c++11 | FileCheck %s
 
+// CHECK-DAG: @PR22043 = global i32 0, align 4
+typedef _Atomic(int) AtomicInt;
+AtomicInt PR22043 = AtomicInt();
+
 // CHECK-DAG: @_ZN7PR180978constant1aE = global { i16, i8 } { i16 1, i8 6 }, align 4
 // CHECK-DAG: @_ZN7PR180978constant1bE = global { i16, i8 } { i16 2, i8 6 }, align 4
 // CHECK-DAG: @_ZN7PR180978constant1cE = global { i16, i8 } { i16 3, i8 6 }, align 4
diff --git a/test/CodeGenCXX/blocks.cpp b/test/CodeGenCXX/blocks.cpp
index 6b11083..c9a56c8 100644
--- a/test/CodeGenCXX/blocks.cpp
+++ b/test/CodeGenCXX/blocks.cpp
@@ -122,7 +122,7 @@
   // CHECK-LABEL: define internal void @___ZN5test44testEv_block_invoke
   // CHECK: [[TMP:%.*]] = alloca [[A:%.*]], align 1
   // CHECK-NEXT: store i8* [[BLOCKDESC:%.*]], i8** {{.*}}, align 8
-  // CHECK-NEXT: load i8*
+  // CHECK-NEXT: load i8**
   // CHECK-NEXT: bitcast i8* [[BLOCKDESC]] to <{ i8*, i32, i32, i8*, %struct.__block_descriptor* }>*
   // CHECK:      call void @_ZN5test41AC1Ev([[A]]* [[TMP]])
   // CHECK-NEXT: call void @_ZN5test43fooENS_1AE([[A]]* [[TMP]])
diff --git a/test/CodeGenCXX/call-with-static-chain.cpp b/test/CodeGenCXX/call-with-static-chain.cpp
new file mode 100644
index 0000000..7cf9291
--- /dev/null
+++ b/test/CodeGenCXX/call-with-static-chain.cpp
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -o - %s | FileCheck -check-prefix=CHECK32 %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | FileCheck -check-prefix=CHECK64 %s
+
+struct A {
+  long x, y;
+};
+
+struct B {
+  long x, y, z, w;
+};
+
+extern "C" {
+
+int f1(A, A, A, A);
+B f2(void);
+_Complex float f3(void);
+A &f4();
+
+}
+
+void test() {
+  A a;
+
+  // CHECK32: call i32 bitcast (i32 (%struct.A*, %struct.A*, %struct.A*, %struct.A*)* @f1 to i32 (i8*, %struct.A*, %struct.A*, %struct.A*, %struct.A*)*)(i8* nest bitcast (i32 (%struct.A*, %struct.A*, %struct.A*, %struct.A*)* @f1 to i8*)
+  // CHECK64: call i32 bitcast (i32 (i64, i64, i64, i64, i64, i64, %struct.A*)* @f1 to i32 (i8*, i64, i64, i64, i64, i64, i64, %struct.A*)*)(i8* nest bitcast (i32 (i64, i64, i64, i64, i64, i64, %struct.A*)* @f1 to i8*)
+  __builtin_call_with_static_chain(f1(a, a, a, a), f1);
+
+  // CHECK32: call void bitcast (void (%struct.B*)* @f2 to void (%struct.B*, i8*)*)(%struct.B* sret %{{[0-9a-z]+}}, i8* nest bitcast (void (%struct.B*)* @f2 to i8*))
+  // CHECK64: call void bitcast (void (%struct.B*)* @f2 to void (%struct.B*, i8*)*)(%struct.B* sret %{{[0-9a-z]+}}, i8* nest bitcast (void (%struct.B*)* @f2 to i8*))
+  __builtin_call_with_static_chain(f2(), f2);
+
+  // CHECK32: call i64 bitcast (i64 ()* @f3 to i64 (i8*)*)(i8* nest bitcast (i64 ()* @f3 to i8*))
+  // CHECK64: call <2 x float> bitcast (<2 x float> ()* @f3 to <2 x float> (i8*)*)(i8* nest bitcast (<2 x float> ()* @f3 to i8*))
+  __builtin_call_with_static_chain(f3(), f3);
+
+  // CHECK32: call dereferenceable(8) %struct.A* bitcast (%struct.A* ()* @f4 to %struct.A* (i8*)*)(i8* nest bitcast (%struct.A* ()* @f4 to i8*))
+  // CHECK64: call dereferenceable(16) %struct.A* bitcast (%struct.A* ()* @f4 to %struct.A* (i8*)*)(i8* nest bitcast (%struct.A* ()* @f4 to i8*))
+  __builtin_call_with_static_chain(f4(), f4);
+}
diff --git a/test/CodeGenCXX/catch-undef-behavior.cpp b/test/CodeGenCXX/catch-undef-behavior.cpp
index aa65438..35b7498 100644
--- a/test/CodeGenCXX/catch-undef-behavior.cpp
+++ b/test/CodeGenCXX/catch-undef-behavior.cpp
@@ -1,6 +1,8 @@
-// RUN: %clang_cc1 -std=c++11 -fsanitize=signed-integer-overflow,integer-divide-by-zero,float-divide-by-zero,shift,unreachable,return,vla-bound,alignment,null,vptr,object-size,float-cast-overflow,bool,enum,array-bounds,function -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
-// RUN: %clang_cc1 -std=c++11 -fsanitize=vptr,address -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-ASAN
-// RUN: %clang_cc1 -std=c++11 -fsanitize=vptr -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=DOWNCAST-NULL
+// RUN: %clang_cc1 -std=c++11 -fsanitize=signed-integer-overflow,integer-divide-by-zero,float-divide-by-zero,shift,unreachable,return,vla-bound,alignment,null,vptr,object-size,float-cast-overflow,bool,enum,array-bounds,function -fsanitize-recover=signed-integer-overflow,integer-divide-by-zero,float-divide-by-zero,shift,vla-bound,alignment,null,vptr,object-size,float-cast-overflow,bool,enum,array-bounds,function -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -fsanitize=vptr,address -fsanitize-recover=vptr,address -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK-ASAN
+// RUN: %clang_cc1 -std=c++11 -fsanitize=vptr -fsanitize-recover=vptr -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=DOWNCAST-NULL
+// RUN: %clang_cc1 -std=c++11 -fsanitize=function -emit-llvm %s -o - -triple x86_64-linux-gnux32 | FileCheck %s --check-prefix=CHECK-X32
+// RUN: %clang_cc1 -std=c++11 -fsanitize=function -emit-llvm %s -o - -triple i386-linux-gnu | FileCheck %s --check-prefix=CHECK-X86
 
 struct S {
   double d;
@@ -389,7 +391,9 @@
   // CHECK-NEXT: br i1 [[AND]]
 }
 
-// CHECK-LABEL: @_Z22indirect_function_callPFviE({{.*}} prefix <{ i32, i8* }> <{ i32 1413876459, i8* bitcast ({ i8*, i8* }* @_ZTIFvPFviEE to i8*) }>
+// CHECK-LABEL: @_Z22indirect_function_callPFviE({{.*}} prologue <{ i32, i8* }> <{ i32 1413876459, i8* bitcast ({ i8*, i8* }* @_ZTIFvPFviEE to i8*) }>
+// CHECK-X32: @_Z22indirect_function_callPFviE({{.*}} prologue <{ i32, i8* }> <{ i32 1413875435, i8* bitcast ({ i8*, i8* }* @_ZTIFvPFviEE to i8*) }>
+// CHECK-X86: @_Z22indirect_function_callPFviE({{.*}} prologue <{ i32, i8* }> <{ i32 1413875435, i8* bitcast ({ i8*, i8* }* @_ZTIFvPFviEE to i8*) }>
 void indirect_function_call(void (*p)(int)) {
   // CHECK: [[PTR:%[0-9]*]] = bitcast void (i32)* {{.*}} to <{ i32, i8* }>*
 
@@ -446,11 +450,11 @@
   // CHECK-NOT: call {{.*}} @__ubsan_handle_load_invalid_value
   // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S4aSEOS0_
   // CHECK-NOT: call {{.*}} @__ubsan_handle_load_invalid_value
-  // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S5C2ERKS0_
+  // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S1C2ERKS0_
   // CHECK-NOT: call {{.*}} __ubsan_handle_load_invalid_value
   // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S2C2ERKS0_
   // CHECK: __ubsan_handle_load_invalid_value
-  // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S1C2ERKS0_
+  // CHECK-LABEL: define {{.*}} @_ZN23CopyValueRepresentation2S5C2ERKS0_
   // CHECK-NOT: call {{.*}} __ubsan_handle_load_invalid_value
 
   struct CustomCopy { CustomCopy(); CustomCopy(const CustomCopy&); };
diff --git a/test/CodeGenCXX/cfi-vptr.cpp b/test/CodeGenCXX/cfi-vptr.cpp
new file mode 100644
index 0000000..545f22c
--- /dev/null
+++ b/test/CodeGenCXX/cfi-vptr.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -fsanitize=cfi-vptr -emit-llvm -o - %s | FileCheck %s
+
+struct A {
+  A();
+  virtual void f();
+};
+
+struct B : virtual A {
+  B();
+};
+
+struct C : virtual A {
+  C();
+};
+
+namespace {
+
+struct D : B, C {
+  D();
+  virtual void f();
+};
+
+}
+
+A::A() {}
+B::B() {}
+C::C() {}
+D::D() {}
+
+void A::f() {
+}
+
+void D::f() {
+}
+
+// CHECK: define void @_Z2afP1A
+void af(A *a) {
+  // CHECK: [[P:%[^ ]*]] = call i1 @llvm.bitset.test(i8* {{%[^ ]*}}, metadata !"1A")
+  // CHECK-NEXT: br i1 [[P]], label %[[CONTBB:[^ ]*]], label %[[TRAPBB:[^ ]*]]
+
+  // CHECK: [[TRAPBB]]
+  // CHECK-NEXT: call void @llvm.trap()
+  // CHECK-NEXT: unreachable
+
+  // CHECK: [[CONTBB]]
+  // CHECK: call void %
+  a->f();
+}
+
+// CHECK: define internal void @_Z2dfPN12_GLOBAL__N_11DE
+void df(D *d) {
+  // CHECK: {{%[^ ]*}} = call i1 @llvm.bitset.test(i8* {{%[^ ]*}}, metadata !"[{{.*}}cfi-vptr.cpp]N12_GLOBAL__N_11DE")
+  d->f();
+}
+
+D d;
+
+void foo() {
+  df(&d);
+}
+
+// CHECK-DAG: !{!"1A", [3 x i8*]* @_ZTV1A, i64 16}
+// CHECK-DAG: !{!"1A", [5 x i8*]* @_ZTCN12_GLOBAL__N_11DE0_1B, i64 32}
+// CHECK-DAG: !{!"1B", [5 x i8*]* @_ZTCN12_GLOBAL__N_11DE0_1B, i64 32}
+// CHECK-DAG: !{!"1A", [9 x i8*]* @_ZTCN12_GLOBAL__N_11DE8_1C, i64 64}
+// CHECK-DAG: !{!"1C", [9 x i8*]* @_ZTCN12_GLOBAL__N_11DE8_1C, i64 32}
+// CHECK-DAG: !{!"1A", [10 x i8*]* @_ZTVN12_GLOBAL__N_11DE, i64 32}
+// CHECK-DAG: !{!"1B", [10 x i8*]* @_ZTVN12_GLOBAL__N_11DE, i64 32}
+// CHECK-DAG: !{!"1C", [10 x i8*]* @_ZTVN12_GLOBAL__N_11DE, i64 72}
+// CHECK-DAG: !{!"[{{.*}}cfi-vptr.cpp]N12_GLOBAL__N_11DE", [10 x i8*]* @_ZTVN12_GLOBAL__N_11DE, i64 32}
+// CHECK-DAG: !{!"1A", [5 x i8*]* @_ZTV1B, i64 32}
+// CHECK-DAG: !{!"1B", [5 x i8*]* @_ZTV1B, i64 32}
+// CHECK-DAG: !{!"1A", [5 x i8*]* @_ZTV1C, i64 32}
+// CHECK-DAG: !{!"1C", [5 x i8*]* @_ZTV1C, i64 32}
diff --git a/test/CodeGenCXX/compound-literals.cpp b/test/CodeGenCXX/compound-literals.cpp
index f1d8802..e771093 100644
--- a/test/CodeGenCXX/compound-literals.cpp
+++ b/test/CodeGenCXX/compound-literals.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple armv7-none-eabi -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -triple armv7-none-eabi -emit-llvm -o - %s | FileCheck %s
 
 struct X {
   X();
@@ -42,3 +42,16 @@
 int *p = (Z){ {1, 2, 3} }.i;
 // CHECK: define {{.*}}__cxx_global_var_init()
 // CHECK: store i32* getelementptr inbounds (%struct.Z* @.compoundliteral, i32 0, i32 0, i32 0), i32** @p
+
+
+int *PR21912_1 = (int []){};
+// CHECK-LABEL: define {{.*}}__cxx_global_var_init1()
+// CHECK: store i32* getelementptr inbounds ([0 x i32]* @.compoundliteral2, i32 0, i32 0), i32** @PR21912_1
+
+union PR21912Ty {
+  long long l;
+  double d;
+};
+union PR21912Ty *PR21912_2 = (union PR21912Ty[]){{.d = 2.0}, {.l = 3}};
+// CHECK-LABEL: define {{.*}}__cxx_global_var_init3()
+// CHECK: store %union.PR21912Ty* getelementptr inbounds ([2 x %union.PR21912Ty]* bitcast (<{ { double }, %union.PR21912Ty }>* @.compoundliteral4 to [2 x %union.PR21912Ty]*), i32 0, i32 0), %union.PR21912Ty** @PR21912_2
diff --git a/test/CodeGenCXX/const-init-cxx11.cpp b/test/CodeGenCXX/const-init-cxx11.cpp
index f671e0a..2992488 100644
--- a/test/CodeGenCXX/const-init-cxx11.cpp
+++ b/test/CodeGenCXX/const-init-cxx11.cpp
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -verify -triple x86_64-apple-darwin -emit-llvm -o - %s -std=c++11 | FileCheck %s
+// RUN: %clang_cc1 -w -triple x86_64-elf-gnu -emit-llvm -o - %s -std=c++11 | FileCheck %s
 
 // FIXME: The padding in all these objects should be zero-initialized.
 namespace StructUnion {
@@ -226,30 +226,30 @@
   };
 
   // This creates a non-const temporary and binds a reference to it.
-  // CHECK: @[[TEMP:.*]] = private global {{.*}} { i32 5 }, align 4
+  // CHECK: @[[TEMP:.*]] = internal global {{.*}} { i32 5 }, align 4
   // CHECK: @_ZN16LiteralReference3litE = constant {{.*}} @[[TEMP]], align 8
   const Lit &lit = Lit();
 
   // This creates a const temporary as part of the reference initialization.
-  // CHECK: @[[TEMP:.*]] = private constant {{.*}} { i32 5 }, align 4
+  // CHECK: @[[TEMP:.*]] = internal constant {{.*}} { i32 5 }, align 4
   // CHECK: @_ZN16LiteralReference4lit2E = constant {{.*}} @[[TEMP]], align 8
   const Lit &lit2 = {};
 
   struct A { int &&r1; const int &&r2; };
   struct B { A &&a1; const A &&a2; };
   B b = { { 0, 1 }, { 2, 3 } };
-  // CHECK: @[[TEMP0:.*]] = private global i32 0, align 4
-  // CHECK: @[[TEMP1:.*]] = private constant i32 1, align 4
-  // CHECK: @[[TEMPA1:.*]] = private global {{.*}} { i32* @[[TEMP0]], i32* @[[TEMP1]] }, align 8
-  // CHECK: @[[TEMP2:.*]] = private global i32 2, align 4
-  // CHECK: @[[TEMP3:.*]] = private constant i32 3, align 4
-  // CHECK: @[[TEMPA2:.*]] = private constant {{.*}} { i32* @[[TEMP2]], i32* @[[TEMP3]] }, align 8
+  // CHECK: @[[TEMP0:.*]] = internal global i32 0, align 4
+  // CHECK: @[[TEMP1:.*]] = internal constant i32 1, align 4
+  // CHECK: @[[TEMPA1:.*]] = internal global {{.*}} { i32* @[[TEMP0]], i32* @[[TEMP1]] }, align 8
+  // CHECK: @[[TEMP2:.*]] = internal global i32 2, align 4
+  // CHECK: @[[TEMP3:.*]] = internal constant i32 3, align 4
+  // CHECK: @[[TEMPA2:.*]] = internal constant {{.*}} { i32* @[[TEMP2]], i32* @[[TEMP3]] }, align 8
   // CHECK: @_ZN16LiteralReference1bE = global {{.*}} { {{.*}}* @[[TEMPA1]], {{.*}}* @[[TEMPA2]] }, align 8
 
   struct Subobj {
     int a, b, c;
   };
-  // CHECK: @[[TEMP:.*]] = private global {{.*}} { i32 1, i32 2, i32 3 }, align 4
+  // CHECK: @[[TEMP:.*]] = internal global {{.*}} { i32 1, i32 2, i32 3 }, align 4
   // CHECK: @_ZN16LiteralReference2soE = constant {{.*}} (i8* getelementptr {{.*}} @[[TEMP]]{{.*}}, i64 4)
   constexpr int &&so = Subobj{ 1, 2, 3 }.b;
 
@@ -258,11 +258,11 @@
     constexpr Derived() : Dummy{200}, Subobj{4, 5, 6} {}
   };
   using ConstDerived = const Derived;
-  // CHECK: @[[TEMPCOMMA:.*]] = private constant {{.*}} { i32 200, i32 4, i32 5, i32 6 }
+  // CHECK: @[[TEMPCOMMA:.*]] = internal constant {{.*}} { i32 200, i32 4, i32 5, i32 6 }
   // CHECK: @_ZN16LiteralReference5commaE = constant {{.*}} getelementptr {{.*}} @[[TEMPCOMMA]]{{.*}}, i64 8)
   constexpr const int &comma = (1, (2, ConstDerived{}).b);
 
-  // CHECK: @[[TEMPDERIVED:.*]] = private global {{.*}} { i32 200, i32 4, i32 5, i32 6 }
+  // CHECK: @[[TEMPDERIVED:.*]] = internal global {{.*}} { i32 200, i32 4, i32 5, i32 6 }
   // CHECK: @_ZN16LiteralReference4baseE = constant {{.*}} getelementptr {{.*}} @[[TEMPDERIVED]]{{.*}}, i64 4)
   constexpr Subobj &&base = Derived{};
 
@@ -343,7 +343,6 @@
     constexpr E() : B(3), c{'b','y','e'} {}
     char c[3];
   };
-
   // CHECK: @_ZN14VirtualMembers1eE = global { i8**, double, i32, i8**, double, [5 x i8], i16, i8**, double, [5 x i8], [3 x i8] } { i8** getelementptr inbounds ([11 x i8*]* @_ZTVN14VirtualMembers1EE, i64 0, i64 2), double 1.000000e+00, i32 64, i8** getelementptr inbounds ([11 x i8*]* @_ZTVN14VirtualMembers1EE, i64 0, i64 5), double 2.000000e+00, [5 x i8] c"hello", i16 5, i8** getelementptr inbounds ([11 x i8*]* @_ZTVN14VirtualMembers1EE, i64 0, i64 9), double 3.000000e+00, [5 x i8] c"world", [3 x i8] c"bye" }
   E e;
 
@@ -352,6 +351,16 @@
   };
   // CHECK: @_ZN14VirtualMembersL13sGlobalMemoryE = internal global { i8** } { i8** getelementptr inbounds ([3 x i8*]* @_ZTVN14VirtualMembers12nsMemoryImplE, i64 0, i64 2) }
   static nsMemoryImpl sGlobalMemory;
+
+  template<class T>
+  struct TemplateClass {
+    constexpr TemplateClass() : t{42} {}
+    virtual void templateMethod() {}
+
+    T t;
+  };
+  // CHECK: @_ZN14VirtualMembers1tE = global { i8**, i32 } { i8** getelementptr inbounds ([3 x i8*]* @_ZTVN14VirtualMembers13TemplateClassIiEE, i64 0, i64 2), i32 42 }
+  TemplateClass<int> t;
 }
 
 namespace PR13273 {
@@ -371,10 +380,10 @@
 namespace ArrayTemporary {
   struct A { const int (&x)[3]; };
   struct B { const A (&x)[2]; };
-  // CHECK: @[[A1:_ZGRN14ArrayTemporary1bE.*]] = private constant [3 x i32] [i32 1, i32 2, i32 3]
-  // CHECK: @[[A2:_ZGRN14ArrayTemporary1bE.*]] = private constant [3 x i32] [i32 4, i32 5, i32 6]
-  // CHECK: @[[ARR:_ZGRN14ArrayTemporary1bE.*]] = private constant [2 x {{.*}}] [{{.*}} { [3 x i32]* @[[A1]] }, {{.*}} { [3 x i32]* @[[A2]] }]
-  // CHECK: @[[B:_ZGRN14ArrayTemporary1bE.*]] = private global {{.*}} { [2 x {{.*}}]* @[[ARR]] }
+  // CHECK: @[[A1:_ZGRN14ArrayTemporary1bE.*]] = internal constant [3 x i32] [i32 1, i32 2, i32 3]
+  // CHECK: @[[A2:_ZGRN14ArrayTemporary1bE.*]] = internal constant [3 x i32] [i32 4, i32 5, i32 6]
+  // CHECK: @[[ARR:_ZGRN14ArrayTemporary1bE.*]] = internal constant [2 x {{.*}}] [{{.*}} { [3 x i32]* @[[A1]] }, {{.*}} { [3 x i32]* @[[A2]] }]
+  // CHECK: @[[B:_ZGRN14ArrayTemporary1bE.*]] = internal global {{.*}} { [2 x {{.*}}]* @[[ARR]] }
   // CHECK: @_ZN14ArrayTemporary1bE = constant {{.*}}* @[[B]]
   B &&b = { { { { 1, 2, 3 } }, { { 4, 5, 6 } } } };
 }
@@ -382,7 +391,7 @@
 namespace UnemittedTemporaryDecl {
   constexpr int &&ref = 0;
   extern constexpr int &ref2 = ref;
-  // CHECK: @_ZGRN22UnemittedTemporaryDecl3refE_ = private global i32 0
+  // CHECK: @_ZGRN22UnemittedTemporaryDecl3refE_ = internal global i32 0
 
   // FIXME: This declaration should not be emitted -- it isn't odr-used.
   // CHECK: @_ZN22UnemittedTemporaryDecl3refE
@@ -393,11 +402,11 @@
 // CHECK: @_ZZN12LocalVarInit3aggEvE1a = internal constant {{.*}} i32 101
 // CHECK: @_ZZN12LocalVarInit4ctorEvE1a = internal constant {{.*}} i32 102
 // CHECK: @_ZZN12LocalVarInit8mutable_EvE1a = private unnamed_addr constant {{.*}} i32 103
-// CHECK: @_ZGRN33ClassTemplateWithStaticDataMember1SIvE1aE_ = linkonce_odr constant i32 5
+// CHECK: @_ZGRN33ClassTemplateWithStaticDataMember1SIvE1aE_ = linkonce_odr constant i32 5, comdat
 // CHECK: @_ZN33ClassTemplateWithStaticDataMember3useE = constant i32* @_ZGRN33ClassTemplateWithStaticDataMember1SIvE1aE_
-// CHECK: @_ZGRN39ClassTemplateWithHiddenStaticDataMember1SIvE1aE_ = linkonce_odr hidden constant i32 5
+// CHECK: @_ZGRN39ClassTemplateWithHiddenStaticDataMember1SIvE1aE_ = linkonce_odr hidden constant i32 5, comdat
 // CHECK: @_ZN39ClassTemplateWithHiddenStaticDataMember3useE = constant i32* @_ZGRN39ClassTemplateWithHiddenStaticDataMember1SIvE1aE_
-// CHECK: @_ZGRZN20InlineStaticConstRef3funEvE1i_ = linkonce_odr constant i32 10
+// CHECK: @_ZGRZN20InlineStaticConstRef3funEvE1i_ = linkonce_odr constant i32 10, comdat
 
 // Constant initialization tests go before this point,
 // dynamic initialization tests go after.
@@ -586,3 +595,16 @@
   const int &S<T>::a = 5;
   const int &use = S<void>::a;
 }
+
+namespace ClassWithStaticConstexprDataMember {
+struct X {
+  static constexpr const char &p = 'c';
+};
+
+// CHECK: @_ZGRN34ClassWithStaticConstexprDataMember1X1pE_
+const char *f() { return &X::p; }
+}
+
+// VirtualMembers::TemplateClass::templateMethod() must be defined in this TU,
+// not just declared.
+// CHECK: define linkonce_odr void @_ZN14VirtualMembers13TemplateClassIiE14templateMethodEv(%"struct.VirtualMembers::TemplateClass"* %this)
diff --git a/test/CodeGenCXX/const-init-cxx1y.cpp b/test/CodeGenCXX/const-init-cxx1y.cpp
index 9348b43..c10cde8 100644
--- a/test/CodeGenCXX/const-init-cxx1y.cpp
+++ b/test/CodeGenCXX/const-init-cxx1y.cpp
@@ -23,18 +23,18 @@
   struct A { int &&temporary; int x; };
   constexpr int f(int &r) { r *= 9; return r - 12; }
   A a = { 6, f(a.temporary) };
-  // CHECK: @_ZGRN21ModifyStaticTemporary1aE_ = private global i32 54
+  // CHECK: @_ZGRN21ModifyStaticTemporary1aE_ = internal global i32 54
   // CHECK: @_ZN21ModifyStaticTemporary1aE = global {{.*}} i32* @_ZGRN21ModifyStaticTemporary1aE_, i32 42
 
   A b = { 7, ++b.temporary };
-  // CHECK: @_ZGRN21ModifyStaticTemporary1bE_ = private global i32 8
+  // CHECK: @_ZGRN21ModifyStaticTemporary1bE_ = internal global i32 8
   // CHECK: @_ZN21ModifyStaticTemporary1bE = global {{.*}} i32* @_ZGRN21ModifyStaticTemporary1bE_, i32 8
 
   // Can't emit all of 'c' as a constant here, so emit the initial value of
   // 'c.temporary', not the value as modified by the partial evaluation within
   // the initialization of 'c.x'.
   A c = { 10, (++c.temporary, b.x) };
-  // CHECK: @_ZGRN21ModifyStaticTemporary1cE_ = private global i32 10
+  // CHECK: @_ZGRN21ModifyStaticTemporary1cE_ = internal global i32 10
   // CHECK: @_ZN21ModifyStaticTemporary1cE = global {{.*}} zeroinitializer
 }
 
diff --git a/test/CodeGenCXX/constructor-init.cpp b/test/CodeGenCXX/constructor-init.cpp
index a8f483e..e10b371 100644
--- a/test/CodeGenCXX/constructor-init.cpp
+++ b/test/CodeGenCXX/constructor-init.cpp
@@ -94,23 +94,23 @@
   };
 
   // CHECK-LABEL: define void @_ZN10InitVTable1BC2Ev(%"struct.InitVTable::B"* %this) unnamed_addr
-  // CHECK:      [[T0:%.*]] = bitcast [[B:%.*]]* [[THIS:%.*]] to i8***
-  // CHECK-NEXT: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN10InitVTable1BE, i64 0, i64 2), i8*** [[T0]]
+  // CHECK:      [[T0:%.*]] = bitcast [[B:%.*]]* [[THIS:%.*]] to i32 (...)***
+  // CHECK-NEXT: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN10InitVTable1BE, i64 0, i64 2) to i32 (...)**), i32 (...)*** [[T0]]
   // CHECK:      [[VTBL:%.*]] = load i32 ([[B]]*)*** {{%.*}}
   // CHECK-NEXT: [[FNP:%.*]] = getelementptr inbounds i32 ([[B]]*)** [[VTBL]], i64 0
   // CHECK-NEXT: [[FN:%.*]] = load i32 ([[B]]*)** [[FNP]]
   // CHECK-NEXT: [[ARG:%.*]] = call i32 [[FN]]([[B]]* [[THIS]])
   // CHECK-NEXT: call void @_ZN10InitVTable1AC2Ei({{.*}}* {{%.*}}, i32 [[ARG]])
-  // CHECK-NEXT: [[T0:%.*]] = bitcast [[B]]* [[THIS]] to i8***
-  // CHECK-NEXT: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN10InitVTable1BE, i64 0, i64 2), i8*** [[T0]]
+  // CHECK-NEXT: [[T0:%.*]] = bitcast [[B]]* [[THIS]] to i32 (...)***
+  // CHECK-NEXT: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN10InitVTable1BE, i64 0, i64 2) to i32 (...)**), i32 (...)*** [[T0]]
   // CHECK-NEXT: ret void
   B::B() : A(foo()) {}
 
   // CHECK-LABEL: define void @_ZN10InitVTable1BC2Ei(%"struct.InitVTable::B"* %this, i32 %x) unnamed_addr
   // CHECK:      [[ARG:%.*]] = add nsw i32 {{%.*}}, 5
   // CHECK-NEXT: call void @_ZN10InitVTable1AC2Ei({{.*}}* {{%.*}}, i32 [[ARG]])
-  // CHECK-NEXT: [[T0:%.*]] = bitcast [[B]]* {{%.*}} to i8***
-  // CHECK-NEXT: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN10InitVTable1BE, i64 0, i64 2), i8*** [[T0]]
+  // CHECK-NEXT: [[T0:%.*]] = bitcast [[B]]* {{%.*}} to i32 (...)***
+  // CHECK-NEXT: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN10InitVTable1BE, i64 0, i64 2) to i32 (...)**), i32 (...)*** [[T0]]
   // CHECK-NEXT: ret void
   B::B(int x) : A(x + 5) {}
 }
@@ -200,6 +200,20 @@
     // CHECK-PR10720: ret
     pair2 &operator=(pair2&&) = default;
 
+    // CHECK-PR10720-LABEL: define linkonce_odr void @_ZN7PR107204pairC2ERKS0_
+    // CHECK-PR10720-NOT: ret
+    // CHECK-PR10720: call void @llvm.memcpy
+    // CHECK-PR10720-NEXT: ret void
+
+    // CHECK-PR10720-LABEL: define linkonce_odr void @_ZN7PR107205pair2C2ERKS0_
+    // CHECK-PR10720-NOT: ret
+    // CHECK-PR10720: load
+    // CHECK-PR10720: icmp ult
+    // CHECK-PR10720-NEXT: br i1
+    // CHECK-PR10720: call void @_ZN7PR107201XC1ERKS0_
+    // CHECK-PR10720-NEXT: br label
+    // CHECK-PR10720: ret void
+
     // CHECK-PR10720-LABEL: define linkonce_odr void @_ZN7PR107205pair2C2EOS0_
     // CHECK-PR10720-NOT: ret
     // CHECK-PR10720: load
@@ -210,23 +224,11 @@
     // CHECK-PR10720: ret void
     pair2(pair2&&) = default;
 
-    // CHECK-PR10720-LABEL: define linkonce_odr void @_ZN7PR107205pair2C2ERKS0_
-    // CHECK-PR10720-NOT: ret
-    // CHECK-PR10720: load
-    // CHECK-PR10720: icmp ult
-    // CHECK-PR10720-NEXT: br i1
-    // CHECK-PR10720: call void @_ZN7PR107201XC1ERKS0_
-    // CHECK-PR10720-NEXT: br label
-    // CHECK-PR10720: ret void
     pair2(const pair2&) = default;
   };
 
   struct pair : X { // Make the copy constructor non-trivial, so we actually generate it.
     int second[4];
-    // CHECK-PR10720-LABEL: define linkonce_odr void @_ZN7PR107204pairC2ERKS0_
-    // CHECK-PR10720-NOT: ret
-    // CHECK-PR10720: call void @llvm.memcpy
-    // CHECK-PR10720-NEXT: ret void
     pair(const pair&) = default;
   };
 
diff --git a/test/CodeGenCXX/constructor-template.cpp b/test/CodeGenCXX/constructor-template.cpp
index 675e3cf..d1ae094 100644
--- a/test/CodeGenCXX/constructor-template.cpp
+++ b/test/CodeGenCXX/constructor-template.cpp
@@ -45,10 +45,10 @@
   delete node;
 }
 
+// CHECK-LP64: __ZN4ListIP12BinomialNodeIiEED1Ev:
 // CHECK-LP64: __ZN4NodeIP12BinomialNodeIiEEC2Ev:
 // CHECK-LP64: __ZN4ListIP12BinomialNodeIiEEC1Ev:
-// CHECK-LP64: __ZN4ListIP12BinomialNodeIiEED1Ev:
 
+// CHECK-LP32: __ZN4ListIP12BinomialNodeIiEED1Ev:
 // CHECK-LP32: __ZN4NodeIP12BinomialNodeIiEEC2Ev:
 // CHECK-LP32: __ZN4ListIP12BinomialNodeIiEEC1Ev:
-// CHECK-LP32: __ZN4ListIP12BinomialNodeIiEED1Ev:
diff --git a/test/CodeGenCXX/copy-constructor-elim.cpp b/test/CodeGenCXX/copy-constructor-elim.cpp
index 8e9bee9..d9b28ce 100644
--- a/test/CodeGenCXX/copy-constructor-elim.cpp
+++ b/test/CodeGenCXX/copy-constructor-elim.cpp
@@ -43,3 +43,17 @@
   S s;
   Call(s);
 }
+
+struct V {
+  int x;
+};
+
+typedef V V_over_aligned __attribute((aligned(8)));
+extern const V_over_aligned gv1 = {};
+
+extern "C" V f() { return gv1; }
+
+// Make sure that we obey the destination's alignment requirements when emitting
+// the copy.
+// CHECK-LABEL: define {{.*}} @f(
+// CHECK:   call void @llvm.memcpy.p0i8.p0i8.{{i64|i32}}({{.*}}, i8* bitcast (%struct.V* @gv1 to i8*), {{i64|i32}} 4, i32 4, i1 false)
diff --git a/test/CodeGenCXX/copy-constructor-synthesis-2.cpp b/test/CodeGenCXX/copy-constructor-synthesis-2.cpp
index 4bb0fee..8fdc4df 100644
--- a/test/CodeGenCXX/copy-constructor-synthesis-2.cpp
+++ b/test/CodeGenCXX/copy-constructor-synthesis-2.cpp
@@ -4,4 +4,4 @@
 A x(A& y) { return y; }
 
 // CHECK: define linkonce_odr {{.*}} @_ZN1AC1ERKS_(%struct.A* {{.*}}%this, %struct.A* dereferenceable({{[0-9]+}})) unnamed_addr
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1A, i64 0, i64 2)
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1A, i64 0, i64 2) to i32 (...)**)
diff --git a/test/CodeGenCXX/copy-constructor-synthesis.cpp b/test/CodeGenCXX/copy-constructor-synthesis.cpp
index 47f8e13..30178a0 100644
--- a/test/CodeGenCXX/copy-constructor-synthesis.cpp
+++ b/test/CodeGenCXX/copy-constructor-synthesis.cpp
@@ -146,18 +146,6 @@
 // CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[T4]], i8* [[T5]], i64 8, i32 8, i1 false)
 // CHECK-NEXT: ret [[A]]* [[THIS]]
 
-// CHECK-LABEL:    define linkonce_odr void @_ZN12rdar138169401AC2ERKS0_(
-// CHECK:      [[THIS:%.*]] = load [[A]]**
-// CHECK-NEXT: [[T0:%.*]] = bitcast [[A]]* [[THIS]] to i8***
-// CHECK-NEXT: store i8** getelementptr inbounds ([4 x i8*]* @_ZTVN12rdar138169401AE, i64 0, i64 2), i8*** [[T0]]
-// CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds [[A]]* [[THIS]], i32 0, i32 1
-// CHECK-NEXT: [[OTHER:%.*]] = load [[A]]**
-// CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds [[A]]* [[OTHER]], i32 0, i32 1
-// CHECK-NEXT: [[T4:%.*]] = bitcast i16* [[T0]] to i8*
-// CHECK-NEXT: [[T5:%.*]] = bitcast i16* [[T2]] to i8*
-// CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[T4]], i8* [[T5]], i64 8, i32 8, i1 false)
-// CHECK-NEXT: ret void
-
 // CHECK-LABEL: define linkonce_odr void @_ZN6PR66281BC2ERKS0_(%"struct.PR6628::B"* %this, %"struct.PR6628::B"* dereferenceable({{[0-9]+}})) unnamed_addr
 // CHECK: call void @_ZN6PR66281TC1Ev
 // CHECK: call void @_ZN6PR66281TC1Ev
@@ -174,6 +162,18 @@
 // CHECK: call void @_ZN6PR66281AC1ERKS0_RKNS_1TES5_
 // CHECK: call void @_ZN6PR66281TD1Ev
 // CHECK: call void @_ZN6PR66281TD1Ev
+
+// CHECK-LABEL:    define linkonce_odr void @_ZN12rdar138169401AC2ERKS0_(
+// CHECK:      [[THIS:%.*]] = load [[A]]**
+// CHECK-NEXT: [[T0:%.*]] = bitcast [[A]]* [[THIS]] to i32 (...)***
+// CHECK-NEXT: store i32 (...)** bitcast (i8** getelementptr inbounds ([4 x i8*]* @_ZTVN12rdar138169401AE, i64 0, i64 2) to i32 (...)**), i32 (...)*** [[T0]]
+// CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds [[A]]* [[THIS]], i32 0, i32 1
+// CHECK-NEXT: [[OTHER:%.*]] = load [[A]]**
+// CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds [[A]]* [[OTHER]], i32 0, i32 1
+// CHECK-NEXT: [[T4:%.*]] = bitcast i16* [[T0]] to i8*
+// CHECK-NEXT: [[T5:%.*]] = bitcast i16* [[T2]] to i8*
+// CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[T4]], i8* [[T5]], i64 8, i32 8, i1 false)
+// CHECK-NEXT: ret void
 }
 
 // rdar://13816940
diff --git a/test/CodeGenCXX/coverage.cpp b/test/CodeGenCXX/coverage.cpp
index 16703bd..3931b0c 100644
--- a/test/CodeGenCXX/coverage.cpp
+++ b/test/CodeGenCXX/coverage.cpp
@@ -3,5 +3,5 @@
 extern "C" void test_name1() {}
 void test_name2() {}
 
-// CHECK: metadata !"0x2e\00test_name1\00test_name1\00\00{{[^,]+}}", {{.*}} DW_TAG_subprogram
-// CHECK: metadata !"0x2e\00test_name2\00test_name2\00_Z10test_name2v\00{{[^,]+}}", {{.*}} DW_TAG_subprogram
+// CHECK: !"0x2e\00test_name1\00test_name1\00\00{{[^,]+}}", {{.*}} DW_TAG_subprogram
+// CHECK: !"0x2e\00test_name2\00test_name2\00_Z10test_name2v\00{{[^,]+}}", {{.*}} DW_TAG_subprogram
diff --git a/test/CodeGenCXX/crash.cpp b/test/CodeGenCXX/crash.cpp
index 073542d..256291a 100644
--- a/test/CodeGenCXX/crash.cpp
+++ b/test/CodeGenCXX/crash.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 %s -std=c++11 -emit-llvm-only
+// RUN: %clang_cc1 -emit-obj -o %t -gline-tables-only -std=c++11 %s
 // CHECK that we don't crash.
 
 // PR11676's example is ill-formed:
diff --git a/test/CodeGenCXX/ctor-dtor-alias.cpp b/test/CodeGenCXX/ctor-dtor-alias.cpp
index 1ae9ead..4c11971 100644
--- a/test/CodeGenCXX/ctor-dtor-alias.cpp
+++ b/test/CodeGenCXX/ctor-dtor-alias.cpp
@@ -16,13 +16,16 @@
 
 // CHECK1: @_ZN5test16foobarIvEC1Ev = weak_odr alias void {{.*}} @_ZN5test16foobarIvEC2Ev
 // CHECK1: @_ZN5test16foobarIvED1Ev = weak_odr alias void (%"struct.test1::foobar"*)* @_ZN5test16foobarIvED2Ev
-// CHECK1: define weak_odr void @_ZN5test16foobarIvEC2Ev({{.*}} comdat $_ZN5test16foobarIvEC5Ev
-// CHECK1: define weak_odr void @_ZN5test16foobarIvED2Ev({{.*}} comdat $_ZN5test16foobarIvED5Ev
-// CHECK1: define weak_odr void @_ZN5test16foobarIvED0Ev({{.*}} comdat $_ZN5test16foobarIvED5Ev
+// CHECK1: define weak_odr void @_ZN5test16foobarIvEC2Ev({{.*}} comdat($_ZN5test16foobarIvEC5Ev)
+// CHECK1: define weak_odr void @_ZN5test16foobarIvED2Ev({{.*}} comdat($_ZN5test16foobarIvED5Ev)
+// CHECK1: define weak_odr void @_ZN5test16foobarIvED0Ev({{.*}} comdat($_ZN5test16foobarIvED5Ev)
 // CHECK1-NOT: comdat
 
 // COFF doesn't support comdats with arbitrary names (C5/D5).
-// COFF-NOT: comdat
+// COFF: define weak_odr {{.*}} void @_ZN5test16foobarIvEC2Ev({{.*}} comdat align
+// COFF: define weak_odr {{.*}} void @_ZN5test16foobarIvEC1Ev({{.*}} comdat align
+// COFF: define weak_odr {{.*}} void @_ZN5test16foobarIvED2Ev({{.*}} comdat align
+// COFF: define weak_odr {{.*}} void @_ZN5test16foobarIvED0Ev({{.*}} comdat align
 
 template <typename T>
 struct foobar {
@@ -39,7 +42,7 @@
 
 // CHECK1: define internal void @__cxx_global_var_init()
 // CHECK1: call void @_ZN5test26foobarIvEC2Ev
-// CHECK1: define linkonce_odr void @_ZN5test26foobarIvEC2Ev(
+// CHECK1: define linkonce_odr void @_ZN5test26foobarIvEC2Ev({{.*}} comdat align
 void g();
 template <typename T> struct foobar {
   foobar() { g(); }
@@ -72,13 +75,13 @@
 
   // CHECK1: define internal void @__cxx_global_var_init2()
   // CHECK1: call i32 @__cxa_atexit{{.*}}_ZN5test41AD2Ev
-  // CHECK1: define linkonce_odr void @_ZN5test41AD2Ev(
+  // CHECK1: define linkonce_odr void @_ZN5test41AD2Ev({{.*}} comdat align
 
   // test that we don't do this optimization at -O0 so that the debugger can
   // see both destructors.
   // NOOPT: define internal void @__cxx_global_var_init2()
   // NOOPT: call i32 @__cxa_atexit{{.*}}@_ZN5test41BD2Ev
-  // NOOPT: define linkonce_odr void @_ZN5test41BD2Ev
+  // NOOPT: define linkonce_odr void @_ZN5test41BD2Ev({{.*}} comdat align
   struct A {
     virtual ~A() {}
   };
@@ -93,7 +96,7 @@
 
   // CHECK2: define internal void @__cxx_global_var_init3()
   // CHECK2: call i32 @__cxa_atexit{{.*}}_ZN5test51AD2Ev
-  // CHECK2: define linkonce_odr void @_ZN5test51AD2Ev(
+  // CHECK2: define linkonce_odr void @_ZN5test51AD2Ev({{.*}} comdat align
   struct A {
     virtual ~A() {}
   };
@@ -215,7 +218,7 @@
 template <typename T>
 foo<T>::~foo() {}
 template class foo<int>;
-// CHECK5: define weak_odr void @_ZN6test103fooIiED2Ev({{.*}} comdat $_ZN6test103fooIiED5Ev
+// CHECK5: define weak_odr void @_ZN6test103fooIiED2Ev({{.*}} comdat($_ZN6test103fooIiED5Ev)
 }
 
 namespace test11 {
@@ -232,3 +235,14 @@
 // CHECK6: @_ZN6test113fooD2Ev = alias {{.*}} @_ZN6test113barD2Ev
 // CHECK6: @_ZN6test113fooD1Ev = alias {{.*}} @_ZN6test113fooD2Ev
 }
+
+namespace test12 {
+template <int>
+struct foo {
+  ~foo() { delete this; }
+};
+
+template class foo<1>;
+// CHECK6: @_ZN6test123fooILi1EED1Ev = weak_odr alias {{.*}} @_ZN6test123fooILi1EED2Ev
+// CHECK6: define weak_odr void @_ZN6test123fooILi1EED2Ev({{.*}}) {{.*}} comdat($_ZN6test123fooILi1EED5Ev)
+}
diff --git a/test/CodeGenCXX/ctor-globalopt.cpp b/test/CodeGenCXX/ctor-globalopt.cpp
new file mode 100644
index 0000000..672fc90
--- /dev/null
+++ b/test/CodeGenCXX/ctor-globalopt.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -o - %s -O1 | FileCheck %s --check-prefix=O1
+// RUN: %clang_cc1 -triple %ms_abi_triple -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple %ms_abi_triple -emit-llvm -o - %s -O1 | FileCheck %s --check-prefix=O1
+
+// Check that GlobalOpt can eliminate static constructors for simple implicit
+// constructors. This is a targetted integration test to make sure that LLVM's
+// optimizers are able to process Clang's IR. GlobalOpt in particular is
+// sensitive to the casts we emit.
+
+// CHECK: @llvm.global_ctors = appending global [1 x { i32, void ()*, i8* }] 
+// CHECK: [{ i32, void ()*, i8* } { i32 65535, void ()* @_GLOBAL__sub_I_ctor_globalopt.cpp, i8* null }]
+
+// CHECK-LABEL: define internal void @_GLOBAL__sub_I_ctor_globalopt.cpp()
+// CHECK: call void @
+// CHECK-NOT: call
+
+// O1: @llvm.global_ctors = appending global [0 x { i32, void ()*, i8* }] zeroinitializer
+
+struct A {
+  virtual void f();
+  int a;
+};
+struct B : virtual A {
+  virtual void g();
+  int b;
+};
+B b;
diff --git a/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-pr12086.cpp b/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-pr12086.cpp
index 91e913e..8ba8000 100644
--- a/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-pr12086.cpp
+++ b/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-pr12086.cpp
@@ -55,10 +55,10 @@
   {1, a}, {3, b}, {5, c}
 };
 
-// CHECK-STATIC-BL: @_ZGR6nested0_ = private constant [2 x i32] [i32 1, i32 2], align 4
-// CHECK-STATIC-BL: @_ZGR6nested1_ = private constant [2 x i32] [i32 3, i32 4], align 4
-// CHECK-STATIC-BL: @_ZGR6nested2_ = private constant [2 x i32] [i32 5, i32 6], align 4
-// CHECK-STATIC-BL: @_ZGR6nested_ = private constant [3 x {{.*}}] [
+// CHECK-STATIC-BL: @_ZGR6nested0_ = internal constant [2 x i32] [i32 1, i32 2], align 4
+// CHECK-STATIC-BL: @_ZGR6nested1_ = internal constant [2 x i32] [i32 3, i32 4], align 4
+// CHECK-STATIC-BL: @_ZGR6nested2_ = internal constant [2 x i32] [i32 5, i32 6], align 4
+// CHECK-STATIC-BL: @_ZGR6nested_ = internal constant [3 x {{.*}}] [
 // CHECK-STATIC-BL:   {{.*}} { i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i32 0, i32 0), i64 2 },
 // CHECK-STATIC-BL:   {{.*}} { i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested1_, i32 0, i32 0), i64 2 },
 // CHECK-STATIC-BL:   {{.*}} { i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested2_, i32 0, i32 0), i64 2 }
@@ -66,10 +66,10 @@
 // CHECK-STATIC-BL: @nested = global {{.*}} { {{.*}} getelementptr inbounds ([3 x {{.*}}]* @_ZGR6nested_, i32 0, i32 0), i64 3 }, align 8
 
 // CHECK-DYNAMIC-BL: @nested = global
-// CHECK-DYNAMIC-BL: @_ZGR6nested_ = private global [3 x
-// CHECK-DYNAMIC-BL: @_ZGR6nested0_ = private global [2 x i32] zeroinitializer
-// CHECK-DYNAMIC-BL: @_ZGR6nested1_ = private global [2 x i32] zeroinitializer
-// CHECK-DYNAMIC-BL: @_ZGR6nested2_ = private global [2 x i32] zeroinitializer
+// CHECK-DYNAMIC-BL: @_ZGR6nested_ = internal global [3 x
+// CHECK-DYNAMIC-BL: @_ZGR6nested0_ = internal global [2 x i32] zeroinitializer
+// CHECK-DYNAMIC-BL: @_ZGR6nested1_ = internal global [2 x i32] zeroinitializer
+// CHECK-DYNAMIC-BL: @_ZGR6nested2_ = internal global [2 x i32] zeroinitializer
 // CHECK-DYNAMIC-BL: store i32 1, i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i64 0, i64 0)
 // CHECK-DYNAMIC-BL: store i32 {{.*}}, i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i64 0, i64 1)
 // CHECK-DYNAMIC-BL: store i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i64 0, i64 0),
@@ -89,10 +89,10 @@
 // CHECK-DYNAMIC-BL:       {{.*}}** getelementptr inbounds ({{.*}}* @nested, i32 0, i32 0), align 8
 // CHECK-DYNAMIC-BL: store i64 3, i64* getelementptr inbounds ({{.*}}* @nested, i32 0, i32 1), align 8
 
-// CHECK-STATIC-BE: @_ZGR6nested0_ = private constant [2 x i32] [i32 1, i32 2], align 4
-// CHECK-STATIC-BE: @_ZGR6nested1_ = private constant [2 x i32] [i32 3, i32 4], align 4
-// CHECK-STATIC-BE: @_ZGR6nested2_ = private constant [2 x i32] [i32 5, i32 6], align 4
-// CHECK-STATIC-BE: @_ZGR6nested_ = private constant [3 x {{.*}}] [
+// CHECK-STATIC-BE: @_ZGR6nested0_ = internal constant [2 x i32] [i32 1, i32 2], align 4
+// CHECK-STATIC-BE: @_ZGR6nested1_ = internal constant [2 x i32] [i32 3, i32 4], align 4
+// CHECK-STATIC-BE: @_ZGR6nested2_ = internal constant [2 x i32] [i32 5, i32 6], align 4
+// CHECK-STATIC-BE: @_ZGR6nested_ = internal constant [3 x {{.*}}] [
 // CHECK-STATIC-BE:   {{.*}} { i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i32 0, i32 0),
 // CHECK-STATIC-BE:            i32* bitcast (i8* getelementptr (i8* bitcast ([2 x i32]* @_ZGR6nested0_ to i8*), i64 8) to i32*) }
 // CHECK-STATIC-BE:   {{.*}} { i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested1_, i32 0, i32 0),
@@ -104,10 +104,10 @@
 // CHECK-STATIC-BE:                           {{.*}} bitcast ({{.*}}* getelementptr (i8* bitcast ([3 x {{.*}}]* @_ZGR6nested_ to i8*), i64 48) to {{.*}}*) }
 
 // CHECK-DYNAMIC-BE: @nested = global
-// CHECK-DYNAMIC-BE: @_ZGR6nested_ = private global [3 x
-// CHECK-DYNAMIC-BE: @_ZGR6nested0_ = private global [2 x i32] zeroinitializer
-// CHECK-DYNAMIC-BE: @_ZGR6nested1_ = private global [2 x i32] zeroinitializer
-// CHECK-DYNAMIC-BE: @_ZGR6nested2_ = private global [2 x i32] zeroinitializer
+// CHECK-DYNAMIC-BE: @_ZGR6nested_ = internal global [3 x
+// CHECK-DYNAMIC-BE: @_ZGR6nested0_ = internal global [2 x i32] zeroinitializer
+// CHECK-DYNAMIC-BE: @_ZGR6nested1_ = internal global [2 x i32] zeroinitializer
+// CHECK-DYNAMIC-BE: @_ZGR6nested2_ = internal global [2 x i32] zeroinitializer
 // CHECK-DYNAMIC-BE: store i32 1, i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i64 0, i64 0)
 // CHECK-DYNAMIC-BE: store i32 {{.*}}, i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i64 0, i64 1)
 // CHECK-DYNAMIC-BE: store i32* getelementptr inbounds ([2 x i32]* @_ZGR6nested0_, i64 0, i64 0),
diff --git a/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp b/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp
index 5a48346..44d44f9 100644
--- a/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp
+++ b/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist-startend.cpp
@@ -32,7 +32,7 @@
   };
 }
 
-// CHECK: @_ZGR15globalInitList1_ = private constant [3 x i32] [i32 1, i32 2, i32 3]
+// CHECK: @_ZGR15globalInitList1_ = internal constant [3 x i32] [i32 1, i32 2, i32 3]
 // CHECK: @globalInitList1 = global {{[^ ]+}} { i32* getelementptr inbounds ([3 x i32]* @_ZGR15globalInitList1_, {{[^)]*}}), i32*
 std::initializer_list<int> globalInitList1 = {1, 2, 3};
 
diff --git a/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist.cpp b/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist.cpp
index 4d30344..79644cd 100644
--- a/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist.cpp
+++ b/test/CodeGenCXX/cxx0x-initializer-stdinitializerlist.cpp
@@ -47,7 +47,7 @@
   ~wantslist1();
 };
 
-// CHECK: @_ZGR15globalInitList1_ = private constant [3 x i32] [i32 1, i32 2, i32 3]
+// CHECK: @_ZGR15globalInitList1_ = internal constant [3 x i32] [i32 1, i32 2, i32 3]
 // CHECK: @globalInitList1 = global %{{[^ ]+}} { i32* getelementptr inbounds ([3 x i32]* @_ZGR15globalInitList1_, i32 0, i32 0), i{{32|64}} 3 }
 std::initializer_list<int> globalInitList1 = {1, 2, 3};
 
@@ -57,20 +57,20 @@
   // objects aren't really a problem).
   //
   // CHECK: @_ZN25thread_local_global_array1xE = thread_local global
-  // CHECK: @_ZGRN25thread_local_global_array1xE_ = private thread_local constant [4 x i32] [i32 1, i32 2, i32 3, i32 4]
+  // CHECK: @_ZGRN25thread_local_global_array1xE_ = internal thread_local constant [4 x i32] [i32 1, i32 2, i32 3, i32 4]
   std::initializer_list<int> thread_local x = { 1, 2, 3, 4 };
 }
 
 // CHECK: @globalInitList2 = global %{{[^ ]+}} zeroinitializer
-// CHECK: @_ZGR15globalInitList2_ = private global [2 x %[[WITHARG:[^ ]*]]] zeroinitializer
+// CHECK: @_ZGR15globalInitList2_ = internal global [2 x %[[WITHARG:[^ ]*]]] zeroinitializer
 
 // CHECK: @_ZN15partly_constant1kE = global i32 0, align 4
 // CHECK: @_ZN15partly_constant2ilE = global {{.*}} null, align 8
-// CHECK: @[[PARTLY_CONSTANT_OUTER:_ZGRN15partly_constant2ilE.*]] = private global {{.*}} zeroinitializer, align 8
-// CHECK: @[[PARTLY_CONSTANT_INNER:_ZGRN15partly_constant2ilE.*]] = private global [3 x {{.*}}] zeroinitializer, align 8
-// CHECK: @[[PARTLY_CONSTANT_FIRST:_ZGRN15partly_constant2ilE.*]] = private constant [3 x i32] [i32 1, i32 2, i32 3], align 4
-// CHECK: @[[PARTLY_CONSTANT_SECOND:_ZGRN15partly_constant2ilE.*]] = private global [2 x i32] zeroinitializer, align 4
-// CHECK: @[[PARTLY_CONSTANT_THIRD:_ZGRN15partly_constant2ilE.*]] = private constant [4 x i32] [i32 5, i32 6, i32 7, i32 8], align 4
+// CHECK: @[[PARTLY_CONSTANT_OUTER:_ZGRN15partly_constant2ilE.*]] = internal global {{.*}} zeroinitializer, align 8
+// CHECK: @[[PARTLY_CONSTANT_INNER:_ZGRN15partly_constant2ilE.*]] = internal global [3 x {{.*}}] zeroinitializer, align 8
+// CHECK: @[[PARTLY_CONSTANT_FIRST:_ZGRN15partly_constant2ilE.*]] = internal constant [3 x i32] [i32 1, i32 2, i32 3], align 4
+// CHECK: @[[PARTLY_CONSTANT_SECOND:_ZGRN15partly_constant2ilE.*]] = internal global [2 x i32] zeroinitializer, align 4
+// CHECK: @[[PARTLY_CONSTANT_THIRD:_ZGRN15partly_constant2ilE.*]] = internal constant [4 x i32] [i32 5, i32 6, i32 7, i32 8], align 4
 
 // CHECK: appending global
 
diff --git a/test/CodeGenCXX/cxx11-exception-spec.cpp b/test/CodeGenCXX/cxx11-exception-spec.cpp
index 75f939f..3fb5c15 100644
--- a/test/CodeGenCXX/cxx11-exception-spec.cpp
+++ b/test/CodeGenCXX/cxx11-exception-spec.cpp
@@ -22,9 +22,9 @@
 // CHECK: define {{.*}} @_ZN1SIA2_sE1fEv() [[NUW]]
 template<> void S<short[2]>::f() noexcept { h(); }
 
-// CHECK: define {{.*}} @_Z1fIDsEvv() [[NONE]] {
+// CHECK: define {{.*}} @_Z1fIDsEvv() [[NONE]] comdat {
 template void f<char16_t>();
-// CHECK: define {{.*}} @_Z1fIA2_DsEvv() [[NUW]]  {
+// CHECK: define {{.*}} @_Z1fIA2_DsEvv() [[NUW]] comdat {
 template void f<char16_t[2]>();
 
 // CHECK: define {{.*}} @_ZN1SIDsE1fEv()
@@ -34,9 +34,9 @@
 template void S<char16_t[2]>::f();
 
 void h() {
-  // CHECK: define {{.*}} @_Z1fIiEvv() [[NUW]] {
+  // CHECK: define {{.*}} @_Z1fIiEvv() [[NUW]] comdat {
   f<int>();
-  // CHECK: define {{.*}} @_Z1fIA2_iEvv() [[NONE]] {
+  // CHECK: define {{.*}} @_Z1fIA2_iEvv() [[NONE]] comdat {
   f<int[2]>();
 
   // CHECK: define {{.*}} @_ZN1SIiE1fEv() [[NUW]]
@@ -45,9 +45,9 @@
   // CHECK-NOT: [[NUW]]
   S<int[2]>::f();
 
-  // CHECK: define {{.*}} @_Z1fIfEvv() [[NUW]] {
+  // CHECK: define {{.*}} @_Z1fIfEvv() [[NUW]] comdat {
   void (*f1)() = &f<float>;
-  // CHECK: define {{.*}} @_Z1fIdEvv() [[NONE]] {
+  // CHECK: define {{.*}} @_Z1fIdEvv() [[NONE]] comdat {
   void (*f2)() = &f<double>;
 
   // CHECK: define {{.*}} @_ZN1SIfE1fEv() [[NUW]]
@@ -56,9 +56,9 @@
   // CHECK-NOT: [[NUW]]
   void (*f4)() = &S<double>::f;
 
-  // CHECK: define {{.*}} @_Z1fIA4_cEvv() [[NUW]] {
+  // CHECK: define {{.*}} @_Z1fIA4_cEvv() [[NUW]] comdat {
   (void)&f<char[4]>;
-  // CHECK: define {{.*}} @_Z1fIcEvv() [[NONE]] {
+  // CHECK: define {{.*}} @_Z1fIcEvv() [[NONE]] comdat {
   (void)&f<char>;
 
   // CHECK: define {{.*}} @_ZN1SIA4_cE1fEv() [[NUW]]
diff --git a/test/CodeGenCXX/cxx1y-init-captures.cpp b/test/CodeGenCXX/cxx1y-init-captures.cpp
index a60269f..c81b592 100644
--- a/test/CodeGenCXX/cxx1y-init-captures.cpp
+++ b/test/CodeGenCXX/cxx1y-init-captures.cpp
@@ -35,6 +35,7 @@
 // CHECK: load i32*
 // CHECK: getelementptr inbounds {{.*}}, i32 0, i32 1
 // CHECK: load i32*
+
 // CHECK: add nsw i32
 
 int h(int a) {
@@ -74,6 +75,9 @@
     //
     // CHECK: call i32 @"_ZZZ1hiENK3$_2clEvENKUlvE_clEv"({{.*}}* %[[INNER]])
     return [=, &c] {
+      // CHECK-LABEL: define internal void @"_ZZ1fvEN3$_0D2Ev"(
+      // CHECK: call void @_ZN1SD1Ev(
+
       // CHECK-LABEL: define internal i32 @"_ZZZ1hiENK3$_2clEvENKUlvE_clEv"(
       // CHECK: %[[INNER_ADDR:.*]] = alloca
       // CHECK: store {{.*}}, {{.*}}** %[[INNER_ADDR]],
@@ -97,6 +101,3 @@
 // Ensure we can emit code for init-captures in global lambdas too.
 auto global_lambda = [a = 0] () mutable { return ++a; };
 int get_incremented() { return global_lambda(); }
-
-// CHECK-LABEL: define internal void @"_ZZ1fvEN3$_0D2Ev"(
-// CHECK: call void @_ZN1SD1Ev(
diff --git a/test/CodeGenCXX/cxx1y-sized-deallocation.cpp b/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
index 7fd3ece..647a640 100644
--- a/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
+++ b/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
@@ -1,6 +1,9 @@
-// RUN: %clang_cc1 -std=c++1y %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s
-// RUN: %clang_cc1 -std=c++11 -fsized-deallocation %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s
+// RUN: %clang_cc1 -std=c++1y %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s --check-prefix=CHECK --check-prefix=CHECKUND
+// RUN: %clang_cc1 -std=c++1y %s -emit-llvm -triple x86_64-linux-gnu -fdefine-sized-deallocation -o - | FileCheck %s --check-prefix=CHECK --check-prefix=CHECKDEF
+// RUN: %clang_cc1 -std=c++11 -fsized-deallocation %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s --check-prefix=CHECK --check-prefix=CHECKUND
+// RUN: %clang_cc1 -std=c++11 -fsized-deallocation -fdefine-sized-deallocation %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s --check-prefix=CHECK --check-prefix=CHECKDEF
 // RUN: %clang_cc1 -std=c++11 %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s --check-prefix=CHECK-UNSIZED
+// RUN: %clang_cc1 -std=c++1y %s -emit-llvm -triple x86_64-linux-gnu -fno-sized-deallocation -o - | FileCheck %s --check-prefix=CHECK-UNSIZED
 
 // CHECK-UNSIZED-NOT: _ZdlPvm
 // CHECK-UNSIZED-NOT: _ZdaPvm
@@ -44,61 +47,92 @@
 D::D() {}
 
 // CHECK-LABEL: define weak_odr void @_Z3delIiEvv()
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 4)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
 // CHECK: call void @_ZdaPv(i8* %{{[^ ]*}})
 //
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 4)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
 // CHECK: call void @_ZdaPv(i8* %{{[^ ]*}})
 
-// CHECK-LABEL: define linkonce void @_ZdlPvm(i8*
-// CHECK: call void @_ZdlPv(i8* %0)
+// CHECKDEF-LABEL: define linkonce void @_ZdlPvm(i8*, i64) #{{[0-9]+}} comdat
+// CHECKDEF: call void @_ZdlPv(i8* %0)
+// CHECKUND-LABEL: declare extern_weak void @_ZdlPvm(i8*
 
 // CHECK-LABEL: define weak_odr void @_Z3delI1BEvv()
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 4)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
 // CHECK: call void @_ZdaPv(i8* %{{[^ ]*}})
 //
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 4)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
 // CHECK: call void @_ZdaPv(i8* %{{[^ ]*}})
 
 // CHECK-LABEL: define weak_odr void @_Z3delI1CEvv()
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 1)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdaPvm, void (i8*, i64)* null),
 // CHECK: mul i64 1, %{{[^ ]*}}
 // CHECK: add i64 %{{[^ ]*}}, 8
 // CHECK: call void @_ZdaPvm(i8* %{{[^ ]*}}, i64 %{{[^ ]*}})
+// CHECKUND: call void @_ZdaPv(i8* %{{[^ ]*}})
 //
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 1)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdaPvm, void (i8*, i64)* null),
 // CHECK: mul i64 1, %{{[^ ]*}}
 // CHECK: add i64 %{{[^ ]*}}, 8
 // CHECK: call void @_ZdaPvm(i8* %{{[^ ]*}}, i64 %{{[^ ]*}})
+// CHECKUND: call void @_ZdaPv(i8* %{{[^ ]*}})
 
-// CHECK-LABEL: define linkonce void @_ZdaPvm(i8*
-// CHECK: call void @_ZdaPv(i8* %0)
+// CHECKDEF-LABEL: define linkonce void @_ZdaPvm(i8*, i64) #{{[0-9]+}} comdat
+// CHECKDEF: call void @_ZdaPv(i8* %0)
+// CHECKUND-LABEL: declare extern_weak void @_ZdaPvm(i8*
 
 // CHECK-LABEL: define weak_odr void @_Z3delI1DEvv()
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 8)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdaPvm, void (i8*, i64)* null),
 // CHECK: mul i64 8, %{{[^ ]*}}
 // CHECK: add i64 %{{[^ ]*}}, 8
 // CHECK: call void @_ZdaPvm(i8* %{{[^ ]*}}, i64 %{{[^ ]*}})
+// CHECKUND: call void @_ZdaPv(i8* %{{[^ ]*}})
 //
-// CHECK-NOT: Zdl
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
+// CHECKDEF-NOT: Zdl
 // CHECK: call void %{{.*}}
 // CHECK-NOT: Zdl
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdaPvm, void (i8*, i64)* null),
 // CHECK: mul i64 8, %{{[^ ]*}}
 // CHECK: add i64 %{{[^ ]*}}, 8
 // CHECK: call void @_ZdaPvm(i8* %{{[^ ]*}}, i64 %{{[^ ]*}})
+// CHECKUND: call void @_ZdaPv(i8* %{{[^ ]*}})
 
 // CHECK-LABEL: define weak_odr void @_Z3delI1EEvv()
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 1)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
 // CHECK: call void @_ZdaPv(i8* %{{[^ ]*}})
 //
 // CHECK: call void @_ZN1EdlEPv(i8* %{{[^ ]*}})
 // CHECK: call void @_ZN1EdaEPv(i8* %{{[^ ]*}})
 
 // CHECK-LABEL: define weak_odr void @_Z3delI1FEvv()
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
 // CHECK: call void @_ZdlPvm(i8* %{{[^ ]*}}, i64 1)
+// CHECKUND: call void @_ZdlPv(i8* %{{[^ ]*}})
+// CHECKUND: br i1 icmp ne (void (i8*, i64)* @_ZdaPvm, void (i8*, i64)* null),
 // CHECK: mul i64 1, %{{[^ ]*}}
 // CHECK: add i64 %{{[^ ]*}}, 8
 // CHECK: call void @_ZdaPvm(i8* %{{[^ ]*}}, i64 %{{[^ ]*}})
+// CHECKUND: call void @_ZdaPv(i8* %{{[^ ]*}})
 //
 // CHECK: call void @_ZN1FdlEPvm(i8* %{{[^ ]*}}, i64 1)
 // CHECK: mul i64 1, %{{[^ ]*}}
diff --git a/test/CodeGenCXX/debug-info-alias.cpp b/test/CodeGenCXX/debug-info-alias.cpp
index 609b5b7..dd4b00b 100644
--- a/test/CodeGenCXX/debug-info-alias.cpp
+++ b/test/CodeGenCXX/debug-info-alias.cpp
@@ -13,15 +13,15 @@
 = foo<T*>;
 }
 
-// CHECK: metadata [[BINT:![0-9]*]], {{[^,]+, [^,]+}}} ; [ DW_TAG_variable ] [bi]
+// CHECK: [[BINT:![0-9]*]], {{[^,]+, [^,]+}}} ; [ DW_TAG_variable ] [bi]
 // CHECK: [[BINT]] = {{.*}} ; [ DW_TAG_typedef ] [bar<int>] [line 42
 x::bar<int> bi;
-// CHECK: metadata [[BFLOAT:![0-9]*]], {{[^,]+, [^,]+}}} ; [ DW_TAG_variable ] [bf]
+// CHECK: [[BFLOAT:![0-9]*]], {{[^,]+, [^,]+}}} ; [ DW_TAG_variable ] [bf]
 // CHECK: [[BFLOAT]] = {{.*}} ; [ DW_TAG_typedef ] [bar<float>] [line 42
 x::bar<float> bf;
 
 using
-// CHECK: metadata [[NARF:![0-9]*]], {{[^,]+, [^,]+}}} ; [ DW_TAG_variable ] [n]
+// CHECK: [[NARF:![0-9]*]], {{[^,]+, [^,]+}}} ; [ DW_TAG_variable ] [n]
 # 142
 narf // CHECK: [[NARF]] = {{.*}} ; [ DW_TAG_typedef ] [narf] [line 142
 = int;
diff --git a/test/CodeGenCXX/debug-info-artificial-arg.cpp b/test/CodeGenCXX/debug-info-artificial-arg.cpp
index a558d20..9eb3c6f 100644
--- a/test/CodeGenCXX/debug-info-artificial-arg.cpp
+++ b/test/CodeGenCXX/debug-info-artificial-arg.cpp
@@ -22,8 +22,8 @@
   A reallyA (500);
 }
 
-// CHECK: ![[CLASSTYPE:.*]] = {{.*}}, metadata !"_ZTS1A"} ; [ DW_TAG_class_type ] [A]
+// CHECK: ![[CLASSTYPE:.*]] = {{.*}}, !"_ZTS1A"} ; [ DW_TAG_class_type ] [A]
 // CHECK: ![[ARTARG:.*]] = {{.*}} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [artificial] [from _ZTS1A]
-// CHECK: metadata !"_ZTS1A", {{.*}} ; [ DW_TAG_subprogram ] [line 12] [public] [A]
-// CHECK: metadata [[FUNCTYPE:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
-// CHECK: [[FUNCTYPE]] = metadata !{null, metadata ![[ARTARG]], metadata !{{.*}}, metadata !{{.*}}}
+// CHECK: !"_ZTS1A", {{.*}} ; [ DW_TAG_subprogram ] [line 12] [public] [A]
+// CHECK: [[FUNCTYPE:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: [[FUNCTYPE]] = !{null, ![[ARTARG]], !{{.*}}, !{{.*}}}
diff --git a/test/CodeGenCXX/debug-info-class.cpp b/test/CodeGenCXX/debug-info-class.cpp
index 5da5321..55d5653 100644
--- a/test/CodeGenCXX/debug-info-class.cpp
+++ b/test/CodeGenCXX/debug-info-class.cpp
@@ -94,29 +94,29 @@
 // CHECK: DW_TAG_class_type ] [bar]
 // CHECK: DW_TAG_union_type ] [baz]
 // CHECK: DW_TAG_class_type ] [B] {{.*}} [def]
-// CHECK: metadata !"0xd\00_vptr$B\00{{.*}}\0064", {{.*}} ; [ DW_TAG_member ]
+// CHECK: !"0xd\00_vptr$B\00{{.*}}\0064", {{.*}} ; [ DW_TAG_member ]
 
-// CHECK: [[C:![0-9]*]] = {{.*}} metadata [[C_MEM:![0-9]*]], metadata !"_ZTS1C", null, metadata !"_ZTS1C"} ; [ DW_TAG_structure_type ] [C] {{.*}} [def]
-// CHECK: [[C_MEM]] = metadata !{metadata [[C_VPTR:![0-9]*]], metadata [[C_S:![0-9]*]], metadata [[C_DTOR:![0-9]*]]}
+// CHECK: [[C:![0-9]*]] = {{.*}} [[C_MEM:![0-9]*]], !"_ZTS1C", null, !"_ZTS1C"} ; [ DW_TAG_structure_type ] [C] {{.*}} [def]
+// CHECK: [[C_MEM]] = !{[[C_VPTR:![0-9]*]], [[C_S:![0-9]*]], [[C_DTOR:![0-9]*]]}
 // CHECK: [[C_VPTR]] = {{.*}} ; [ DW_TAG_member ] [_vptr$C] {{.*}} [artificial]
 // CHECK: [[C_S]] = {{.*}} ; [ DW_TAG_member ] [s] {{.*}} [static] [from int]
 // CHECK: [[C_DTOR]] = {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [~C]
 
-// CHECK: null, null, null, metadata !"_ZTS1D"} ; [ DW_TAG_structure_type ] [D] {{.*}} [decl]
-// CHECK: null, null, null, metadata !"_ZTS1E"} ; [ DW_TAG_structure_type ] [E] {{.*}} [decl]
-// CHECK: [[F:![0-9]*]] = {{.*}} null, null, null, metadata !"_ZTS1F"} ; [ DW_TAG_structure_type ] [F] {{.*}} [decl]
+// CHECK: null, null, null, !"_ZTS1D"} ; [ DW_TAG_structure_type ] [D] {{.*}} [decl]
+// CHECK: null, null, null, !"_ZTS1E"} ; [ DW_TAG_structure_type ] [E] {{.*}} [decl]
+// CHECK: [[F:![0-9]*]] = {{.*}} null, null, null, !"_ZTS1F"} ; [ DW_TAG_structure_type ] [F] {{.*}} [decl]
 
-// CHECK: null, null, null, metadata !"_ZTS1G"} ; [ DW_TAG_structure_type ] [G] {{.*}} [decl]
-// CHECK: metadata [[G_INNER_MEM:![0-9]*]], null, null, metadata !"_ZTSN1G5innerE"} ; [ DW_TAG_structure_type ] [inner] [line 50, {{.*}} [def]
-// CHECK: [[G_INNER_MEM]] = metadata !{metadata [[G_INNER_I:![0-9]*]]}
+// CHECK: null, null, null, !"_ZTS1G"} ; [ DW_TAG_structure_type ] [G] {{.*}} [decl]
+// CHECK: [[G_INNER_MEM:![0-9]*]], null, null, !"_ZTSN1G5innerE"} ; [ DW_TAG_structure_type ] [inner] [line 50, {{.*}} [def]
+// CHECK: [[G_INNER_MEM]] = !{[[G_INNER_I:![0-9]*]]}
 // CHECK: [[G_INNER_I]] = {{.*}} ; [ DW_TAG_member ] [j] {{.*}} [from int]
 
 // CHECK: ; [ DW_TAG_structure_type ] [A]
 // CHECK: HdrSize
 // CHECK: ; [ DW_TAG_structure_type ] [I] {{.*}} [def]
 //
-// CHECK: metadata !"_ZTS1D", {{.*}}, metadata [[D_FUNC_DECL:![0-9]*]], metadata {{![0-9]*}}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
-// CHECK: [[D_FUNC_DECL]] = metadata !{metadata !"0x2e\00func\00{{.*}}\000\00{{[0-9]+}}"{{.*}}, metadata !"_ZTS1D", {{.*}}, null} ; [ DW_TAG_subprogram ] {{.*}} [func]
+// CHECK: !"_ZTS1D", {{.*}}, [[D_FUNC_DECL:![0-9]*]], {{![0-9]*}}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
+// CHECK: [[D_FUNC_DECL]] = !{!"0x2e\00func\00{{.*}}\000\00{{[0-9]+}}"{{.*}}, !"_ZTS1D", {{.*}}, null} ; [ DW_TAG_subprogram ] {{.*}} [func]
 
-// CHECK: ![[EXCEPTLOC]] = metadata !{i32 84,
-// CHECK: ![[RETLOC]] = metadata !{i32 83,
+// CHECK: ![[EXCEPTLOC]] = !MDLocation(line: 84,
+// CHECK: ![[RETLOC]] = !MDLocation(line: 83,
diff --git a/test/CodeGenCXX/debug-info-cxx1y.cpp b/test/CodeGenCXX/debug-info-cxx1y.cpp
index 5e5741a..261f965 100644
--- a/test/CodeGenCXX/debug-info-cxx1y.cpp
+++ b/test/CodeGenCXX/debug-info-cxx1y.cpp
@@ -1,13 +1,13 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm-only -std=c++14 -emit-llvm -g %s -o - | FileCheck %s
 
-// CHECK: [[EMPTY:![0-9]*]] = metadata !{}
-// CHECK: \00foo\00{{.*}}, metadata [[EMPTY]], {{.*}}} ; [ DW_TAG_structure_type ]
+// CHECK: [[EMPTY:![0-9]*]] = !{}
+// CHECK: \00foo\00{{.*}}, [[EMPTY]], {{.*}}} ; [ DW_TAG_structure_type ]
 // FIXME: The context of this definition should be the CU/file scope, not the class.
-// CHECK: metadata !"_ZTS3foo", metadata [[SUBROUTINE_TYPE:![0-9]*]], {{.*}}, metadata [[FUNC_DECL:![0-9]*]], metadata {{![0-9]*}}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
-// CHECK: [[SUBROUTINE_TYPE]] = {{.*}}, metadata [[TYPE_LIST:![0-9]*]],
-// CHECK: [[TYPE_LIST]] = metadata !{metadata [[INT:![0-9]*]]}
+// CHECK: !"_ZTS3foo", [[SUBROUTINE_TYPE:![0-9]*]], {{.*}}, [[FUNC_DECL:![0-9]*]], {{![0-9]*}}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
+// CHECK: [[SUBROUTINE_TYPE]] = {{.*}}, [[TYPE_LIST:![0-9]*]],
+// CHECK: [[TYPE_LIST]] = !{[[INT:![0-9]*]]}
 // CHECK: [[INT]] = {{.*}} ; [ DW_TAG_base_type ] [int]
-// CHECK: [[FUNC_DECL]] = {{.*}}, metadata !"_ZTS3foo", metadata [[SUBROUTINE_TYPE]], {{.*}}} ; [ DW_TAG_subprogram ] {{.*}} [func]
+// CHECK: [[FUNC_DECL]] = {{.*}}, !"_ZTS3foo", [[SUBROUTINE_TYPE]], {{.*}}} ; [ DW_TAG_subprogram ] {{.*}} [func]
 
 struct foo {
   static auto func();
diff --git a/test/CodeGenCXX/debug-info-decl-nested.cpp b/test/CodeGenCXX/debug-info-decl-nested.cpp
index 3b36ce5..95d32c4 100644
--- a/test/CodeGenCXX/debug-info-decl-nested.cpp
+++ b/test/CodeGenCXX/debug-info-decl-nested.cpp
@@ -21,7 +21,7 @@
   OuterClass(const Foo *); // line 10
 };
 OuterClass::InnerClass OuterClass::theInnerClass; // This toplevel decl causes InnerClass to be generated.
-// CHECK0: metadata !"0x2e\00OuterClass\00{{.*}}\00[[@LINE+1]]"{{.*}}, metadata ![[DECL]], metadata {{![0-9]+}}} ; [ DW_TAG_subprogram ] [line [[@LINE+1]]] [def] [OuterClass]
+// CHECK0: !"0x2e\00OuterClass\00{{.*}}\00[[@LINE+1]]"{{.*}}, ![[DECL]], {{![0-9]+}}} ; [ DW_TAG_subprogram ] [line [[@LINE+1]]] [def] [OuterClass]
 OuterClass::OuterClass(const Foo *meta) { } // line 13
 
 
@@ -37,7 +37,7 @@
     InnerClass1();
   } theInnerClass1;
 // CHECK1: [[DECL:[0-9]+]] = {{.*}} ; [ DW_TAG_subprogram ] [line [[@LINE+2]]] [Bar]
-// CHECK1: metadata !"0x2e\00Bar\00{{.*}}\00[[@LINE+4]]"{{.*}}, metadata ![[DECL]], metadata {{![0-9]+}}} ; [ DW_TAG_subprogram ] [line [[@LINE+4]]] [def] [Bar]
+// CHECK1: !"0x2e\00Bar\00{{.*}}\00[[@LINE+4]]"{{.*}}, ![[DECL]], {{![0-9]+}}} ; [ DW_TAG_subprogram ] [line [[@LINE+4]]] [def] [Bar]
   void Bar(const Foo1 *);
 };
 OuterClass1::InnerClass1 OuterClass1::theInnerClass1;
@@ -58,5 +58,5 @@
   ~OuterClass2(); // line 10
 };
 OuterClass2::InnerClass2 OuterClass2::theInnerClass2;
-// CHECK2: metadata !"0x2e\00~OuterClass2\00{{.*}}\00[[@LINE+1]]"{{.*}}, metadata ![[DECL]], metadata {{.*}}} ; [ DW_TAG_subprogram ] [line [[@LINE+1]]] [def] [~OuterClass2]
+// CHECK2: !"0x2e\00~OuterClass2\00{{.*}}\00[[@LINE+1]]"{{.*}}, ![[DECL]], {{.*}}} ; [ DW_TAG_subprogram ] [line [[@LINE+1]]] [def] [~OuterClass2]
 OuterClass2::~OuterClass2() { }
diff --git a/test/CodeGenCXX/debug-info-enum-class.cpp b/test/CodeGenCXX/debug-info-enum-class.cpp
index cfa9611..28ffce0 100644
--- a/test/CodeGenCXX/debug-info-enum-class.cpp
+++ b/test/CodeGenCXX/debug-info-enum-class.cpp
@@ -29,10 +29,10 @@
 
 namespace test2 {
 // FIXME: this should just be a declaration under -fno-standalone-debug
-// CHECK: metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST2:![0-9]*]], {{.*}}, metadata [[TEST_ENUMS:![0-9]*]], null, null, metadata !"_ZTSN5test21EE"} ; [ DW_TAG_enumeration_type ] [E]
+// CHECK:  !"0x4\00{{.*}}", {{[^,]*}}, [[TEST2:![0-9]*]], {{.*}}, [[TEST_ENUMS:![0-9]*]], null, null, !"_ZTSN5test21EE"} ; [ DW_TAG_enumeration_type ] [E]
 // CHECK: [[TEST2]] = {{.*}} ; [ DW_TAG_namespace ] [test2]
-// CHECK: [[TEST_ENUMS]] = metadata !{metadata [[TEST_E:![0-9]*]]}
-// CHECK: [[TEST_E]] = metadata !{metadata !"0x28\00e\000"} ; [ DW_TAG_enumerator ] [e :: 0]
+// CHECK: [[TEST_ENUMS]] = !{[[TEST_E:![0-9]*]]}
+// CHECK: [[TEST_E]] = !{!"0x28\00e\000"} ; [ DW_TAG_enumerator ] [e :: 0]
 enum E : int;
 void func(E *) {
 }
@@ -41,7 +41,7 @@
 
 namespace test3 {
 // FIXME: this should just be a declaration under -fno-standalone-debug
-// CHECK: metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST3:![0-9]*]], {{.*}}, metadata [[TEST_ENUMS]], null, null, metadata !"_ZTSN5test31EE"} ; [ DW_TAG_enumeration_type ] [E]
+// CHECK:  !"0x4\00{{.*}}", {{[^,]*}}, [[TEST3:![0-9]*]], {{.*}}, [[TEST_ENUMS]], null, null, !"_ZTSN5test31EE"} ; [ DW_TAG_enumeration_type ] [E]
 // CHECK: [[TEST3]] = {{.*}} ; [ DW_TAG_namespace ] [test3]
 enum E : int { e };
 void func(E *) {
@@ -49,7 +49,7 @@
 }
 
 namespace test4 {
-// CHECK: metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST4:![0-9]*]], {{.*}}, metadata [[TEST_ENUMS]], null, null, metadata !"_ZTSN5test41EE"} ; [ DW_TAG_enumeration_type ] [E]
+// CHECK:  !"0x4\00{{.*}}", {{[^,]*}}, [[TEST4:![0-9]*]], {{.*}}, [[TEST_ENUMS]], null, null, !"_ZTSN5test41EE"} ; [ DW_TAG_enumeration_type ] [E]
 // CHECK: [[TEST4]] = {{.*}} ; [ DW_TAG_namespace ] [test4]
 enum E : int;
 void f1(E *) {
@@ -62,7 +62,7 @@
 // CHECK: ; [ DW_TAG_enumeration_type ] [D] [line 6, size 16, align 16, offset 0] [decl] [from ]
 
 namespace test5 {
-// CHECK: metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST5:![0-9]*]], {{.*}}, null, null, null, metadata !"_ZTSN5test51EE"} ; [ DW_TAG_enumeration_type ] [E]
+// CHECK:  !"0x4\00{{.*}}", {{[^,]*}}, [[TEST5:![0-9]*]], {{.*}}, null, null, null, !"_ZTSN5test51EE"} ; [ DW_TAG_enumeration_type ] [E]
 // CHECK: [[TEST5]] = {{.*}} ; [ DW_TAG_namespace ] [test5]
 enum E : int;
 void f1(E *) {
diff --git a/test/CodeGenCXX/debug-info-enum.cpp b/test/CodeGenCXX/debug-info-enum.cpp
index 9aa2d1b..954f6f6 100644
--- a/test/CodeGenCXX/debug-info-enum.cpp
+++ b/test/CodeGenCXX/debug-info-enum.cpp
@@ -1,13 +1,13 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -g %s -o - | FileCheck %s
 
-// CHECK: metadata !"0x11\00{{.*}}", {{[^,]*}}, metadata [[ENUMS:![0-9]*]], {{.*}}} ; [ DW_TAG_compile_unit ]
-// CHECK: [[ENUMS]] = metadata !{metadata [[E1:![0-9]*]], metadata [[E2:![0-9]*]], metadata [[E3:![0-9]*]]}
+// CHECK: !"0x11\00{{.*}}", {{[^,]*}}, [[ENUMS:![0-9]*]], {{.*}}} ; [ DW_TAG_compile_unit ]
+// CHECK: [[ENUMS]] = !{[[E1:![0-9]*]], [[E2:![0-9]*]], [[E3:![0-9]*]]}
 
 namespace test1 {
-// CHECK: [[E1]] = metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST1:![0-9]*]], {{.*}}, metadata [[TEST1_ENUMS:![0-9]*]], null, null, metadata !"_ZTSN5test11eE"} ; [ DW_TAG_enumeration_type ] [e]
+// CHECK: [[E1]] = !{!"0x4\00{{.*}}", {{[^,]*}}, [[TEST1:![0-9]*]], {{.*}}, [[TEST1_ENUMS:![0-9]*]], null, null, !"_ZTSN5test11eE"} ; [ DW_TAG_enumeration_type ] [e]
 // CHECK: [[TEST1]] = {{.*}} ; [ DW_TAG_namespace ] [test1]
-// CHECK: [[TEST1_ENUMS]] = metadata !{metadata [[TEST1_E:![0-9]*]]}
-// CHECK: [[TEST1_E]] = metadata !{metadata !"0x28\00E\000"} ; [ DW_TAG_enumerator ] [E :: 0]
+// CHECK: [[TEST1_ENUMS]] = !{[[TEST1_E:![0-9]*]]}
+// CHECK: [[TEST1_E]] = !{!"0x28\00E\000"} ; [ DW_TAG_enumerator ] [E :: 0]
 enum e { E };
 void foo() {
   int v = E;
@@ -16,7 +16,7 @@
 
 namespace test2 {
 // rdar://8195980
-// CHECK: [[E2]] = metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST2:![0-9]*]], {{.*}}, metadata [[TEST1_ENUMS]], null, null, metadata !"_ZTSN5test21eE"} ; [ DW_TAG_enumeration_type ] [e]
+// CHECK: [[E2]] = !{!"0x4\00{{.*}}", {{[^,]*}}, [[TEST2:![0-9]*]], {{.*}}, [[TEST1_ENUMS]], null, null, !"_ZTSN5test21eE"} ; [ DW_TAG_enumeration_type ] [e]
 // CHECK: [[TEST2]] = {{.*}} ; [ DW_TAG_namespace ] [test2]
 enum e { E };
 bool func(int i) {
@@ -25,10 +25,10 @@
 }
 
 namespace test3 {
-// CHECK: [[E3]] = metadata !{metadata !"0x4\00{{.*}}", {{[^,]*}}, metadata [[TEST3:![0-9]*]], {{.*}}, metadata [[TEST3_ENUMS:![0-9]*]], null, null, metadata !"_ZTSN5test31eE"} ; [ DW_TAG_enumeration_type ] [e]
+// CHECK: [[E3]] = !{!"0x4\00{{.*}}", {{[^,]*}}, [[TEST3:![0-9]*]], {{.*}}, [[TEST3_ENUMS:![0-9]*]], null, null, !"_ZTSN5test31eE"} ; [ DW_TAG_enumeration_type ] [e]
 // CHECK: [[TEST3]] = {{.*}} ; [ DW_TAG_namespace ] [test3]
-// CHECK: [[TEST3_ENUMS]] = metadata !{metadata [[TEST3_E:![0-9]*]]}
-// CHECK: [[TEST3_E]] = metadata !{metadata !"0x28\00E\00-1"} ; [ DW_TAG_enumerator ] [E :: -1]
+// CHECK: [[TEST3_ENUMS]] = !{[[TEST3_E:![0-9]*]]}
+// CHECK: [[TEST3_E]] = !{!"0x28\00E\00-1"} ; [ DW_TAG_enumerator ] [E :: -1]
 enum e { E = -1 };
 void func() {
   e x;
diff --git a/test/CodeGenCXX/debug-info-flex-member.cpp b/test/CodeGenCXX/debug-info-flex-member.cpp
index 7f54415..bc501c0 100644
--- a/test/CodeGenCXX/debug-info-flex-member.cpp
+++ b/test/CodeGenCXX/debug-info-flex-member.cpp
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s
 
-// CHECK: metadata !{metadata !"0x21\000\00-1"}        ; [ DW_TAG_subrange_type ]
+// CHECK:  !"0x21\000\00-1"}        ; [ DW_TAG_subrange_type ]
 
 struct StructName {
   int member[];
diff --git a/test/CodeGenCXX/debug-info-function-context.cpp b/test/CodeGenCXX/debug-info-function-context.cpp
index d58f7c6..a6c5a11 100644
--- a/test/CodeGenCXX/debug-info-function-context.cpp
+++ b/test/CodeGenCXX/debug-info-function-context.cpp
@@ -25,12 +25,12 @@
 // functions that belong to the namespace have it as a context, and the global
 // function has the file as a context.
 
-// CHECK: metadata !"0x2e\00member_function\00{{.*}}", metadata !{{[0-9]+}}, metadata !"_ZTS1C"{{.*}} [ DW_TAG_subprogram ] [line 11] [def] [member_function]
+// CHECK: !"0x2e\00member_function\00{{.*}}", !{{[0-9]+}}, !"_ZTS1C"{{.*}} [ DW_TAG_subprogram ] [line 11] [def] [member_function]
 
-// CHECK: metadata !"0x2e\00static_member_function\00{{.*}}", metadata !{{[0-9]+}}, metadata !"_ZTS1C"{{.*}}  [ DW_TAG_subprogram ] [line 13] [def] [static_member_function]
+// CHECK: !"0x2e\00static_member_function\00{{.*}}", !{{[0-9]+}}, !"_ZTS1C"{{.*}}  [ DW_TAG_subprogram ] [line 13] [def] [static_member_function]
 
-// CHECK: metadata !"0x2e\00global_function\00{{[^,]+}}", metadata !{{[0-9]+}}, metadata [[FILE:![0-9]*]]{{.*}}  [ DW_TAG_subprogram ] [line 17] [def] [global_function]
+// CHECK: !"0x2e\00global_function\00{{[^,]+}}", !{{[0-9]+}}, [[FILE:![0-9]*]]{{.*}}  [ DW_TAG_subprogram ] [line 17] [def] [global_function]
 // CHECK: [[FILE]] = {{.*}} [ DW_TAG_file_type ]
 
-// CHECK: metadata !"0x2e\00global_namespace_function\00{{[^,]+}}", metadata !{{[0-9]+}}, metadata [[NS:![0-9]*]]{{.*}} [ DW_TAG_subprogram ] [line 20] [def] [global_namespace_function]
+// CHECK: !"0x2e\00global_namespace_function\00{{[^,]+}}", !{{[0-9]+}}, [[NS:![0-9]*]]{{.*}} [ DW_TAG_subprogram ] [line 20] [def] [global_namespace_function]
 // CHECK: [[NS]] = {{.*}} [ DW_TAG_namespace ] [ns] [line 19]
diff --git a/test/CodeGenCXX/debug-info-global.cpp b/test/CodeGenCXX/debug-info-global.cpp
index 10900f3..5fc61c7 100644
--- a/test/CodeGenCXX/debug-info-global.cpp
+++ b/test/CodeGenCXX/debug-info-global.cpp
@@ -10,10 +10,10 @@
   return ns::cnst + ns::cnst;
 }
 
-// CHECK: metadata !"0x11\00{{.*}}"{{.*}}, metadata [[GLOBALS:![0-9]*]], metadata {{![0-9]*}}} ; [ DW_TAG_compile_unit ]
+// CHECK: !"0x11\00{{.*}}"{{.*}}, [[GLOBALS:![0-9]*]], {{![0-9]*}}} ; [ DW_TAG_compile_unit ]
 
-// CHECK: [[GLOBALS]] = metadata !{metadata [[CNST:![0-9]*]]}
+// CHECK: [[GLOBALS]] = !{[[CNST:![0-9]*]]}
 
-// CHECK: [[CNST]] = metadata !{metadata !"0x34\00cnst\00{{.*}}", metadata [[NS:![0-9]*]], {{[^,]+, [^,]+, [^,]+, [^,]+}}} ; [ DW_TAG_variable ] [cnst]
+// CHECK: [[CNST]] = !{!"0x34\00cnst\00{{.*}}", [[NS:![0-9]*]], {{[^,]+, [^,]+, [^,]+, [^,]+}}} ; [ DW_TAG_variable ] [cnst]
 // CHECK: [[NS]] = {{.*}}; [ DW_TAG_namespace ] [ns]
 
diff --git a/test/CodeGenCXX/debug-info-globalinit.cpp b/test/CodeGenCXX/debug-info-globalinit.cpp
index 30c8bfc..efba958 100644
--- a/test/CodeGenCXX/debug-info-globalinit.cpp
+++ b/test/CodeGenCXX/debug-info-globalinit.cpp
@@ -34,5 +34,5 @@
 // CHECK-NOT: __cxx_global_var_init
 // CHECK: store i32 %[[C2]], i32* @_ZL1k, align 4, !dbg
 // 
-// CHECK: ![[LINE]] = metadata !{i32 13, i32
-// CHECK: ![[LINE2]] = metadata !{i32 15, i32
+// CHECK: ![[LINE]] = !MDLocation(line: 13,
+// CHECK: ![[LINE2]] = !MDLocation(line: 15,
diff --git a/test/CodeGenCXX/debug-info-line-if.cpp b/test/CodeGenCXX/debug-info-line-if.cpp
index bd96377..d0205af 100644
--- a/test/CodeGenCXX/debug-info-line-if.cpp
+++ b/test/CodeGenCXX/debug-info-line-if.cpp
@@ -48,8 +48,8 @@
   // CHECK: br label
   // CHECK: br label {{.*}}, !dbg [[DBG4:!.*]]
 
-  // CHECK: [[DBG1]] = metadata !{i32 100, i32 0, metadata !{{.*}}, null}
-  // CHECK: [[DBG2]] = metadata !{i32 200, i32 0, metadata !{{.*}}, null}
-  // CHECK: [[DBG3]] = metadata !{i32 300, i32 0, metadata !{{.*}}, null}
-  // CHECK: [[DBG4]] = metadata !{i32 401, i32 0, metadata !{{.*}}, null}
+  // CHECK: [[DBG1]] = !MDLocation(line: 100, scope: !{{.*}})
+  // CHECK: [[DBG2]] = !MDLocation(line: 200, scope: !{{.*}})
+  // CHECK: [[DBG3]] = !MDLocation(line: 300, scope: !{{.*}})
+  // CHECK: [[DBG4]] = !MDLocation(line: 401, scope: !{{.*}})
 }
diff --git a/test/CodeGenCXX/debug-info-line.cpp b/test/CodeGenCXX/debug-info-line.cpp
new file mode 100644
index 0000000..98b99d5
--- /dev/null
+++ b/test/CodeGenCXX/debug-info-line.cpp
@@ -0,0 +1,324 @@
+// RUN: %clang_cc1 -w -gline-tables-only -std=c++11 -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -w -gline-tables-only -std=c++11 -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - -triple i686-linux-gnu | FileCheck %s
+
+// XFAIL: win32
+
+int &src();
+int *sink();
+extern "C" __complex float complex_src();
+extern "C" __complex float *complex_sink();
+
+// CHECK-LABEL: define
+void f1() {
+  *sink()
+  // CHECK: store {{.*}}, !dbg [[DBG_F1:!.*]]
+#line 100
+      = //
+      src();
+}
+
+struct foo {
+  int i;
+  int &j;
+  __complex float k;
+  foo();
+};
+
+// CHECK-LABEL: define
+foo::foo()
+    :
+#line 200
+      i // CHECK: store i32 {{.*}} !dbg [[DBG_FOO_VALUE:!.*]]
+      (src()),
+      j // CHECK: store i32* {{.*}} !dbg [[DBG_FOO_REF:!.*]]
+      (src()),
+      k // CHECK: store float {{.*}} !dbg [[DBG_FOO_COMPLEX:!.*]]
+      (complex_src()) {
+}
+
+// CHECK-LABEL: define {{.*}}f2{{.*}}
+void f2() {
+  // CHECK: store float {{.*}} !dbg [[DBG_F2:!.*]]
+  *complex_sink()
+#line 300
+      = //
+      complex_src();
+}
+
+// CHECK-LABEL: define
+void f3() {
+  // CHECK: store float {{.*}} !dbg [[DBG_F3:!.*]]
+  *complex_sink()
+#line 400
+      += //
+      complex_src();
+}
+
+// CHECK-LABEL: define
+void f4() {
+#line 500
+  auto x // CHECK: store {{.*}} !dbg [[DBG_F4:!.*]]
+      = src();
+}
+
+// CHECK-LABEL: define
+void f5() {
+#line 600
+  auto x // CHECK: store float {{.*}} !dbg [[DBG_F5:!.*]]
+      = complex_src();
+}
+
+struct agg { int i; };
+agg agg_src();
+
+// CHECK-LABEL: define
+void f6() {
+  agg x;
+  // CHECK: call void @llvm.memcpy{{.*}} !dbg [[DBG_F6:!.*]]
+  x
+#line 700
+      = //
+      agg_src();
+}
+
+// CHECK-LABEL: define
+void f7() {
+  int *src1();
+  int src2();
+#line 800
+  int x = ( // CHECK: load {{.*}} !dbg [[DBG_F7:!.*]]
+      src1())[src2()];
+}
+
+// CHECK-LABEL: define
+void f8() {
+  int src1[1];
+  int src2();
+#line 900
+  int x = ( // CHECK: load {{.*}} !dbg [[DBG_F8:!.*]]
+      src1)[src2()];
+}
+
+// CHECK-LABEL: define
+void f9(int i) {
+  int src1[1][i];
+  int src2();
+#line 1000
+  auto x = ( // CHECK: getelementptr {{.*}} !dbg [[DBG_F9:!.*]]
+      src1)[src2()];
+}
+
+inline void *operator new(decltype(sizeof(1)), void *p) noexcept { return p; }
+
+// CHECK-LABEL: define
+void f10() {
+  void *void_src();
+  (
+    // CHECK: store {{.*}} !dbg [[DBG_F10_STORE:!.*]]
+#line 1100
+      new (void_src()) int(src()));
+}
+
+// noexcept just to simplify the codegen a bit
+void fn() noexcept(true);
+
+struct bar {
+  bar();
+  // noexcept(false) to convolute the global dtor
+  ~bar() noexcept(false);
+};
+// global ctor cleanup
+// CHECK-LABEL: define
+// CHECK: invoke{{ }}
+// CHECK: invoke{{ }}
+// CHECK:   to label {{.*}}, !dbg [[DBG_GLBL_CTOR_B:!.*]]
+
+// terminate caller
+// CHECK-LABEL: define
+
+// global dtor cleanup
+// CHECK-LABEL: define
+// CHECK: invoke{{ }}
+// CHECK: invoke{{ }}
+// CHECK:   to label {{.*}}, !dbg [[DBG_GLBL_DTOR_B:!.*]]
+#line 1200
+bar b[1] = { //
+    (fn(),   //
+     bar())};
+
+// CHECK-LABEL: define
+__complex double f11() {
+  __complex double f;
+// CHECK: store {{.*}} !dbg [[DBG_F11:!.*]]
+#line 1300
+  return f;
+}
+
+// CHECK-LABEL: define
+void f12() {
+  int f12_1();
+  void f12_2(int = f12_1());
+// CHECK: call {{(signext )?}}i32 {{.*}} !dbg [[DBG_F12:!.*]]
+#line 1400
+  f12_2();
+}
+
+// CHECK-LABEL: define
+void f13() {
+// CHECK: call {{.*}} !dbg [[DBG_F13:!.*]]
+#define F13_IMPL 1, src()
+  1,
+#line 1500
+  F13_IMPL;
+}
+
+struct f14_impl {
+  f14_impl(int);
+};
+
+// CHECK-LABEL: define
+struct f14_use {
+// CHECK: call {{.*}}f14_impl{{.*}}, !dbg [[DBG_F14_CTOR_CALL:![0-9]*]]
+#line 1600
+  f14_impl v{//
+             1};
+  f14_use();
+};
+
+f14_use::f14_use() = default;
+
+// CHECK-LABEL: define
+// CHECK-LABEL: define
+void func(foo);
+void f15(foo *f) {
+  func(
+// CHECK: getelementptr {{.*}}, !dbg [[DBG_F15:![0-9]*]]
+#line 1700
+      f[3]);
+}
+
+// CHECK-LABEL: define
+void f16(__complex float f) {
+  __complex float g = //
+// CHECK: add {{.*}}, !dbg [[DBG_F16:![0-9]*]]
+#line 1800
+      f + 1;
+}
+
+// CHECK-LABEL: define
+void f17(int *x) {
+  1,
+// CHECK: getelementptr {{.*}}, !dbg [[DBG_F17:![0-9]*]]
+#line 1900
+      x[1];
+}
+
+// CHECK-LABEL: define
+void f18(int a, int b) {
+// CHECK: icmp {{.*}}, !dbg [[DBG_F18_1:![0-9]*]]
+// CHECK: br {{.*}}, !dbg [[DBG_F18_2:![0-9]*]]
+#line 2000
+  if (a  //
+      && //
+      b)
+    ;
+}
+
+// CHECK-LABEL: define
+void f19(int a, int b) {
+// CHECK: icmp {{.*}}, !dbg [[DBG_F19_1:![0-9]*]]
+// CHECK: br {{.*}}, !dbg [[DBG_F19_2:![0-9]*]]
+#line 2100
+  if (a  //
+      || //
+      b)
+    ;
+}
+
+// CHECK-LABEL: define
+void f20(int a, int b, int c) {
+// CHECK: icmp {{.*}}, !dbg [[DBG_F20_1:![0-9]*]]
+// FIXME: Conditional operator's exprloc should be the '?' not the start of the
+// expression, then this would go in the right place. (but adding getExprLoc to
+// the ConditionalOperator breaks the ARC migration tool - need to investigate
+// further).
+// CHECK: br {{.*}}, !dbg [[DBG_F20_1]]
+#line 2200
+  if (a  //
+      ? //
+      b : c)
+    ;
+}
+
+// CHECK-LABEL: define
+int f21_a(int = 0);
+void f21_b(int = f21_a());
+void f21() {
+// CHECK: call {{.*}}f21_b{{.*}}, !dbg [[DBG_F21:![0-9]*]]
+#line 2300
+  f21_b();
+}
+
+// CHECK-LABEL: define
+struct f22_dtor {
+  ~f22_dtor();
+};
+void f22() {
+  {
+    f22_dtor f;
+    src();
+// CHECK: invoke {{.*}}src
+// CHECK: call {{.*}}, !dbg [[DBG_F22:![0-9]*]]
+// CHECK: call {{.*}}, !dbg [[DBG_F22]]
+#line 2400
+  }
+}
+
+// CHECK-LABEL: define
+struct f23_struct {
+};
+f23_struct f23_a();
+void f23_b(f23_struct = f23_a());
+void f23() {
+// CHECK: call {{.*}}f23_a{{.*}}, !dbg [[DBG_F23:![0-9]*]]
+#line 2500
+  f23_b();
+}
+
+// CHECK-LABEL: define
+void f24_a(__complex float = complex_src());
+void f24() {
+// CHECK: call {{.*}}complex_src{{.*}}, !dbg [[DBG_F24:![0-9]*]]
+#line 2600
+  f24_a();
+}
+
+// CHECK: [[DBG_F1]] = !MDLocation(line: 100,
+// CHECK: [[DBG_FOO_VALUE]] = !MDLocation(line: 200,
+// CHECK: [[DBG_FOO_REF]] = !MDLocation(line: 202,
+// CHECK: [[DBG_FOO_COMPLEX]] = !MDLocation(line: 204,
+// CHECK: [[DBG_F2]] = !MDLocation(line: 300,
+// CHECK: [[DBG_F3]] = !MDLocation(line: 400,
+// CHECK: [[DBG_F4]] = !MDLocation(line: 500,
+// CHECK: [[DBG_F5]] = !MDLocation(line: 600,
+// CHECK: [[DBG_F6]] = !MDLocation(line: 700,
+// CHECK: [[DBG_F7]] = !MDLocation(line: 800,
+// CHECK: [[DBG_F8]] = !MDLocation(line: 900,
+// CHECK: [[DBG_F9]] = !MDLocation(line: 1000,
+// CHECK: [[DBG_F10_STORE]] = !MDLocation(line: 1100,
+// CHECK: [[DBG_GLBL_CTOR_B]] = !MDLocation(line: 1200,
+// CHECK: [[DBG_GLBL_DTOR_B]] = !MDLocation(line: 1200,
+// CHECK: [[DBG_F11]] = !MDLocation(line: 1300,
+// CHECK: [[DBG_F12]] = !MDLocation(line: 1400,
+// CHECK: [[DBG_F13]] = !MDLocation(line: 1500,
+// CHECK: [[DBG_F14_CTOR_CALL]] = !MDLocation(line: 1600,
+// CHECK: [[DBG_F15]] = !MDLocation(line: 1700,
+// CHECK: [[DBG_F16]] = !MDLocation(line: 1800,
+// CHECK: [[DBG_F17]] = !MDLocation(line: 1900,
+// CHECK: [[DBG_F18_1]] = !MDLocation(line: 2000,
+// CHECK: [[DBG_F18_2]] = !MDLocation(line: 2001,
+// CHECK: [[DBG_F19_1]] = !MDLocation(line: 2100,
+// CHECK: [[DBG_F19_2]] = !MDLocation(line: 2101,
+// CHECK: [[DBG_F20_1]] = !MDLocation(line: 2200,
+// CHECK: [[DBG_F23]] = !MDLocation(line: 2500,
+// CHECK: [[DBG_F24]] = !MDLocation(line: 2600,
diff --git a/test/CodeGenCXX/debug-info-method.cpp b/test/CodeGenCXX/debug-info-method.cpp
index 02b7426..bb69a65 100644
--- a/test/CodeGenCXX/debug-info-method.cpp
+++ b/test/CodeGenCXX/debug-info-method.cpp
@@ -1,14 +1,14 @@
 // RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -std=c++11 -g %s -o - | FileCheck %s
-// CHECK: metadata !"_ZTS1A"} ; [ DW_TAG_class_type ] [A]
-// CHECK: metadata !"{{.*}}\00_ZN1A3fooEiS_3$_0\00{{.*}}", {{.*}} [protected]
+// CHECK: !"_ZTS1A"} ; [ DW_TAG_class_type ] [A]
+// CHECK: !"{{.*}}\00_ZN1A3fooEiS_3$_0\00{{.*}}", {{.*}} [protected]
 // CHECK: ![[THISTYPE:[0-9]+]] = {{.*}} ; [ DW_TAG_pointer_type ] {{.*}} [artificial] [from _ZTS1A]
-// CHECK: DW_TAG_ptr_to_member_type
-// CHECK: {{.*}}metadata ![[MEMFUNTYPE:[0-9]+]], metadata !{{.*}}} ; [ DW_TAG_ptr_to_member_type ] {{.*}} [from ]
-// CHECK: ![[MEMFUNTYPE]] = {{.*}}metadata ![[MEMFUNARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ] {{.*}} [from ]
-// CHECK: ![[MEMFUNARGS]] = {{.*}}, metadata ![[THISTYPE]],
-// CHECK: metadata !"0x101\00\00{{.*}}"{{.*}} DW_TAG_arg_variable
-// CHECK: metadata !"0x101\00\00{{.*}}"{{.*}} DW_TAG_arg_variable
-// CHECK: metadata !"0x101\00\00{{.*}}"{{.*}} DW_TAG_arg_variable
+// CHECK: [ DW_TAG_ptr_to_member_type ] [line {{[0-9]+}}, size {{[1-9][0-9]+}}, align
+// CHECK: {{.*}}![[MEMFUNTYPE:[0-9]+]], !{{.*}}} ; [ DW_TAG_ptr_to_member_type ] {{.*}} [from ]
+// CHECK: ![[MEMFUNTYPE]] = {{.*}}![[MEMFUNARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ] {{.*}} [from ]
+// CHECK: ![[MEMFUNARGS]] = {{.*}}, ![[THISTYPE]],
+// CHECK: !"0x101\00\00{{.*}}"{{.*}} DW_TAG_arg_variable
+// CHECK: !"0x101\00\00{{.*}}"{{.*}} DW_TAG_arg_variable
+// CHECK: !"0x101\00\00{{.*}}"{{.*}} DW_TAG_arg_variable
 union {
   int a;
   float b;
diff --git a/test/CodeGenCXX/debug-info-namespace.cpp b/test/CodeGenCXX/debug-info-namespace.cpp
index c999ce2..60d508b 100644
--- a/test/CodeGenCXX/debug-info-namespace.cpp
+++ b/test/CodeGenCXX/debug-info-namespace.cpp
@@ -55,45 +55,45 @@
 // This should work even if 'i' and 'func' were declarations & not definitions,
 // but it doesn't yet.
 
-// CHECK: [[CU:![0-9]*]] = metadata !{metadata !"0x11\00{{.*}}\001"{{.*}}, metadata [[MODULES:![0-9]*]]} ; [ DW_TAG_compile_unit ]
+// CHECK: [[CU:![0-9]*]] = !{!"0x11\00{{.*}}\001"{{.*}}, [[MODULES:![0-9]*]]} ; [ DW_TAG_compile_unit ]
 // CHECK: [[FOO:![0-9]*]] {{.*}} ; [ DW_TAG_structure_type ] [foo] [line 5, size 0, align 0, offset 0] [decl] [from ]
-// CHECK: [[FOOCPP:![0-9]*]] = metadata !{metadata !"foo.cpp", {{.*}}
-// CHECK: [[NS:![0-9]*]] = metadata !{metadata !"0x39\00B\001", metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]]} ; [ DW_TAG_namespace ] [B] [line 1]
-// CHECK: [[CTXT]] = metadata !{metadata !"0x39\00A\005", metadata [[FILE:![0-9]*]], null} ; [ DW_TAG_namespace ] [A] [line 5]
+// CHECK: [[FOOCPP:![0-9]*]] = !{!"foo.cpp", {{.*}}
+// CHECK: [[NS:![0-9]*]] = !{!"0x39\00B\001", [[FILE2:![0-9]*]], [[CTXT:![0-9]*]]} ; [ DW_TAG_namespace ] [B] [line 1]
+// CHECK: [[CTXT]] = !{!"0x39\00A\005", [[FILE:![0-9]*]], null} ; [ DW_TAG_namespace ] [A] [line 5]
 // CHECK: [[FILE]] {{.*}}debug-info-namespace.cpp"
 // CHECK: [[BAR:![0-9]*]] {{.*}} ; [ DW_TAG_structure_type ] [bar] [line 6, {{.*}}] [decl] [from ]
 // CHECK: [[F1:![0-9]*]] {{.*}} ; [ DW_TAG_subprogram ] [line 4] [def] [f1]
 // CHECK: [[FILE2]]} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]
 // CHECK: [[FUNC:![0-9]*]] {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
 // CHECK: [[FUNC_FWD:![0-9]*]] {{.*}} [ DW_TAG_subprogram ] [line 47] [def] [func_fwd]
-// CHECK: [[I:![0-9]*]] = metadata !{metadata !"0x34\00i\00{{.*}}", metadata [[NS]], {{.*}} ; [ DW_TAG_variable ] [i]
-// CHECK: [[VAR_FWD:![0-9]*]] = metadata !{metadata !"0x34\00var_fwd\00{{.*}}", metadata [[NS]], {{.*}}} ; [ DW_TAG_variable ] [var_fwd] [line 44] [def]
+// CHECK: [[I:![0-9]*]] = !{!"0x34\00i\00{{.*}}", [[NS]], {{.*}} ; [ DW_TAG_variable ] [i]
+// CHECK: [[VAR_FWD:![0-9]*]] = !{!"0x34\00var_fwd\00{{.*}}", [[NS]], {{.*}}} ; [ DW_TAG_variable ] [var_fwd] [line 44] [def]
 
-// CHECK: [[MODULES]] = metadata !{metadata [[M1:![0-9]*]], metadata [[M2:![0-9]*]], metadata [[M3:![0-9]*]], metadata [[M4:![0-9]*]], metadata [[M5:![0-9]*]], metadata [[M6:![0-9]*]], metadata [[M7:![0-9]*]], metadata [[M8:![0-9]*]], metadata [[M9:![0-9]*]], metadata [[M10:![0-9]*]], metadata [[M11:![0-9]*]], metadata [[M12:![0-9]*]], metadata [[M13:![0-9]*]], metadata [[M14:![0-9]*]], metadata [[M15:![0-9]*]], metadata [[M16:![0-9]*]], metadata [[M17:![0-9]*]]}
-// CHECK: [[M1]] = metadata !{metadata !"0x3a\0015\00", metadata [[CTXT]], metadata [[NS]]} ; [ DW_TAG_imported_module ]
-// CHECK: [[M2]] = metadata !{metadata !"0x3a\00{{[0-9]+}}\00", metadata [[CU]], metadata [[CTXT]]} ; [ DW_TAG_imported_module ]
-// CHECK: [[M3]] = metadata !{metadata !"0x8\0019\00E", metadata [[CU]], metadata [[CTXT]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M4]] = metadata !{metadata !"0x3a\0023\00", metadata [[LEX2:![0-9]*]], metadata [[NS]]} ; [ DW_TAG_imported_module ]
-// CHECK: [[LEX2]] = metadata !{metadata !"0xb\00{{[0-9]*}}\000\00{{.*}}", metadata [[FILE2]], metadata [[LEX1:![0-9]+]]} ; [ DW_TAG_lexical_block ]
-// CHECK: [[LEX1]] = metadata !{metadata !"0xb\00{{[0-9]*}}\000\00{{.*}}", metadata [[FILE2]], metadata [[FUNC]]} ; [ DW_TAG_lexical_block ]
-// CHECK: [[M5]] = metadata !{metadata !"0x3a\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[CTXT]]} ; [ DW_TAG_imported_module ]
-// CHECK: [[M6]] = metadata !{metadata !"0x8\0027\00", metadata [[FUNC]], metadata [[FOO:!"_ZTSN1A1B3fooE"]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M7]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[BAR:!"_ZTSN1A1B3barE"]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M8]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[F1]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M9]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[I]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M10]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[BAZ:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[BAZ]] = metadata !{metadata !"0x16\00baz\00{{.*}}", metadata [[FOOCPP]], metadata [[NS]], metadata !"_ZTSN1A1B3barE"} ; [ DW_TAG_typedef ] [baz] {{.*}} [from _ZTSN1A1B3barE]
-// CHECK: [[M11]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00X", metadata [[FUNC]], metadata [[CTXT]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M12]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00Y", metadata [[FUNC]], metadata [[M11]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M13]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[VAR_DECL:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
-// CHECK [[VAR_DECL]] = metadata !{metadata !"0x34\00var_decl\00{{.*}}", metadata [[NS]], {{.*}}} ; [ DW_TAG_variable ] [var_decl] [line 8]
-// CHECK: [[M14]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[FUNC_DECL:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[FUNC_DECL]] = metadata !{metadata !"0x2e\00func_decl\00{{.*}}", metadata [[FOOCPP]], metadata [[NS]], {{.*}}} ; [ DW_TAG_subprogram ] [line 9] [scope 0] [func_decl]
-// CHECK: [[M15]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[VAR_FWD:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M16]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[FUNC]], metadata [[FUNC_FWD:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
-// CHECK: [[M17]] = metadata !{metadata !"0x8\00{{[0-9]+}}\00", metadata [[CTXT]], metadata [[I]]} ; [ DW_TAG_imported_declaration ]
-// CHECK-GMLT: [[CU:![0-9]*]] = metadata !{metadata !"0x11\00{{.*}}\002"{{.*}}, metadata [[MODULES:![0-9]*]]} ; [ DW_TAG_compile_unit ]
-// CHECK-GMLT: [[MODULES]] = metadata !{}
+// CHECK: [[MODULES]] = !{[[M1:![0-9]*]], [[M2:![0-9]*]], [[M3:![0-9]*]], [[M4:![0-9]*]], [[M5:![0-9]*]], [[M6:![0-9]*]], [[M7:![0-9]*]], [[M8:![0-9]*]], [[M9:![0-9]*]], [[M10:![0-9]*]], [[M11:![0-9]*]], [[M12:![0-9]*]], [[M13:![0-9]*]], [[M14:![0-9]*]], [[M15:![0-9]*]], [[M16:![0-9]*]], [[M17:![0-9]*]]}
+// CHECK: [[M1]] = !{!"0x3a\0015\00", [[CTXT]], [[NS]]} ; [ DW_TAG_imported_module ]
+// CHECK: [[M2]] = !{!"0x3a\00{{[0-9]+}}\00", [[CU]], [[CTXT]]} ; [ DW_TAG_imported_module ]
+// CHECK: [[M3]] = !{!"0x8\0019\00E", [[CU]], [[CTXT]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M4]] = !{!"0x3a\0023\00", [[LEX2:![0-9]*]], [[NS]]} ; [ DW_TAG_imported_module ]
+// CHECK: [[LEX2]] = !{!"0xb\00{{[0-9]*}}\000\00{{.*}}", [[FILE2]], [[LEX1:![0-9]+]]} ; [ DW_TAG_lexical_block ]
+// CHECK: [[LEX1]] = !{!"0xb\00{{[0-9]*}}\000\00{{.*}}", [[FILE2]], [[FUNC]]} ; [ DW_TAG_lexical_block ]
+// CHECK: [[M5]] = !{!"0x3a\00{{[0-9]+}}\00", [[FUNC]], [[CTXT]]} ; [ DW_TAG_imported_module ]
+// CHECK: [[M6]] = !{!"0x8\0027\00", [[FUNC]], [[FOO:!"_ZTSN1A1B3fooE"]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M7]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[BAR:!"_ZTSN1A1B3barE"]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M8]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[F1]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M9]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[I]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M10]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[BAZ:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[BAZ]] = !{!"0x16\00baz\00{{.*}}", [[FOOCPP]], [[NS]], !"_ZTSN1A1B3barE"} ; [ DW_TAG_typedef ] [baz] {{.*}} [from _ZTSN1A1B3barE]
+// CHECK: [[M11]] = !{!"0x8\00{{[0-9]+}}\00X", [[FUNC]], [[CTXT]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M12]] = !{!"0x8\00{{[0-9]+}}\00Y", [[FUNC]], [[M11]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M13]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[VAR_DECL:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
+// CHECK [[VAR_DECL]] = !{!"0x34\00var_decl\00{{.*}}", [[NS]], {{.*}}} ; [ DW_TAG_variable ] [var_decl] [line 8]
+// CHECK: [[M14]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[FUNC_DECL:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[FUNC_DECL]] = !{!"0x2e\00func_decl\00{{.*}}", [[FOOCPP]], [[NS]], {{.*}}} ; [ DW_TAG_subprogram ] [line 9] [scope 0] [func_decl]
+// CHECK: [[M15]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[VAR_FWD:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M16]] = !{!"0x8\00{{[0-9]+}}\00", [[FUNC]], [[FUNC_FWD:![0-9]*]]} ; [ DW_TAG_imported_declaration ]
+// CHECK: [[M17]] = !{!"0x8\00{{[0-9]+}}\00", [[CTXT]], [[I]]} ; [ DW_TAG_imported_declaration ]
+// CHECK-GMLT: [[CU:![0-9]*]] = !{!"0x11\00{{.*}}\002"{{.*}}, [[MODULES:![0-9]*]]} ; [ DW_TAG_compile_unit ]
+// CHECK-GMLT: [[MODULES]] = !{}
 
 // CHECK-NOLIMIT: ; [ DW_TAG_structure_type ] [bar] [line 6, {{.*}}] [def] [from ]
 
diff --git a/test/CodeGenCXX/debug-info-ptr-to-member-function.cpp b/test/CodeGenCXX/debug-info-ptr-to-member-function.cpp
new file mode 100644
index 0000000..656e6f4
--- /dev/null
+++ b/test/CodeGenCXX/debug-info-ptr-to-member-function.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 %s -triple x86_64-apple-darwin -g -emit-llvm -o - | FileCheck %s
+
+struct T {
+  int method();
+};
+
+void foo(int (T::*method)()) {}
+
+// A pointer to a member function is a pair of function- and this-pointer.
+// CHECK: [ DW_TAG_ptr_to_member_type ] {{.*}} size 128
diff --git a/test/CodeGenCXX/debug-info-qualifiers.cpp b/test/CodeGenCXX/debug-info-qualifiers.cpp
index 301e315..2655bd9 100644
--- a/test/CodeGenCXX/debug-info-qualifiers.cpp
+++ b/test/CodeGenCXX/debug-info-qualifiers.cpp
@@ -2,25 +2,25 @@
 // Test (r)value and CVR qualifiers on C++11 non-static member functions.
 class A {
 public:
-  // CHECK: metadata !"0x2e\00l\00{{.*}}\00[[@LINE+2]]"{{, [^,]+, [^,]+}}, metadata ![[PLSR:[0-9]+]], {{.*}}[ DW_TAG_subprogram ] [line [[@LINE+2]]] [public] [reference] [l]
+  // CHECK: !"0x2e\00l\00{{.*}}\00[[@LINE+2]]"{{, [^,]+, [^,]+}}, ![[PLSR:[0-9]+]], {{.*}}[ DW_TAG_subprogram ] [line [[@LINE+2]]] [public] [reference] [l]
   // CHECK: ![[PLSR]] ={{.*}}[ DW_TAG_subroutine_type ]{{.*}}[reference]
   void l() const &;
-  // CHECK: ![[ARGS:[0-9]+]] = metadata !{null, metadata ![[THIS:[0-9]+]]}
-  // CHECK: ![[THIS]] = {{.*}} metadata ![[CONST_A:.*]]} ; [ DW_TAG_pointer_type ]
+  // CHECK: ![[ARGS:[0-9]+]] = !{null, ![[THIS:[0-9]+]]}
+  // CHECK: ![[THIS]] = {{.*}} ![[CONST_A:.*]]} ; [ DW_TAG_pointer_type ]
   // CHECK: ![[CONST_A]] = {{.*}} [ DW_TAG_const_type ]
-  // CHECK: metadata !"0x2e\00r\00{{.*}}\00[[@LINE+2]]"{{, [^,]+, [^,]+}}, metadata ![[PRSR:[0-9]+]], {{.*}}[ DW_TAG_subprogram ] [line [[@LINE+2]]] [public] [rvalue reference] [r]
-  // CHECK: ![[PRSR]] ={{.*}}metadata ![[ARGS]], null, null, null}{{.*}}[ DW_TAG_subroutine_type ]{{.*}}[rvalue reference]
+  // CHECK: !"0x2e\00r\00{{.*}}\00[[@LINE+2]]"{{, [^,]+, [^,]+}}, ![[PRSR:[0-9]+]], {{.*}}[ DW_TAG_subprogram ] [line [[@LINE+2]]] [public] [rvalue reference] [r]
+  // CHECK: ![[PRSR]] ={{.*}}![[ARGS]], null, null, null}{{.*}}[ DW_TAG_subroutine_type ]{{.*}}[rvalue reference]
   void r() const &&;
 };
 
 void g() {
   A a;
   // The type of pl is "void (A::*)() const &".
-  // CHECK: metadata ![[PL:[0-9]+]]} ; [ DW_TAG_auto_variable ] [pl] [line [[@LINE+2]]]
-  // CHECK: metadata ![[PLSR]], metadata !"{{.*}}"} ; [ DW_TAG_ptr_to_member_type ]
+  // CHECK: ![[PL:[0-9]+]]} ; [ DW_TAG_auto_variable ] [pl] [line [[@LINE+2]]]
+  // CHECK: ![[PLSR]], !"{{.*}}"} ; [ DW_TAG_ptr_to_member_type ]
   auto pl = &A::l;
 
-  // CHECK: metadata ![[PR:[0-9]+]]} ; [ DW_TAG_auto_variable ] [pr] [line [[@LINE+2]]]
-  // CHECK: metadata ![[PRSR]], metadata !"{{.*}}"} ; [ DW_TAG_ptr_to_member_type ]
+  // CHECK: ![[PR:[0-9]+]]} ; [ DW_TAG_auto_variable ] [pr] [line [[@LINE+2]]]
+  // CHECK: ![[PRSR]], !"{{.*}}"} ; [ DW_TAG_ptr_to_member_type ]
   auto pr = &A::r;
 }
diff --git a/test/CodeGenCXX/debug-info-rvalue-ref.cpp b/test/CodeGenCXX/debug-info-rvalue-ref.cpp
index ce5d3c1..36e4aa3 100644
--- a/test/CodeGenCXX/debug-info-rvalue-ref.cpp
+++ b/test/CodeGenCXX/debug-info-rvalue-ref.cpp
@@ -8,4 +8,4 @@
   printf("%d\n", i);
 }
 
-// CHECK: metadata !{metadata !"0x42\00\000\000\000\000\000", null, null, metadata !{{.*}}} ; [ DW_TAG_rvalue_reference_type ]
+// CHECK:  !"0x42\00\000\000\000\000\000", null, null, !{{.*}}} ; [ DW_TAG_rvalue_reference_type ]
diff --git a/test/CodeGenCXX/debug-info-same-line.cpp b/test/CodeGenCXX/debug-info-same-line.cpp
deleted file mode 100644
index 965a538..0000000
--- a/test/CodeGenCXX/debug-info-same-line.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-// RUN: %clang_cc1 -g -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s
-
-// Make sure that clang outputs distinct debug info for a function
-// that is inlined twice on the same line. Otherwise it would appear
-// as if the function was only inlined once.
-
-#define INLINE inline __attribute__((always_inline))
-
-int i;
-
-INLINE void sum(int a, int b) {
-  i = a + b;
-}
-
-void noinline(int x, int y) {
-  i = x + y;
-}
-
-#define CALLS sum(9, 10), sum(11, 12)
-
-inline void inlsum(int t, int u) {
-  i = t + u;
-}
-
-int main() {
-  sum(1, 2), sum(3, 4);
-  noinline(5, 6), noinline(7, 8);
-  CALLS;
-  inlsum(13, 14), inlsum(15, 16);
-}
-
-// CHECK-LABEL: @main
-// CHECK: = add {{.*}} !dbg [[FIRST_INLINE:![0-9]*]]
-// CHECK: = add {{.*}} !dbg [[SECOND_INLINE:![0-9]*]]
-
-// Check that we don't give column information (and thus end up with distinct
-// line entries) for two non-inlined calls on the same line.
-// CHECK: call {{.*}}noinline{{.*}}({{i32[ ]?[a-z]*}} 5, {{i32[ ]?[a-z]*}} 6), !dbg [[NOINLINE:![0-9]*]]
-// CHECK: call {{.*}}noinline{{.*}}({{i32[ ]?[a-z]*}} 7, {{i32[ ]?[a-z]*}} 8), !dbg [[NOINLINE]]
-
-// FIXME: These should be separate locations but because the two calls have the
-// same line /and/ column, they get coalesced into a single inlined call by
-// accident. We need discriminators or some other changes to LLVM to cope with
-// this. (this is, unfortunately, an LLVM test disguised as a Clang test - since
-// inlining is forced to happen here). It's possible this could be fixed in
-// Clang, but I doubt it'll be the right place for the fix.
-// CHECK: = add {{.*}} !dbg [[FIRST_MACRO_INLINE:![0-9]*]]
-// CHECK: = add {{.*}} !dbg [[FIRST_MACRO_INLINE]]
-
-// Even if the functions are marked inline but do not get inlined, they
-// shouldn't use column information, and thus should be at the same debug
-// location.
-// CHECK: call {{.*}}inlsum{{.*}}({{i32[ ]?[a-z]*}} 13, {{i32[ ]?[a-z]*}} 14), !dbg [[INL_FIRST:![0-9]*]]
-// CHECK: call {{.*}}inlsum{{.*}}({{i32[ ]?[a-z]*}} 15, {{i32[ ]?[a-z]*}} 16), !dbg [[INL_SECOND:![0-9]*]]
-
-// [[FIRST_INLINE]] =
-// [[SECOND_INLINE]] =
-
-// FIXME: These should be the same location since the functions appear on the
-// same line and were not inlined - they needlessly have column information
-// intended to disambiguate inlined calls, which is going to confuse GDB as it
-// doesn't cope well with column information.
-// [[INL_FIRST]] =
-// [[INL_SECOND]] =
diff --git a/test/CodeGenCXX/debug-info-scope.cpp b/test/CodeGenCXX/debug-info-scope.cpp
index 8957e60..e66588d 100644
--- a/test/CodeGenCXX/debug-info-scope.cpp
+++ b/test/CodeGenCXX/debug-info-scope.cpp
@@ -9,47 +9,47 @@
 void f();
 
 void func() {
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[IF1:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
-  // CHECK: [[IF1]] = metadata !{metadata !"0xb\00[[@LINE+1]]\00{{.*}}", metadata !{{.*}}} ; [ DW_TAG_lexical_block ]
+  // CHECK: = !{!"0x100\00{{.*}}", [[IF1:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
+  // CHECK: [[IF1]] = !{!"0xb\00[[@LINE+1]]\00{{.*}}", !{{.*}}} ; [ DW_TAG_lexical_block ]
   if (int i = src())
     f();
 
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[IF2:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
-  // CHECK: [[IF2]] = metadata !{metadata !"0xb\00[[@LINE+1]]\00{{.*}}", metadata !{{.*}}} ; [ DW_TAG_lexical_block ]
+  // CHECK: = !{!"0x100\00{{.*}}", [[IF2:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
+  // CHECK: [[IF2]] = !{!"0xb\00[[@LINE+1]]\00{{.*}}", !{{.*}}} ; [ DW_TAG_lexical_block ]
   if (int i = src()) {
     f();
   } else
     f();
 
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[FOR:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
-  // CHECK: [[FOR]] = metadata !{metadata !"0xb\00[[@LINE+1]]\00{{.*}}", metadata !{{.*}}} ; [ DW_TAG_lexical_block ]
+  // CHECK: = !{!"0x100\00{{.*}}", [[FOR:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
+  // CHECK: [[FOR]] = !{!"0xb\00[[@LINE+1]]\00{{.*}}", !{{.*}}} ; [ DW_TAG_lexical_block ]
   for (int i = 0;
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[FOR_BODY:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [b] [line [[@LINE+6]]]
+  // CHECK: = !{!"0x100\00{{.*}}", [[FOR_BODY:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [b] [line [[@LINE+6]]]
   // The scope could be located at 'bool b', but LLVM drops line information for
   // scopes anyway, so it's not terribly important.
   // FIXME: change the debug info schema to not include locations of scopes,
   // since they're not used.
-  // CHECK: [[FOR_BODY]] = metadata !{metadata !"0xb\00[[@LINE-6]]\00{{.*}}", metadata !{{.*}}} ; [ DW_TAG_lexical_block ]
+  // CHECK: [[FOR_BODY]] = !{!"0xb\00[[@LINE-6]]\00{{.*}}", !{{.*}}} ; [ DW_TAG_lexical_block ]
        bool b = i != 10; ++i)
     f();
 
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[FOR:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
-  // CHECK: [[FOR]] = metadata !{metadata !"0xb\00[[@LINE+1]]\00{{.*}}", metadata !{{.*}}} ; [ DW_TAG_lexical_block ]
+  // CHECK: = !{!"0x100\00{{.*}}", [[FOR:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE+2]]]
+  // CHECK: [[FOR]] = !{!"0xb\00[[@LINE+1]]\00{{.*}}", !{{.*}}} ; [ DW_TAG_lexical_block ]
   for (int i = 0; i != 10; ++i) {
-  // FIXME: Do not include scopes that have only other scopes (and no variables
-  // or using declarations) as direct children, they just waste
-  // space/relocations/etc.
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[FOR_COMPOUND:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [b] [line [[@LINE+3]]]
-  // CHECK: [[FOR_COMPOUND]] = metadata !{metadata !"0xb\00[[@LINE-5]]\00{{.*}}", metadata !{{[0-9]+}}, metadata [[FOR_BODY:![0-9]+]]} ; [ DW_TAG_lexical_block ]
-  // CHECK: [[FOR_BODY]] = metadata !{metadata !"0xb\00[[@LINE-6]]\00{{.*}}", metadata !{{[0-9]+}}, metadata [[FOR]]} ; [ DW_TAG_lexical_block ]
+    // FIXME: Do not include scopes that have only other scopes (and no variables
+    // or using declarations) as direct children, they just waste
+    // space/relocations/etc.
+    // CHECK: [[FOR_LOOP_INCLUDING_COND:!.*]] = !{!"0xb\00[[@LINE-4]]\00{{.*}}", !{{[0-9]+}}, [[FOR]]} ; [ DW_TAG_lexical_block ]
+    // CHECK: = !{!"0x100\00{{.*}}", [[FOR_COMPOUND:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [b] [line [[@LINE+2]]]
+    // CHECK: [[FOR_COMPOUND]] = !{!"0xb\00[[@LINE-6]]\00{{.*}}", !{{[0-9]+}}, [[FOR_LOOP_INCLUDING_COND]]} ; [ DW_TAG_lexical_block ]
     bool b = i % 2;
   }
 
   int x[] = {1, 2};
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[RANGE_FOR:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [__range] [line 0]
-  // CHECK: [[RANGE_FOR]] = metadata !{metadata !"0xb\00[[@LINE+1]]\00{{.*}}", metadata !{{.*}}} ; [ DW_TAG_lexical_block ]
+  // CHECK: = !{!"0x100\00{{.*}}", [[RANGE_FOR:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [__range] [line 0]
+  // CHECK: [[RANGE_FOR]] = !{!"0xb\00[[@LINE+1]]\00{{.*}}", !{{.*}}} ; [ DW_TAG_lexical_block ]
   for (int i : x) {
-  // CHECK: = metadata !{metadata !"0x100\00{{.*}}", metadata [[RANGE_FOR_BODY:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE-1]]]
-  // CHECK: [[RANGE_FOR_BODY]] = metadata !{metadata !"0xb\00[[@LINE-2]]\00{{.*}}", metadata !{{[0-9]+}}, metadata [[RANGE_FOR]]} ; [ DW_TAG_lexical_block ]
+  // CHECK: = !{!"0x100\00{{.*}}", [[RANGE_FOR_BODY:![0-9]*]], {{.*}} ; [ DW_TAG_auto_variable ] [i] [line [[@LINE-1]]]
+  // CHECK: [[RANGE_FOR_BODY]] = !{!"0xb\00[[@LINE-2]]\00{{.*}}", !{{[0-9]+}}, [[RANGE_FOR]]} ; [ DW_TAG_lexical_block ]
   }
 }
diff --git a/test/CodeGenCXX/debug-info-static-fns.cpp b/test/CodeGenCXX/debug-info-static-fns.cpp
index eb2a245..41b713c 100644
--- a/test/CodeGenCXX/debug-info-static-fns.cpp
+++ b/test/CodeGenCXX/debug-info-static-fns.cpp
@@ -7,4 +7,4 @@
 }
 
 // Verify that a is present and mangled.
-// CHECK: metadata !"0x2e\00a\00a\00_ZN1AL1aEi\00{{.*}}", {{.*}}, i32 (i32)* @_ZN1AL1aEi, {{.*}} ; [ DW_TAG_subprogram ] [line 4] [local] [def] [a]
+// CHECK: !"0x2e\00a\00a\00_ZN1AL1aEi\00{{.*}}", {{.*}}, i32 (i32)* @_ZN1AL1aEi, {{.*}} ; [ DW_TAG_subprogram ] [line 4] [local] [def] [a]
diff --git a/test/CodeGenCXX/debug-info-static-member.cpp b/test/CodeGenCXX/debug-info-static-member.cpp
index d80f978..18fd691 100644
--- a/test/CodeGenCXX/debug-info-static-member.cpp
+++ b/test/CodeGenCXX/debug-info-static-member.cpp
@@ -33,15 +33,15 @@
 // why the definition of "a" comes before the declarations while
 // "b" and "c" come after.
 
-// CHECK: metadata !"_ZTS1X"} ; [ DW_TAG_enumeration_type ] [X]
-// CHECK: metadata !"_ZTS1C"} ; [ DW_TAG_class_type ] [C]
-// CHECK: ![[DECL_A:[0-9]+]] = metadata {{.*}} [ DW_TAG_member ] [a] [line {{.*}}, size 0, align 0, offset 0] [static]
-// CHECK: metadata !"0xd\00const_a\00{{.*}}", {{.*}}, i1 true} ; [ DW_TAG_member ] [const_a] [line {{.*}}, size 0, align 0, offset 0] [static]
-// CHECK: ![[DECL_B:[0-9]+]] = metadata !{metadata !"0xd\00b\00{{.*}}", {{.*}} [ DW_TAG_member ] [b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
-// CHECK: metadata !"0xd\00const_b\00{{.*}}", {{.*}}, float 0x{{.*}}} ; [ DW_TAG_member ] [const_b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
-// CHECK: ![[DECL_C:[0-9]+]] = metadata !{metadata !"0xd\00c\00{{.*}}", {{.*}} [ DW_TAG_member ] [c] [line {{.*}}, size 0, align 0, offset 0] [public] [static]
-// CHECK: metadata !"0xd\00const_c\00{{.*}}", {{.*}} [ DW_TAG_member ] [const_c] [line {{.*}}, size 0, align 0, offset 0] [public] [static]
-// CHECK: metadata !"0xd\00x_a\00{{.*}}", {{.*}} [ DW_TAG_member ] [x_a] {{.*}} [public] [static]
+// CHECK: !"_ZTS1X"} ; [ DW_TAG_enumeration_type ] [X]
+// CHECK: !"_ZTS1C"} ; [ DW_TAG_class_type ] [C]
+// CHECK: ![[DECL_A:[0-9]+]] = {{.*}} [ DW_TAG_member ] [a] [line {{.*}}, size 0, align 0, offset 0] [static]
+// CHECK: !"0xd\00const_a\00{{.*}}", {{.*}}, i1 true} ; [ DW_TAG_member ] [const_a] [line {{.*}}, size 0, align 0, offset 0] [static]
+// CHECK: ![[DECL_B:[0-9]+]] = !{!"0xd\00b\00{{.*}}", {{.*}} [ DW_TAG_member ] [b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
+// CHECK: !"0xd\00const_b\00{{.*}}", {{.*}}, float 0x{{.*}}} ; [ DW_TAG_member ] [const_b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
+// CHECK: ![[DECL_C:[0-9]+]] = !{!"0xd\00c\00{{.*}}", {{.*}} [ DW_TAG_member ] [c] [line {{.*}}, size 0, align 0, offset 0] [public] [static]
+// CHECK: !"0xd\00const_c\00{{.*}}", {{.*}} [ DW_TAG_member ] [const_c] [line {{.*}}, size 0, align 0, offset 0] [public] [static]
+// CHECK: !"0xd\00x_a\00{{.*}}", {{.*}} [ DW_TAG_member ] [x_a] {{.*}} [public] [static]
 
 // CHECK: ; [ DW_TAG_structure_type ] [static_decl_templ<int>] {{.*}} [def]
 // CHECK: ; [ DW_TAG_member ] [static_decl_templ_var]
@@ -76,9 +76,9 @@
   return static_decl_templ<int>::static_decl_templ_var;
 }
 
-// CHECK: metadata !{metadata !"0x34\00a\00{{.*}}", null, {{.*}} @_ZN1C1aE, metadata ![[DECL_A]]} ; [ DW_TAG_variable ] [a] {{.*}} [def]
-// CHECK: metadata !{metadata !"0x34\00b\00{{.*}}", null, {{.*}} @_ZN1C1bE, metadata ![[DECL_B]]} ; [ DW_TAG_variable ] [b] {{.*}} [def]
-// CHECK: metadata !{metadata !"0x34\00c\00{{.*}}", null, {{.*}} @_ZN1C1cE, metadata ![[DECL_C]]} ; [ DW_TAG_variable ] [c] {{.*}} [def]
+// CHECK:  !"0x34\00a\00{{.*}}", null, {{.*}} @_ZN1C1aE, ![[DECL_A]]} ; [ DW_TAG_variable ] [a] {{.*}} [def]
+// CHECK:  !"0x34\00b\00{{.*}}", null, {{.*}} @_ZN1C1bE, ![[DECL_B]]} ; [ DW_TAG_variable ] [b] {{.*}} [def]
+// CHECK:  !"0x34\00c\00{{.*}}", null, {{.*}} @_ZN1C1cE, ![[DECL_C]]} ; [ DW_TAG_variable ] [c] {{.*}} [def]
 
 // CHECK-NOT: ; [ DW_TAG_variable ] [anon_static_decl_var]
 
@@ -101,4 +101,4 @@
 int y::z;
 }
 
-// CHECK: metadata !{metadata !"0x34\00z\00{{.*}}", metadata [[NS_X]], {{.*}} ; [ DW_TAG_variable ] [z] {{.*}} [def]
+// CHECK:  !"0x34\00z\00{{.*}}", [[NS_X]], {{.*}} ; [ DW_TAG_variable ] [z] {{.*}} [def]
diff --git a/test/CodeGenCXX/debug-info-template-explicit-specialization.cpp b/test/CodeGenCXX/debug-info-template-explicit-specialization.cpp
index 506c0d5..4613038 100644
--- a/test/CodeGenCXX/debug-info-template-explicit-specialization.cpp
+++ b/test/CodeGenCXX/debug-info-template-explicit-specialization.cpp
@@ -91,3 +91,11 @@
 extern template class j<int>;
 j<int> jj;
 // CHECK: ; [ DW_TAG_structure_type ] [j<int, int>]
+
+template <typename T>
+struct k {
+};
+template <>
+struct k<int>;
+template struct k<int>;
+// CHECK-NOT: ; [ DW_TAG_structure_type ] [k<int>]
diff --git a/test/CodeGenCXX/debug-info-template-limit.cpp b/test/CodeGenCXX/debug-info-template-limit.cpp
index 2e80cd8..8e05c7f 100644
--- a/test/CodeGenCXX/debug-info-template-limit.cpp
+++ b/test/CodeGenCXX/debug-info-template-limit.cpp
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -emit-llvm -fno-standalone-debug -triple %itanium_abi_triple -g %s -o - | FileCheck %s
 
 // Check that this pointer type is TC<int>
-// CHECK: ![[LINE:[0-9]+]] = metadata !{metadata !"0x2\00TC<int>\00{{.*}}", {{.*}} metadata !"_ZTS2TCIiE"} ; [ DW_TAG_class_type ]
-// CHECK: metadata !"_ZTS2TCIiE"} ; [ DW_TAG_pointer_type ]{{.*}}[from _ZTS2TCIiE]
+// CHECK: ![[LINE:[0-9]+]] = !{!"0x2\00TC<int>\00{{.*}}", {{.*}} !"_ZTS2TCIiE"} ; [ DW_TAG_class_type ]
+// CHECK: !"_ZTS2TCIiE"} ; [ DW_TAG_pointer_type ]{{.*}}[from _ZTS2TCIiE]
 
 template<typename T>
 class TC {
diff --git a/test/CodeGenCXX/debug-info-template-member.cpp b/test/CodeGenCXX/debug-info-template-member.cpp
index 7aa1d3d..c1d9f67 100644
--- a/test/CodeGenCXX/debug-info-template-member.cpp
+++ b/test/CodeGenCXX/debug-info-template-member.cpp
@@ -16,25 +16,25 @@
   return MyClass().add<3>(x); // even though add<3> is ODR used, don't emit it since we don't codegen it
 }
 
-// CHECK: [[FOO_MEM:![0-9]*]], null, null, metadata !"_ZTS3foo"} ; [ DW_TAG_structure_type ] [foo]
-// CHECK: [[FOO_MEM]] = metadata !{metadata [[FOO_FUNC:![0-9]*]]}
-// CHECK: [[FOO_FUNC]] = metadata !{metadata !"0x2e\00func\00func\00_ZN3foo4funcEN5outerIS_E5innerE\00{{.*}}"{{, [^,]+, [^,]+}}, metadata [[FOO_FUNC_TYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [func]
-// CHECK: [[FOO_FUNC_TYPE]] = {{.*}}, metadata [[FOO_FUNC_PARAMS:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
-// CHECK: [[FOO_FUNC_PARAMS]] = metadata !{null, metadata !{{[0-9]*}}, metadata !"[[OUTER_FOO_INNER_ID:.*]]"}
-// CHECK: !{{[0-9]*}} = {{.*}}, null, metadata !"[[OUTER_FOO_INNER_ID]]"} ; [ DW_TAG_structure_type ] [inner]
+// CHECK: [[FOO_MEM:![0-9]*]], null, null, !"_ZTS3foo"} ; [ DW_TAG_structure_type ] [foo]
+// CHECK: [[FOO_MEM]] = !{[[FOO_FUNC:![0-9]*]]}
+// CHECK: [[FOO_FUNC]] = !{!"0x2e\00func\00func\00_ZN3foo4funcEN5outerIS_E5innerE\00{{.*}}"{{, [^,]+, [^,]+}}, [[FOO_FUNC_TYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [func]
+// CHECK: [[FOO_FUNC_TYPE]] = {{.*}}, [[FOO_FUNC_PARAMS:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: [[FOO_FUNC_PARAMS]] = !{null, !{{[0-9]*}}, !"[[OUTER_FOO_INNER_ID:.*]]"}
+// CHECK: !{{[0-9]*}} = {{.*}}, null, !"[[OUTER_FOO_INNER_ID]]"} ; [ DW_TAG_structure_type ] [inner]
 
-// CHECK: metadata [[VIRT_MEM:![0-9]*]], metadata !"_ZTS4virtI4elemE", metadata [[VIRT_TEMP_PARAM:![0-9]*]], metadata !"_ZTS4virtI4elemE"} ; [ DW_TAG_structure_type ] [virt<elem>] {{.*}} [def]
-// CHECK: [[VIRT_TEMP_PARAM]] = metadata !{metadata [[VIRT_T:![0-9]*]]}
-// CHECK: [[VIRT_T]] = metadata !{metadata !"0x2f\00T\000\000"{{, [^,]+}}, metadata !"_ZTS4elem", {{.*}} ; [ DW_TAG_template_type_parameter ]
+// CHECK: [[VIRT_MEM:![0-9]*]], !"_ZTS4virtI4elemE", [[VIRT_TEMP_PARAM:![0-9]*]], !"_ZTS4virtI4elemE"} ; [ DW_TAG_structure_type ] [virt<elem>] {{.*}} [def]
+// CHECK: [[VIRT_TEMP_PARAM]] = !{[[VIRT_T:![0-9]*]]}
+// CHECK: [[VIRT_T]] = !{!"0x2f\00T\000\000"{{, [^,]+}}, !"_ZTS4elem", {{.*}} ; [ DW_TAG_template_type_parameter ]
 
-// CHECK: [[C:![0-9]*]] = {{.*}}, metadata [[C_MEM:![0-9]*]], metadata !"_ZTS7MyClass", null, metadata !"_ZTS7MyClass"} ; [ DW_TAG_structure_type ] [MyClass]
-// CHECK: [[C_MEM]] = metadata !{metadata [[C_VPTR:![0-9]*]], metadata [[C_FUNC:![0-9]*]]}
+// CHECK: [[C:![0-9]*]] = {{.*}}, [[C_MEM:![0-9]*]], !"_ZTS7MyClass", null, !"_ZTS7MyClass"} ; [ DW_TAG_structure_type ] [MyClass]
+// CHECK: [[C_MEM]] = !{[[C_VPTR:![0-9]*]], [[C_FUNC:![0-9]*]]}
 // CHECK: [[C_VPTR]] = {{.*}} ; [ DW_TAG_member ] [_vptr$MyClass]
 
 // CHECK: [[C_FUNC]] = {{.*}} ; [ DW_TAG_subprogram ] [line 7] [func]
 
-// CHECK: [[ELEM:![0-9]*]] = {{.*}}, metadata [[ELEM_MEM:![0-9]*]], null, null, metadata !"_ZTS4elem"} ; [ DW_TAG_structure_type ] [elem] {{.*}} [def]
-// CHECK: [[ELEM_MEM]] = metadata !{metadata [[ELEM_X:![0-9]*]]}
+// CHECK: [[ELEM:![0-9]*]] = {{.*}}, [[ELEM_MEM:![0-9]*]], null, null, !"_ZTS4elem"} ; [ DW_TAG_structure_type ] [elem] {{.*}} [def]
+// CHECK: [[ELEM_MEM]] = !{[[ELEM_X:![0-9]*]]}
 // CHECK: [[ELEM_X]] = {{.*}} ; [ DW_TAG_member ] [x] {{.*}} [static] [from _ZTS4virtI4elemE]
 
 // Check that the member function template specialization and implicit special
@@ -42,8 +42,8 @@
 // didn't appear in the class's member list (C_MEM). This prevents the functions
 // from being added to type units, while still appearing in the type
 // declaration/reference in the compile unit.
-// CHECK: metadata !"_ZTS7MyClass", {{.*}} ; [ DW_TAG_subprogram ] [line 4] [add<2>]
-// CHECK: metadata !"_ZTS7MyClass", {{.*}} ; [ DW_TAG_subprogram ] [line 0] [MyClass]
+// CHECK: !"_ZTS7MyClass", {{.*}} ; [ DW_TAG_subprogram ] [line 0] [MyClass]
+// CHECK: !"_ZTS7MyClass", {{.*}} ; [ DW_TAG_subprogram ] [line 4] [add<2>]
 
 template<typename T>
 struct outer {
@@ -65,7 +65,7 @@
 
 outer<foo>::inner x;
 
-// CHECK: metadata !{metadata !"0x34\00{{.*}}", {{.*}}, metadata !"[[OUTER_FOO_INNER_ID]]", %"struct.outer<foo>::inner"* @x, {{.*}} ; [ DW_TAG_variable ] [x]
+// CHECK:  !"0x34\00{{.*}}", {{.*}}, !"[[OUTER_FOO_INNER_ID]]", %"struct.outer<foo>::inner"* @x, {{.*}} ; [ DW_TAG_variable ] [x]
 
 template <typename T>
 struct virt {
diff --git a/test/CodeGenCXX/debug-info-template-partial-specialization.cpp b/test/CodeGenCXX/debug-info-template-partial-specialization.cpp
index cce84af..6940c0f 100644
--- a/test/CodeGenCXX/debug-info-template-partial-specialization.cpp
+++ b/test/CodeGenCXX/debug-info-template-partial-specialization.cpp
@@ -3,7 +3,7 @@
 {
   template <class _Tp, class _Dp, bool > struct __pointer_type1 {};
 
-  // CHECK: metadata ![[PARAMS:[0-9]+]], metadata !"_ZTSN18__pointer_type_imp15__pointer_type1I1C14default_deleteIS1_ELb0EEE"} ; [ DW_TAG_structure_type ] [__pointer_type1<C, default_delete<C>, false>] [line [[@LINE+1]], size 8, align 8, offset 0] [def] [from ]
+  // CHECK: ![[PARAMS:[0-9]+]], !"_ZTSN18__pointer_type_imp15__pointer_type1I1C14default_deleteIS1_ELb0EEE"} ; [ DW_TAG_structure_type ] [__pointer_type1<C, default_delete<C>, false>] [line [[@LINE+1]], size 8, align 8, offset 0] [def] [from ]
   template <class _Tp, class _Dp> struct __pointer_type1<_Tp, _Dp, false>
   {
     typedef _Tp* type;
@@ -14,7 +14,7 @@
 {
   // Test that the bool template type parameter is emitted.
   //
-  // CHECK: ![[PARAMS]] = metadata !{metadata !{{.*}}, metadata !{{.*}}, metadata ![[FALSE:[0-9]+]]}
+  // CHECK: ![[PARAMS]] = !{!{{.*}}, !{{.*}}, ![[FALSE:[0-9]+]]}
   // CHECK: ![[FALSE]] = {{.*}} i8 0, {{.*}}} ; [ DW_TAG_template_value_parameter ]
   typedef typename __pointer_type_imp::__pointer_type1<_Tp, _Dp, false>::type type;
 };
diff --git a/test/CodeGenCXX/debug-info-template-quals.cpp b/test/CodeGenCXX/debug-info-template-quals.cpp
index a9cd513..15c096f 100644
--- a/test/CodeGenCXX/debug-info-template-quals.cpp
+++ b/test/CodeGenCXX/debug-info-template-quals.cpp
@@ -16,12 +16,12 @@
 }
 
 // CHECK: [[BS:.*]] = {{.*}} ; [ DW_TAG_structure_type ] [basic_string<char>] [line 4, size 8, align 8, offset 0] [def] [from ]
-// CHECK: [[TYPE:![0-9]*]] = metadata !{metadata !"0x15\00{{.*}}"{{.*}}, metadata [[ARGS:.*]], null, null, null} ; [ DW_TAG_subroutine_type ]
-// CHECK: [[ARGS]] = metadata !{metadata !{{.*}}, metadata !{{.*}}, metadata [[P:![0-9]*]], metadata [[R:.*]]}
-// CHECK: [[P]] = {{.*}}, metadata [[CON:![0-9]*]]} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [from ]
-// CHECK: [[CON]] = {{.*}}, metadata [[CH:![0-9]*]]} ; [ DW_TAG_const_type ] [line 0, size 0, align 0, offset 0] [from char]
+// CHECK: [[TYPE:![0-9]*]] = !{!"0x15\00{{.*}}"{{.*}}, [[ARGS:.*]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: [[ARGS]] = !{!{{.*}}, !{{.*}}, [[P:![0-9]*]], [[R:.*]]}
+// CHECK: [[P]] = {{.*}}, [[CON:![0-9]*]]} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [from ]
+// CHECK: [[CON]] = {{.*}}, [[CH:![0-9]*]]} ; [ DW_TAG_const_type ] [line 0, size 0, align 0, offset 0] [from char]
 // CHECK: [[CH]] = {{.*}} ; [ DW_TAG_base_type ] [char] [line 0, size 8, align 8, offset 0, enc DW_ATE_signed_char]
 
-// CHECK: [[R]] = {{.*}}, metadata [[CON2:![0-9]*]]} ; [ DW_TAG_reference_type ] [line 0, size 0, align 0, offset 0] [from ]
-// CHECK: [[CON2]] = {{.*}}, metadata !"_ZTS12basic_stringIcE"} ; [ DW_TAG_const_type ] [line 0, size 0, align 0, offset 0] [from _ZTS12basic_stringIcE]
-// CHECK: metadata !"0x2e\00assign\00{{.*}}\008"{{, [^,]+, [^,]+}}, metadata !8, {{.*}} ; [ DW_TAG_subprogram ] [line 7] [def] [scope 8] [assign]
+// CHECK: [[R]] = {{.*}}, [[CON2:![0-9]*]]} ; [ DW_TAG_reference_type ] [line 0, size 0, align 0, offset 0] [from ]
+// CHECK: [[CON2]] = {{.*}}, !"_ZTS12basic_stringIcE"} ; [ DW_TAG_const_type ] [line 0, size 0, align 0, offset 0] [from _ZTS12basic_stringIcE]
+// CHECK: !"0x2e\00assign\00{{.*}}\008"{{, [^,]+, [^,]+}}, !8, {{.*}} ; [ DW_TAG_subprogram ] [line 7] [def] [scope 8] [assign]
diff --git a/test/CodeGenCXX/debug-info-template.cpp b/test/CodeGenCXX/debug-info-template.cpp
index b7652f7..17b9450 100644
--- a/test/CodeGenCXX/debug-info-template.cpp
+++ b/test/CodeGenCXX/debug-info-template.cpp
@@ -1,96 +1,96 @@
 // RUN: %clang -S -emit-llvm -target x86_64-unknown_unknown -g %s -o - -std=c++11 | FileCheck %s
 
-// CHECK: metadata !"0x11\00{{.*}}"{{, [^,]+, [^,]+}}, metadata [[RETAIN:![0-9]*]], {{.*}} ; [ DW_TAG_compile_unit ]
-// CHECK: [[EMPTY:![0-9]*]] = metadata !{}
-// CHECK: [[RETAIN]] = metadata !{metadata !{{[0-9]]*}}, metadata [[FOO:![0-9]*]],
+// CHECK: !"0x11\00{{.*}}"{{, [^,]+, [^,]+}}, [[RETAIN:![0-9]*]], {{.*}} ; [ DW_TAG_compile_unit ]
+// CHECK: [[EMPTY:![0-9]*]] = !{}
+// CHECK: [[RETAIN]] = !{!{{[0-9]]*}}, [[FOO:![0-9]*]],
 
 
-// CHECK: [[TC:![0-9]*]] = {{.*}}, metadata [[TCARGS:![0-9]*]], metadata !"{{.*}}"} ; [ DW_TAG_structure_type ] [TC<unsigned int, 2, &glb, &foo::e, &foo::f, &foo::g, 1, 2, 3>]
-// CHECK: [[TCARGS]] = metadata !{metadata [[TCARG1:![0-9]*]], metadata [[TCARG2:![0-9]*]], metadata [[TCARG3:![0-9]*]], metadata [[TCARG4:![0-9]*]], metadata [[TCARG5:![0-9]*]], metadata [[TCARG6:![0-9]*]], metadata [[TCARG7:![0-9]*]]}
+// CHECK: [[TC:![0-9]*]] = {{.*}}, [[TCARGS:![0-9]*]], !"{{.*}}"} ; [ DW_TAG_structure_type ] [TC<unsigned int, 2, &glb, &foo::e, &foo::f, &foo::g, 1, 2, 3>]
+// CHECK: [[TCARGS]] = !{[[TCARG1:![0-9]*]], [[TCARG2:![0-9]*]], [[TCARG3:![0-9]*]], [[TCARG4:![0-9]*]], [[TCARG5:![0-9]*]], [[TCARG6:![0-9]*]], [[TCARG7:![0-9]*]]}
 //
 // We seem to be missing file/line/col info on template value parameters -
 // metadata supports it but it's not populated. GCC doesn't emit it either,
 // perhaps we should just drop it from the metadata.
 //
-// CHECK: [[TCARG1]] = metadata !{metadata !"0x2f\00T\000\000", null, metadata [[UINT:![0-9]*]], null} ; [ DW_TAG_template_type_parameter ]
+// CHECK: [[TCARG1]] = !{!"0x2f\00T\000\000", null, [[UINT:![0-9]*]], null} ; [ DW_TAG_template_type_parameter ]
 // CHECK: [[UINT:![0-9]*]] = {{.*}} ; [ DW_TAG_base_type ] [unsigned int]
-// CHECK: [[TCARG2]] = metadata !{metadata !"0x30\00\00{{.*}}", {{[^,]+}}, metadata [[UINT]], i32 2, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[TCARG3]] = metadata !{metadata !"0x30\00x\00{{.*}}", {{[^,]+}}, metadata [[CINTPTR:![0-9]*]], i32* @glb, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[CINTPTR]] = {{.*}}, metadata [[CINT:![0-9]*]]} ; [ DW_TAG_pointer_type ] {{.*}} [from ]
-// CHECK: [[CINT]] = {{.*}}, metadata [[INT:![0-9]*]]} ; [ DW_TAG_const_type ] {{.*}} [from int]
+// CHECK: [[TCARG2]] = !{!"0x30\00\00{{.*}}", {{[^,]+}}, [[UINT]], i32 2, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCARG3]] = !{!"0x30\00x\00{{.*}}", {{[^,]+}}, [[CINTPTR:![0-9]*]], i32* @glb, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[CINTPTR]] = {{.*}}, [[CINT:![0-9]*]]} ; [ DW_TAG_pointer_type ] {{.*}} [from ]
+// CHECK: [[CINT]] = {{.*}}, [[INT:![0-9]*]]} ; [ DW_TAG_const_type ] {{.*}} [from int]
 // CHECK: [[INT]] = {{.*}} ; [ DW_TAG_base_type ] [int]
-// CHECK: [[TCARG4]] = metadata !{metadata !"0x30\00a\00{{.*}}", {{[^,]+}}, metadata [[MEMINTPTR:![0-9]*]], i64 8, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[MEMINTPTR]] = {{.*}}, metadata !"_ZTS3foo"} ; [ DW_TAG_ptr_to_member_type ] {{.*}}[from int]
+// CHECK: [[TCARG4]] = !{!"0x30\00a\00{{.*}}", {{[^,]+}}, [[MEMINTPTR:![0-9]*]], i64 8, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[MEMINTPTR]] = {{.*}}, !"_ZTS3foo"} ; [ DW_TAG_ptr_to_member_type ] {{.*}}[from int]
 //
 // Currently Clang emits the pointer-to-member-function value, but LLVM doesn't
 // use it (GCC doesn't emit a value for pointers to member functions either - so
 // it's not clear what, if any, format would be acceptable to GDB)
 //
-// CHECK: [[TCARG5]] = metadata !{metadata !"0x30\00b\00{{.*}}", {{[^,]+}}, metadata [[MEMFUNPTR:![0-9]*]], { i64, i64 } { i64 ptrtoint (void (%struct.foo*)* @_ZN3foo1fEv to i64), i64 0 }, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[MEMFUNPTR]] = {{.*}}, metadata [[FTYPE:![0-9]*]], metadata !"_ZTS3foo"} ; [ DW_TAG_ptr_to_member_type ]
-// CHECK: [[FTYPE]] = {{.*}}, metadata [[FARGS:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
-// CHECK: [[FARGS]] = metadata !{null, metadata [[FARG1:![0-9]*]]}
+// CHECK: [[TCARG5]] = !{!"0x30\00b\00{{.*}}", {{[^,]+}}, [[MEMFUNPTR:![0-9]*]], { i64, i64 } { i64 ptrtoint (void (%struct.foo*)* @_ZN3foo1fEv to i64), i64 0 }, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[MEMFUNPTR]] = {{.*}}, [[FTYPE:![0-9]*]], !"_ZTS3foo"} ; [ DW_TAG_ptr_to_member_type ]
+// CHECK: [[FTYPE]] = {{.*}}, [[FARGS:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: [[FARGS]] = !{null, [[FARG1:![0-9]*]]}
 // CHECK: [[FARG1]] = {{.*}} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [artificial] [from _ZTS3foo]
 //
-// CHECK: [[TCARG6]] = metadata !{metadata !"0x30\00f\00{{.*}}", {{[^,]+}}, metadata [[FUNPTR:![0-9]*]], void ()* @_ZN3foo1gEv, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[FUNPTR]] = {{.*}}, metadata [[FUNTYPE:![0-9]*]]} ; [ DW_TAG_pointer_type ]
-// CHECK: [[FUNTYPE]] = {{.*}}, metadata [[FUNARGS:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
-// CHECK: [[FUNARGS]] = metadata !{null}
-// CHECK: [[TCARG7]] = metadata !{metadata !"0x4107\00Is\000\000", null, null, metadata [[TCARG7_VALS:![0-9]*]], null} ; [ DW_TAG_GNU_template_parameter_pack ]
-// CHECK: [[TCARG7_VALS]] = metadata !{metadata [[TCARG7_1:![0-9]*]], metadata [[TCARG7_2:![0-9]*]], metadata [[TCARG7_3:![0-9]*]]}
-// CHECK: [[TCARG7_1]] = metadata !{metadata !"0x30\00\00{{.*}}", {{[^,]+}}, metadata [[INT]], i32 1, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[TCARG7_2]] = metadata !{metadata !"0x30\00\00{{.*}}", {{[^,]+}}, metadata [[INT]], i32 2, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[TCARG7_3]] = metadata !{metadata !"0x30\00\00{{.*}}", {{[^,]+}}, metadata [[INT]], i32 3, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCARG6]] = !{!"0x30\00f\00{{.*}}", {{[^,]+}}, [[FUNPTR:![0-9]*]], void ()* @_ZN3foo1gEv, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[FUNPTR]] = {{.*}}, [[FUNTYPE:![0-9]*]]} ; [ DW_TAG_pointer_type ]
+// CHECK: [[FUNTYPE]] = {{.*}}, [[FUNARGS:![0-9]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: [[FUNARGS]] = !{null}
+// CHECK: [[TCARG7]] = !{!"0x4107\00Is\000\000", null, null, [[TCARG7_VALS:![0-9]*]], null} ; [ DW_TAG_GNU_template_parameter_pack ]
+// CHECK: [[TCARG7_VALS]] = !{[[TCARG7_1:![0-9]*]], [[TCARG7_2:![0-9]*]], [[TCARG7_3:![0-9]*]]}
+// CHECK: [[TCARG7_1]] = !{!"0x30\00\00{{.*}}", {{[^,]+}}, [[INT]], i32 1, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCARG7_2]] = !{!"0x30\00\00{{.*}}", {{[^,]+}}, [[INT]], i32 2, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCARG7_3]] = !{!"0x30\00\00{{.*}}", {{[^,]+}}, [[INT]], i32 3, {{.*}} ; [ DW_TAG_template_value_parameter ]
 //
 // We could just emit a declaration of 'foo' here, rather than the entire
 // definition (same goes for any time we emit a member (function or data)
 // pointer type)
-// CHECK: [[FOO]] = {{.*}}, metadata !"_ZTS3foo"} ; [ DW_TAG_structure_type ] [foo]
-// CHECK: metadata !"0x2e\00f\00f\00_ZN3foo1fEv\00{{.*}}", metadata [[FTYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ]
+// CHECK: [[FOO]] = {{.*}}, !"_ZTS3foo"} ; [ DW_TAG_structure_type ] [foo]
+// CHECK: !"0x2e\00f\00f\00_ZN3foo1fEv\00{{.*}}", [[FTYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ]
 //
 
-// CHECK: metadata !{metadata !"0x13\00{{.*}}", metadata !{{[0-9]*}}, metadata !"_ZTS2TCIjLj2EXadL_Z3glbEEXadL_ZN3foo1eEEEXadL_ZNS0_1fEvEEXadL_ZNS0_1gEvEEJLi1ELi2ELi3EEE", {{.*}}, metadata !"[[TCNESTED:.*]]"} ; [ DW_TAG_structure_type ] [nested]
-// CHECK: metadata [[TCNARGS:![0-9]*]], metadata !"[[TCNT:.*]]"} ; [ DW_TAG_structure_type ] [TC<int, -3, nullptr, nullptr, nullptr, nullptr>]
-// CHECK: [[TCNARGS]] = metadata !{metadata [[TCNARG1:![0-9]*]], metadata [[TCNARG2:![0-9]*]], metadata [[TCNARG3:![0-9]*]], metadata [[TCNARG4:![0-9]*]], metadata [[TCNARG5:![0-9]*]], metadata [[TCNARG6:![0-9]*]], metadata [[TCNARG7:![0-9]*]]}
-// CHECK: [[TCNARG1]] = metadata !{metadata !"0x2f\00T\000\000", null, metadata [[INT]], null} ; [ DW_TAG_template_type_parameter ]
-// CHECK: [[TCNARG2]] = metadata !{metadata !"0x30\00\000\000", null, metadata [[INT]], i32 -3, null} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[TCNARG3]] = metadata !{metadata !"0x30\00x\000\000", null, metadata [[CINTPTR]], i8 0, null} ; [ DW_TAG_template_value_parameter ]
+// CHECK:  !"0x13\00{{.*}}", !{{[0-9]*}}, !"_ZTS2TCIjLj2EXadL_Z3glbEEXadL_ZN3foo1eEEEXadL_ZNS0_1fEvEEXadL_ZNS0_1gEvEEJLi1ELi2ELi3EEE", {{.*}}, !"[[TCNESTED:.*]]"} ; [ DW_TAG_structure_type ] [nested]
+// CHECK: [[TCNARGS:![0-9]*]], !"[[TCNT:.*]]"} ; [ DW_TAG_structure_type ] [TC<int, -3, nullptr, nullptr, nullptr, nullptr>]
+// CHECK: [[TCNARGS]] = !{[[TCNARG1:![0-9]*]], [[TCNARG2:![0-9]*]], [[TCNARG3:![0-9]*]], [[TCNARG4:![0-9]*]], [[TCNARG5:![0-9]*]], [[TCNARG6:![0-9]*]], [[TCNARG7:![0-9]*]]}
+// CHECK: [[TCNARG1]] = !{!"0x2f\00T\000\000", null, [[INT]], null} ; [ DW_TAG_template_type_parameter ]
+// CHECK: [[TCNARG2]] = !{!"0x30\00\000\000", null, [[INT]], i32 -3, null} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCNARG3]] = !{!"0x30\00x\000\000", null, [[CINTPTR]], i8 0, null} ; [ DW_TAG_template_value_parameter ]
 
 // The interesting null pointer: -1 for member data pointers (since they are
 // just an offset in an object, they can be zero and non-null for the first
 // member)
 
-// CHECK: [[TCNARG4]] = metadata !{metadata !"0x30\00a\000\000", null, metadata [[MEMINTPTR]], i64 -1, null} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCNARG4]] = !{!"0x30\00a\000\000", null, [[MEMINTPTR]], i64 -1, null} ; [ DW_TAG_template_value_parameter ]
 //
 // In some future iteration we could possibly emit the value of a null member
 // function pointer as '{ i64, i64 } zeroinitializer' as it may be handled
 // naturally from the LLVM CodeGen side once we decide how to handle non-null
 // member function pointers. For now, it's simpler just to emit the 'i8 0'.
 //
-// CHECK: [[TCNARG5]] = metadata !{metadata !"0x30\00b\000\000", null, metadata [[MEMFUNPTR]], i8 0, null} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[TCNARG6]] = metadata !{metadata !"0x30\00f\000\000", null, metadata [[FUNPTR]], i8 0, null} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[TCNARG7]] = metadata !{metadata !"0x4107\00Is\000\000", null, null, metadata [[EMPTY]], null} ; [ DW_TAG_GNU_template_parameter_pack ]
+// CHECK: [[TCNARG5]] = !{!"0x30\00b\000\000", null, [[MEMFUNPTR]], i8 0, null} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCNARG6]] = !{!"0x30\00f\000\000", null, [[FUNPTR]], i8 0, null} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[TCNARG7]] = !{!"0x4107\00Is\000\000", null, null, [[EMPTY]], null} ; [ DW_TAG_GNU_template_parameter_pack ]
 
 // FIXME: these parameters should probably be rendered as 'glb' rather than
 // '&glb', since they're references, not pointers.
-// CHECK: metadata [[NNARGS:![0-9]*]], metadata !"[[NNT:.*]]"} ; [ DW_TAG_structure_type ] [NN<tmpl_impl, &glb, &glb>]
-// CHECK: [[NNARGS]] = metadata !{metadata [[NNARG1:![0-9]*]], metadata [[NNARG2:![0-9]*]], metadata [[NNARG3:![0-9]*]]}
-// CHECK: [[NNARG1]] = metadata !{metadata !"0x4106\00tmpl\000\000", null, null, metadata !"tmpl_impl", null} ; [ DW_TAG_GNU_template_template_param ]
-// CHECK: [[NNARG2]] = metadata !{metadata !"0x30\00lvr\00{{.*}}", {{[^,]+}}, metadata [[INTLVR:![0-9]*]], i32* @glb, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[INTLVR]] = {{.*}}, metadata [[INT]]} ; [ DW_TAG_reference_type ] {{.*}} [from int]
-// CHECK: [[NNARG3]] = metadata !{metadata !"0x30\00rvr\00{{.*}}", {{[^,]+}}, metadata [[INTRVR:![0-9]*]], i32* @glb, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[INTRVR]] = {{.*}}, metadata [[INT]]} ; [ DW_TAG_rvalue_reference_type ] {{.*}} [from int]
+// CHECK: [[NNARGS:![0-9]*]], !"[[NNT:.*]]"} ; [ DW_TAG_structure_type ] [NN<tmpl_impl, &glb, &glb>]
+// CHECK: [[NNARGS]] = !{[[NNARG1:![0-9]*]], [[NNARG2:![0-9]*]], [[NNARG3:![0-9]*]]}
+// CHECK: [[NNARG1]] = !{!"0x4106\00tmpl\000\000", null, null, !"tmpl_impl", null} ; [ DW_TAG_GNU_template_template_param ]
+// CHECK: [[NNARG2]] = !{!"0x30\00lvr\00{{.*}}", {{[^,]+}}, [[INTLVR:![0-9]*]], i32* @glb, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[INTLVR]] = {{.*}}, [[INT]]} ; [ DW_TAG_reference_type ] {{.*}} [from int]
+// CHECK: [[NNARG3]] = !{!"0x30\00rvr\00{{.*}}", {{[^,]+}}, [[INTRVR:![0-9]*]], i32* @glb, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[INTRVR]] = {{.*}}, [[INT]]} ; [ DW_TAG_rvalue_reference_type ] {{.*}} [from int]
 
-// CHECK: metadata [[PTOARGS:![0-9]*]], metadata !"{{.*}}"} ; [ DW_TAG_structure_type ] [PaddingAtEndTemplate<&PaddedObj>]
-// CHECK: [[PTOARGS]] = metadata !{metadata [[PTOARG1:![0-9]*]]}
-// CHECK: [[PTOARG1]] = metadata !{metadata !"0x30\00\000\000", null, metadata [[CONST_PADDINGATEND_PTR:![0-9]*]], %struct.PaddingAtEnd* @PaddedObj, null} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[PTOARGS:![0-9]*]], !"{{.*}}"} ; [ DW_TAG_structure_type ] [PaddingAtEndTemplate<&PaddedObj>]
+// CHECK: [[PTOARGS]] = !{[[PTOARG1:![0-9]*]]}
+// CHECK: [[PTOARG1]] = !{!"0x30\00\000\000", null, [[CONST_PADDINGATEND_PTR:![0-9]*]], %struct.PaddingAtEnd* @PaddedObj, null} ; [ DW_TAG_template_value_parameter ]
 // CHECK: [[CONST_PADDINGATEND_PTR]] = {{.*}} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [from _ZTS12PaddingAtEnd]
 
-// CHECK: metadata !"[[TCNESTED]]", %"struct.TC<unsigned int, 2, &glb, &foo::e, &foo::f, &foo::g, 1, 2, 3>::nested"* @tci, null} ; [ DW_TAG_variable ] [tci]
+// CHECK: !"[[TCNESTED]]", %"struct.TC<unsigned int, 2, &glb, &foo::e, &foo::f, &foo::g, 1, 2, 3>::nested"* @tci, null} ; [ DW_TAG_variable ] [tci]
 
-// CHECK: metadata !"[[TCNT]]", %struct.TC* @tcn, null} ; [ DW_TAG_variable ] [tcn]
+// CHECK: !"[[TCNT]]", %struct.TC* @tcn, null} ; [ DW_TAG_variable ] [tcn]
 
-// CHECK: metadata !"[[NNT]]", %struct.NN* @nn, null} ; [ DW_TAG_variable ] [nn]
+// CHECK: !"[[NNT]]", %struct.NN* @nn, null} ; [ DW_TAG_variable ] [nn]
 struct foo {
   char pad[8]; // make the member pointer to 'e' a bit more interesting (nonzero)
   int e;
diff --git a/test/CodeGenCXX/debug-info-thunk.cpp b/test/CodeGenCXX/debug-info-thunk.cpp
index a2dd43c..9f18790 100644
--- a/test/CodeGenCXX/debug-info-thunk.cpp
+++ b/test/CodeGenCXX/debug-info-thunk.cpp
@@ -14,4 +14,4 @@
 
 void C::f() { }
 
-// CHECK: metadata !{metadata !"0x2e\00\00\00_ZThn{{[48]}}_N1C1fEv\0015\00{{.*}}", {{.*}} ; [ DW_TAG_subprogram ] [line 15] [def]{{$}}
+// CHECK:  !"0x2e\00\00\00_ZThn{{[48]}}_N1C1fEv\0015\00{{.*}}", {{.*}} ; [ DW_TAG_subprogram ] [line 15] [def]{{$}}
diff --git a/test/CodeGenCXX/debug-info-union-template.cpp b/test/CodeGenCXX/debug-info-union-template.cpp
index 6f644a9..aa66e3f 100644
--- a/test/CodeGenCXX/debug-info-union-template.cpp
+++ b/test/CodeGenCXX/debug-info-union-template.cpp
@@ -10,6 +10,6 @@
   Value<float> f;
 }
 
-// CHECK: metadata !{metadata !"0x17\00Value<float>\00{{.*}}", {{.*}}, metadata [[TTPARAM:![0-9]+]], metadata !"_ZTSN7PR156375ValueIfEE"} ; [ DW_TAG_union_type ] [Value<float>]
-// CHECK: [[TTPARAM]] = metadata !{metadata [[PARAMS:.*]]}
-// CHECK: [[PARAMS]] = metadata !{metadata !"0x2f\00T\000\000", {{.*}} ; [ DW_TAG_template_type_parameter ]
+// CHECK:  !"0x17\00Value<float>\00{{.*}}", {{.*}}, [[TTPARAM:![0-9]+]], !"_ZTSN7PR156375ValueIfEE"} ; [ DW_TAG_union_type ] [Value<float>]
+// CHECK: [[TTPARAM]] = !{[[PARAMS:.*]]}
+// CHECK: [[PARAMS]] = !{!"0x2f\00T\000\000", {{.*}} ; [ DW_TAG_template_type_parameter ]
diff --git a/test/CodeGenCXX/debug-info-uuid.cpp b/test/CodeGenCXX/debug-info-uuid.cpp
index 5bc0489..b7e532b 100644
--- a/test/CodeGenCXX/debug-info-uuid.cpp
+++ b/test/CodeGenCXX/debug-info-uuid.cpp
@@ -1,20 +1,20 @@
 // RUN: %clang_cc1 -emit-llvm -fms-extensions -triple=x86_64-pc-win32 -g %s -o - -std=c++11 | FileCheck %s
 // RUN: %clang_cc1 -emit-llvm -fms-extensions -triple=x86_64-unknown-unknown -g %s -o - -std=c++11 2>&1 | FileCheck %s --check-prefix=CHECK-ITANIUM
 
-// CHECK: metadata [[TGIARGS:![0-9]*]], null} ; [ DW_TAG_structure_type ] [tmpl_guid<&__uuidof(uuid)>]
-// CHECK: [[TGIARGS]] = metadata !{metadata [[TGIARG1:![0-9]*]]}
-// CHECK: [[TGIARG1]] = metadata !{metadata !"0x30\00\00{{.*}}", {{[^,]+}}, metadata [[CONST_GUID_PTR:![0-9]*]], { i32, i16, i16, [8 x i8] }* @_GUID_12345678_1234_1234_1234_1234567890ab, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[CONST_GUID_PTR]] = {{.*}}, metadata [[CONST_GUID:![0-9]*]]} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [from ]
-// CHECK: [[CONST_GUID]] = {{.*}}, metadata [[GUID:![0-9]*]]} ; [ DW_TAG_const_type ] [line 0, size 0, align 0, offset 0] [from _GUID]
+// CHECK: [[TGIARGS:![0-9]*]], null} ; [ DW_TAG_structure_type ] [tmpl_guid<&__uuidof(uuid)>]
+// CHECK: [[TGIARGS]] = !{[[TGIARG1:![0-9]*]]}
+// CHECK: [[TGIARG1]] = !{!"0x30\00\00{{.*}}", {{[^,]+}}, [[CONST_GUID_PTR:![0-9]*]], { i32, i16, i16, [8 x i8] }* @_GUID_12345678_1234_1234_1234_1234567890ab, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[CONST_GUID_PTR]] = {{.*}}, [[CONST_GUID:![0-9]*]]} ; [ DW_TAG_pointer_type ] [line 0, size 64, align 64, offset 0] [from ]
+// CHECK: [[CONST_GUID]] = {{.*}}, [[GUID:![0-9]*]]} ; [ DW_TAG_const_type ] [line 0, size 0, align 0, offset 0] [from _GUID]
 // CHECK: [[GUID]] = {{.*}} ; [ DW_TAG_structure_type ] [_GUID]
 
-// CHECK: metadata [[TGI2ARGS:![0-9]*]], null} ; [ DW_TAG_structure_type ] [tmpl_guid2<__uuidof(uuid)>]
-// CHECK: [[TGI2ARGS]] = metadata !{metadata [[TGI2ARG1:![0-9]*]]}
-// CHECK: [[TGI2ARG1]] = metadata !{metadata !"0x30\00\00{{.*}}", {{[^,]+}}, metadata [[CONST_GUID_REF:![0-9]*]], { i32, i16, i16, [8 x i8] }* @_GUID_12345678_1234_1234_1234_1234567890ab, {{.*}} ; [ DW_TAG_template_value_parameter ]
-// CHECK: [[CONST_GUID_REF]] = {{.*}}, metadata [[CONST_GUID:![0-9]*]]} ; [ DW_TAG_reference_type ] [line 0, size 0, align 0, offset 0] [from ]
+// CHECK: [[TGI2ARGS:![0-9]*]], null} ; [ DW_TAG_structure_type ] [tmpl_guid2<__uuidof(uuid)>]
+// CHECK: [[TGI2ARGS]] = !{[[TGI2ARG1:![0-9]*]]}
+// CHECK: [[TGI2ARG1]] = !{!"0x30\00\00{{.*}}", {{[^,]+}}, [[CONST_GUID_REF:![0-9]*]], { i32, i16, i16, [8 x i8] }* @_GUID_12345678_1234_1234_1234_1234567890ab, {{.*}} ; [ DW_TAG_template_value_parameter ]
+// CHECK: [[CONST_GUID_REF]] = {{.*}}, [[CONST_GUID:![0-9]*]]} ; [ DW_TAG_reference_type ] [line 0, size 0, align 0, offset 0] [from ]
 
-// CHECK-ITANIUM: metadata !"_ZTS9tmpl_guidIXadu8__uuidoft4uuidEE"} ; [ DW_TAG_structure_type ] [tmpl_guid<&__uuidof(uuid)>]
-// CHECK-ITANIUM: metadata !"_ZTS10tmpl_guid2IXu8__uuidoft4uuidEE"} ; [ DW_TAG_structure_type ] [tmpl_guid2<__uuidof(uuid)>]
+// CHECK-ITANIUM: !"_ZTS9tmpl_guidIXadu8__uuidoft4uuidEE"} ; [ DW_TAG_structure_type ] [tmpl_guid<&__uuidof(uuid)>]
+// CHECK-ITANIUM: !"_ZTS10tmpl_guid2IXu8__uuidoft4uuidEE"} ; [ DW_TAG_structure_type ] [tmpl_guid2<__uuidof(uuid)>]
 
 struct _GUID;
 template <const _GUID *>
diff --git a/test/CodeGenCXX/debug-info-varargs.cpp b/test/CodeGenCXX/debug-info-varargs.cpp
index 6175e65..25e8f35 100644
--- a/test/CodeGenCXX/debug-info-varargs.cpp
+++ b/test/CodeGenCXX/debug-info-varargs.cpp
@@ -2,21 +2,21 @@
 
 struct A
 {
-  // CHECK-DAG: metadata !{metadata !"0x2e\00a\00a\00_ZN1A1aEiz\00[[@LINE+1]]\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[ATY:[0-9]+]]{{.*}}[ DW_TAG_subprogram ]{{.*}}[a]
+  // CHECK-DAG:  !"0x2e\00a\00a\00_ZN1A1aEiz\00[[@LINE+1]]\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[ATY:[0-9]+]]{{.*}}[ DW_TAG_subprogram ]{{.*}}[a]
   void a(int c, ...) {}
-  // CHECK: ![[ATY]] ={{.*}} metadata ![[AARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
+  // CHECK: ![[ATY]] ={{.*}} ![[AARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
   // We no longer use an explicit unspecified parameter. Instead we use a trailing null to mean the function is variadic.
-  // CHECK: ![[AARGS]] = metadata !{null, metadata !{{[0-9]+}}, metadata !{{[0-9]+}}, null}
+  // CHECK: ![[AARGS]] = !{null, !{{[0-9]+}}, !{{[0-9]+}}, null}
 };
 
-  // CHECK: metadata !{metadata !"0x2e\00b\00b\00_Z1biz\00[[@LINE+1]]\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[BTY:[0-9]+]]{{.*}}[ DW_TAG_subprogram ]{{.*}}[b]
+  // CHECK:  !"0x2e\00b\00b\00_Z1biz\00[[@LINE+1]]\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[BTY:[0-9]+]]{{.*}}[ DW_TAG_subprogram ]{{.*}}[b]
 void b(int c, ...) {
-  // CHECK: ![[BTY]] ={{.*}} metadata ![[BARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
-  // CHECK: ![[BARGS]] = metadata !{null, metadata !{{[0-9]+}}, null}
+  // CHECK: ![[BTY]] ={{.*}} ![[BARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
+  // CHECK: ![[BARGS]] = !{null, !{{[0-9]+}}, null}
 
   A a;
 
-  // CHECK: metadata !{metadata !"0x100\00fptr\00[[@LINE+1]]\000"{{, [^,]+, [^,]+}}, metadata ![[PST:[0-9]+]]} ; [ DW_TAG_auto_variable ] [fptr] [line [[@LINE+1]]]
+  // CHECK:  !"0x100\00fptr\00[[@LINE+1]]\000"{{, [^,]+, [^,]+}}, ![[PST:[0-9]+]]} ; [ DW_TAG_auto_variable ] [fptr] [line [[@LINE+1]]]
   void (*fptr)(int, ...) = b;
-  // CHECK: ![[PST]] ={{.*}} metadata ![[BTY]]} ; [ DW_TAG_pointer_type ]
+  // CHECK: ![[PST]] ={{.*}} ![[BTY]]} ; [ DW_TAG_pointer_type ]
 }
diff --git a/test/CodeGenCXX/debug-info-wchar.cpp b/test/CodeGenCXX/debug-info-wchar.cpp
index dff3b3c..5b5fdcc 100644
--- a/test/CodeGenCXX/debug-info-wchar.cpp
+++ b/test/CodeGenCXX/debug-info-wchar.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -emit-llvm -g %s -o -| FileCheck %s
 void foo() {
-// CHECK: metadata !{metadata !"0x24\00wchar_t\00{{.*}}", null, null} ; [ DW_TAG_base_type ] [wchar_t]
+// CHECK:  !"0x24\00wchar_t\00{{.*}}", null, null} ; [ DW_TAG_base_type ] [wchar_t]
   const wchar_t w = L'x';
 }
diff --git a/test/CodeGenCXX/debug-info-windows-dtor.cpp b/test/CodeGenCXX/debug-info-windows-dtor.cpp
new file mode 100644
index 0000000..a94f2b0
--- /dev/null
+++ b/test/CodeGenCXX/debug-info-windows-dtor.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple i386-unknown-windows-msvc -std=c++11 -emit-llvm -gline-tables-only %s -o - | FileCheck %s
+
+struct A {
+  virtual ~A() {}
+};
+
+struct B {
+  virtual ~B() {}
+};
+
+template<typename T>
+struct AB: A, B {
+};
+
+template struct AB<int>;
+
+// CHECK-LABEL: define {{.*}}@"\01??_E?$AB@H@@W3AEPAXI@Z"
+// CHECK: call {{.*}}@"\01??_G?$AB@H@@UAEPAXI@Z"({{.*}}) #{{[0-9]*}}, !dbg [[THUNK_LOC:![0-9]*]]
+// CHECK-LABEL: define
+
+// CHECK: [[THUNK_VEC_DEL_DTOR:![0-9]*]] = {{.*}} @"\01??_E?$AB@H@@W3AEPAXI@Z", {{.*}}; [ DW_TAG_subprogram ]
+// CHECK: [[THUNK_LOC]] = !MDLocation(line: 15, scope: [[THUNK_VEC_DEL_DTOR]])
diff --git a/test/CodeGenCXX/debug-info-zero-length-arrays.cpp b/test/CodeGenCXX/debug-info-zero-length-arrays.cpp
index 144c476..f1ba636 100644
--- a/test/CodeGenCXX/debug-info-zero-length-arrays.cpp
+++ b/test/CodeGenCXX/debug-info-zero-length-arrays.cpp
@@ -6,7 +6,7 @@
 };
 A a;
 
-// CHECK: metadata [[ARRAY_TYPE:![0-9]*]]} ; [ DW_TAG_member ] [x]
-// CHECK: metadata !{metadata !"0x1\00\000\000\0032\000\000\000", null, null, metadata {{![0-9]+}}, metadata [[ELEM_TYPE:![0-9]+]], null, null, null} ; [ DW_TAG_array_type ] [line 0, size 0, align 32, offset 0] [from int]
-// CHECK: [[ELEM_TYPE]] = metadata !{metadata [[SUBRANGE:.*]]}
-// CHECK: [[SUBRANGE]] = metadata !{metadata !"0x21\000\00-1"} ; [ DW_TAG_subrange_type ] [unbounded]
+// CHECK: [[ARRAY_TYPE:![0-9]*]]} ; [ DW_TAG_member ] [x]
+// CHECK:  !"0x1\00\000\000\0032\000\000\000", null, null, {{![0-9]+}}, [[ELEM_TYPE:![0-9]+]], null, null, null} ; [ DW_TAG_array_type ] [line 0, size 0, align 32, offset 0] [from int]
+// CHECK: [[ELEM_TYPE]] = !{[[SUBRANGE:.*]]}
+// CHECK: [[SUBRANGE]] = !{!"0x21\000\00-1"} ; [ DW_TAG_subrange_type ] [unbounded]
diff --git a/test/CodeGenCXX/debug-info.cpp b/test/CodeGenCXX/debug-info.cpp
index 95a53fe..b9002f6 100644
--- a/test/CodeGenCXX/debug-info.cpp
+++ b/test/CodeGenCXX/debug-info.cpp
@@ -53,17 +53,20 @@
   }
 }
 
-// MSVC: [[VBASE_B:![0-9]+]] = metadata !{metadata !"0x13\00B\00{{[0-9]+}}\0096\0032\000\000\000", {{.*}}, null, metadata [[VBASE_B_DEF:![0-9]+]], {{.*}}} ; [ DW_TAG_structure_type ] [B] [line 49, size 96, align 32, offset 0] [def] [from ]
-// MSVC: [[VBASE_B_DEF]] = metadata !{metadata [[VBASE_A_IN_B:![0-9]+]],
+// CHECK: define void @_ZN7pr147634funcENS_3fooE
+// CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[F:.*]], metadata ![[EXPR:.*]])
+
+// MSVC: [[VBASE_B:![0-9]+]] = distinct !{!"0x13\00B\00{{[0-9]+}}\0096\0032\000\000\000", {{.*}}, null, [[VBASE_B_DEF:![0-9]+]], {{.*}}} ; [ DW_TAG_structure_type ] [B] [line 49, size 96, align 32, offset 0] [def] [from ]
+// MSVC: [[VBASE_B_DEF]] = !{[[VBASE_A_IN_B:![0-9]+]],
 //
 // Look for the vbtable offset of A, which should be 4.
-// MSVC: [[VBASE_A_IN_B]] = metadata !{metadata !"0x1c\00\000\000\000\004\0032", null, metadata [[VBASE_B]], metadata !{{[0-9]*}}} ; [ DW_TAG_inheritance ] [line 0, size 0, align 0, offset 4] [from A]
+// MSVC: [[VBASE_A_IN_B]] = !{!"0x1c\00\000\000\000\004\0032", null, [[VBASE_B]], !{{[0-9]*}}} ; [ DW_TAG_inheritance ] [line 0, size 0, align 0, offset 4] [from A]
 
-// CHECK: metadata !{metadata !"0x13\00B\00{{[0-9]+}}\00128\0064\000\000\000", {{.*}}, null, metadata [[VBASE_B_DEF:![0-9]+]], {{.*}}} ; [ DW_TAG_structure_type ] [B] [line 49, size 128, align 64, offset 0] [def] [from ]
-// CHECK: [[VBASE_B_DEF]] = metadata !{metadata [[VBASE_A_IN_B:![0-9]+]],
+// CHECK:  !"0x13\00B\00{{[0-9]+}}\00128\0064\000\000\000", {{.*}}, null, [[VBASE_B_DEF:![0-9]+]], {{.*}}} ; [ DW_TAG_structure_type ] [B] [line 49, size 128, align 64, offset 0] [def] [from ]
+// CHECK: [[VBASE_B_DEF]] = !{[[VBASE_A_IN_B:![0-9]+]],
 //
 // Look for the vtable offset offset, which should be -24.
-// CHECK: [[VBASE_A_IN_B]] = metadata !{metadata !"0x1c\00\000\000\000\0024\0032", null, metadata !"_ZTSN11VirtualBase1BE", metadata !"_ZTSN11VirtualBase1AE"} ; [ DW_TAG_inheritance ] [line 0, size 0, align 0, offset 24] [from _ZTSN11VirtualBase1AE]
+// CHECK: [[VBASE_A_IN_B]] = !{!"0x1c\00\000\000\000\0024\0032", null, !"_ZTSN11VirtualBase1BE", !"_ZTSN11VirtualBase1AE"} ; [ DW_TAG_inheritance ] [line 0, size 0, align 0, offset 24] [from _ZTSN11VirtualBase1AE]
 namespace b5249287 {
 template <typename T> class A {
   struct B;
@@ -85,15 +88,15 @@
   return f; // reference 'f' for now because otherwise we hit another bug
 }
 
-// CHECK: metadata !{metadata !"0x13\00{{.*}}", metadata !{{[0-9]*}}, metadata [[PR14763:![0-9]*]], {{.*}}, metadata !"[[FOO:.*]]"} ; [ DW_TAG_structure_type ] [foo]
+// CHECK:  !"0x13\00{{.*}}", !{{[0-9]*}}, [[PR14763:![0-9]*]], {{.*}}, !"[[FOO:.*]]"} ; [ DW_TAG_structure_type ] [foo]
 // CHECK: [[PR14763]] = {{.*}} ; [ DW_TAG_namespace ] [pr14763]
 // CHECK: [[INCTYPE:![0-9]*]] = {{.*}} ; [ DW_TAG_structure_type ] [incomplete]{{.*}} [decl]
-// CHECK: metadata [[A_MEM:![0-9]*]], null, null, metadata !"_ZTSN7pr162141aE"} ; [ DW_TAG_structure_type ] [a]
-// CHECK: [[A_MEM]] = metadata !{metadata [[A_I:![0-9]*]]}
+// CHECK: [[A_MEM:![0-9]*]], null, null, !"_ZTSN7pr162141aE"} ; [ DW_TAG_structure_type ] [a]
+// CHECK: [[A_MEM]] = !{[[A_I:![0-9]*]]}
 // CHECK: [[A_I]] = {{.*}} ; [ DW_TAG_member ] [i] {{.*}} [from int]
 // CHECK: ; [ DW_TAG_structure_type ] [b] {{.*}}[decl]
 
-// CHECK: [[FUNC:![0-9]*]] = metadata !{metadata !"0x2e\00func\00func\00_ZN7pr147634funcENS_3fooE\00{{.*}}"{{, [^,]+, [^,]+}}, metadata [[FUNC_TYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
+// CHECK: [[FUNC:![0-9]*]] = !{!"0x2e\00func\00func\00_ZN7pr147634funcENS_3fooE\00{{.*}}"{{, [^,]+, [^,]+}}, [[FUNC_TYPE:![0-9]*]], {{.*}} ; [ DW_TAG_subprogram ] {{.*}} [def] [func]
 }
 
 void foo() {
@@ -106,13 +109,14 @@
 namespace pr9608 { // also pr9600
 struct incomplete;
 incomplete (*x)[3];
-// CHECK: metadata [[INCARRAYPTR:![0-9]*]], [3 x i8]** @_ZN6pr96081xE, null} ; [ DW_TAG_variable ] [x]
-// CHECK: [[INCARRAYPTR]] = {{.*}}metadata [[INCARRAY:![0-9]*]]} ; [ DW_TAG_pointer_type ]
-// CHECK: [[INCARRAY]] = metadata !{metadata !"0x1\00\000\000\000\000\000\000", null, null, metadata !"_ZTSN6pr960810incompleteE", metadata {{![0-9]+}}, null, null, null} ; [ DW_TAG_array_type ] [line 0, size 0, align 0, offset 0] [from _ZTSN6pr960810incompleteE]
+// CHECK: [[INCARRAYPTR:![0-9]*]], [3 x i8]** @_ZN6pr96081xE, null} ; [ DW_TAG_variable ] [x]
+// CHECK: [[INCARRAYPTR]] = {{.*}}[[INCARRAY:![0-9]*]]} ; [ DW_TAG_pointer_type ]
+// CHECK: [[INCARRAY]] = !{!"0x1\00\000\000\000\000\000\000", null, null, !"_ZTSN6pr960810incompleteE", {{![0-9]+}}, null, null, null} ; [ DW_TAG_array_type ] [line 0, size 0, align 0, offset 0] [from _ZTSN6pr960810incompleteE]
 }
 
 // For some reason function arguments ended up down here
-// CHECK: = metadata !{metadata !"0x101\00f\00{{.*}}\008192", metadata [[FUNC]], metadata {{![0-9]+}}, metadata !"[[FOO]]"} ; [ DW_TAG_arg_variable ] [f]
+// CHECK: ![[F]] = !{!"0x101\00f\00{{.*}}\000", [[FUNC]], {{![0-9]+}}, !"[[FOO]]"} ; [ DW_TAG_arg_variable ] [f]
+// CHECK: ![[EXPR]] = {{.*}} ; [ DW_TAG_expression ] [DW_OP_deref]
 
 // CHECK: ; [ DW_TAG_auto_variable ] [c]
 
diff --git a/test/CodeGenCXX/debug-lambda-expressions.cpp b/test/CodeGenCXX/debug-lambda-expressions.cpp
index f8ccbae..ac84036 100644
--- a/test/CodeGenCXX/debug-lambda-expressions.cpp
+++ b/test/CodeGenCXX/debug-lambda-expressions.cpp
@@ -29,39 +29,38 @@
 // D: 18
 // CHECK: [[D_FUNC:.*]] = {{.*}} [ DW_TAG_subprogram ] [line [[D_LINE:.*]]] [def] [d]
 
-// Back to D. -- 24
-// CHECK: [[LAM_D:.*]] = {{.*}}, metadata [[D_FUNC]], {{.*}}, metadata [[LAM_D_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[D_LINE]],
-// CHECK: [[LAM_D_ARGS]] = metadata !{metadata [[CAP_D_X:.*]], metadata [[CAP_D_Y:.*]], metadata [[CON_LAM_D:.*]]}
-// CHECK: [[CAP_D_X]] = {{.*}}, metadata [[LAM_D]], {{.*}} [ DW_TAG_member ] [x] [line [[D_LINE]],
-// CHECK: [[CAP_D_Y]] = {{.*}}, metadata [[LAM_D]], {{.*}} [ DW_TAG_member ] [y] [line [[D_LINE]],
-// CHECK: [[CON_LAM_D]] = {{.*}}, metadata [[LAM_D]], {{.*}} [ DW_TAG_subprogram ] [line [[D_LINE]]] [public] [operator()]
-
-
-// Back to C. -- 55
-// CHECK: [[LAM_C:.*]] = {{.*}}, metadata [[C_FUNC]], {{.*}}, metadata [[LAM_C_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[C_LINE]],
-// CHECK: [[LAM_C_ARGS]] = metadata !{metadata [[CAP_C:.*]], metadata [[CON_LAM_C:.*]]}
-// Ignoring the member type for now.
-// CHECK: [[CAP_C]] = {{.*}}, metadata [[LAM_C]], {{.*}}} ; [ DW_TAG_member ] [x] [line [[C_LINE]],
-// CHECK: [[CON_LAM_C]] = {{.*}}, metadata [[LAM_C]], {{.*}} [ DW_TAG_subprogram ] [line [[C_LINE]]] [public] [operator()]
-
-
-// Back to B. -- 67
-// CHECK: [[LAM_B:.*]] = {{.*}}, metadata [[B_FUNC]], {{.*}}, metadata [[LAM_B_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[B_LINE]],
-// CHECK: [[LAM_B_ARGS]] = metadata !{metadata [[CAP_B:.*]], metadata [[CON_LAM_B:.*]]}
-// CHECK: [[CAP_B]] = {{.*}}, metadata [[LAM_B]], {{.*}}} ; [ DW_TAG_member ] [x] [line [[B_LINE]],
-// CHECK: [[CON_LAM_B]] = {{.*}}, metadata [[LAM_B]], {{.*}} [ DW_TAG_subprogram ] [line [[B_LINE]]] [public] [operator()]
 
 // Back to A. -- 78
-// CHECK: [[LAM_A:.*]] = {{.*}}, metadata [[A_FUNC]], {{.*}}, metadata [[LAM_A_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[A_LINE]],
-// CHECK: [[LAM_A_ARGS]] = metadata !{metadata [[CON_LAM_A:.*]]}
-// CHECK: [[CON_LAM_A]] = {{.*}}, metadata [[LAM_A]], {{.*}} [ DW_TAG_subprogram ] [line [[A_LINE]]] [public] [operator()]
+// CHECK: [[LAM_A:.*]] = {{.*}}, [[A_FUNC]], {{.*}}, [[LAM_A_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[A_LINE]],
+// CHECK: [[LAM_A_ARGS]] = !{[[CON_LAM_A:.*]]}
+// CHECK: [[CON_LAM_A]] = {{.*}}, [[LAM_A]], {{.*}} [ DW_TAG_subprogram ] [line [[A_LINE]]] [public] [operator()]
+
+// Back to B. -- 67
+// CHECK: [[LAM_B:.*]] = {{.*}}, [[B_FUNC]], {{.*}}, [[LAM_B_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[B_LINE]],
+// CHECK: [[LAM_B_ARGS]] = !{[[CAP_B:.*]], [[CON_LAM_B:.*]]}
+// CHECK: [[CAP_B]] = {{.*}}, [[LAM_B]], {{.*}}} ; [ DW_TAG_member ] [x] [line [[B_LINE]],
+// CHECK: [[CON_LAM_B]] = {{.*}}, [[LAM_B]], {{.*}} [ DW_TAG_subprogram ] [line [[B_LINE]]] [public] [operator()]
+
+// Back to C. -- 55
+// CHECK: [[LAM_C:.*]] = {{.*}}, [[C_FUNC]], {{.*}}, [[LAM_C_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[C_LINE]],
+// CHECK: [[LAM_C_ARGS]] = !{[[CAP_C:.*]], [[CON_LAM_C:.*]]}
+// Ignoring the member type for now.
+// CHECK: [[CAP_C]] = {{.*}}, [[LAM_C]], {{.*}}} ; [ DW_TAG_member ] [x] [line [[C_LINE]],
+// CHECK: [[CON_LAM_C]] = {{.*}}, [[LAM_C]], {{.*}} [ DW_TAG_subprogram ] [line [[C_LINE]]] [public] [operator()]
+
+// Back to D. -- 24
+// CHECK: [[LAM_D:.*]] = {{.*}}, [[D_FUNC]], {{.*}}, [[LAM_D_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[D_LINE]],
+// CHECK: [[LAM_D_ARGS]] = !{[[CAP_D_X:.*]], [[CAP_D_Y:.*]], [[CON_LAM_D:.*]]}
+// CHECK: [[CAP_D_X]] = {{.*}}, [[LAM_D]], {{.*}} [ DW_TAG_member ] [x] [line [[D_LINE]],
+// CHECK: [[CAP_D_Y]] = {{.*}}, [[LAM_D]], {{.*}} [ DW_TAG_member ] [y] [line [[D_LINE]],
+// CHECK: [[CON_LAM_D]] = {{.*}}, [[LAM_D]], {{.*}} [ DW_TAG_subprogram ] [line [[D_LINE]]] [public] [operator()]
 
 // CVAR:
-// CHECK: {{.*}} metadata [[CVAR_T:![0-9]*]], {{.*}} ; [ DW_TAG_variable ] [cvar] [line [[CVAR_LINE:[0-9]*]]] 
-// CHECK: [[CVAR_T]] = {{.*}}, metadata ![[CVAR_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[CVAR_LINE]],
-// CHECK: [[CVAR_ARGS]] = metadata !{metadata !{{.*}}}
+// CHECK: {{.*}} [[CVAR_T:![0-9]*]], {{.*}} ; [ DW_TAG_variable ] [cvar] [line [[CVAR_LINE:[0-9]*]]] 
+// CHECK: [[CVAR_T]] = {{.*}}, ![[CVAR_ARGS:.*]], null, null, null} ; [ DW_TAG_class_type ] [line [[CVAR_LINE]],
+// CHECK: [[CVAR_ARGS]] = !{!{{.*}}}
 
 // VAR:
-// CHECK: {{.*}} metadata [[VAR_T:![0-9]*]], {{.*}} ; [ DW_TAG_variable ] [var] [line [[VAR_LINE:[0-9]*]]]
-// CHECK: [[VAR_T]] = {{.*}}, metadata [[VAR_ARGS:![0-9]*]], null, null, null} ; [ DW_TAG_class_type ] [line [[VAR_LINE]],
-// CHECK: [[VAR_ARGS]] = metadata !{metadata !{{.*}}}
+// CHECK: {{.*}} [[VAR_T:![0-9]*]], {{.*}} ; [ DW_TAG_variable ] [var] [line [[VAR_LINE:[0-9]*]]]
+// CHECK: [[VAR_T]] = {{.*}}, [[VAR_ARGS:![0-9]*]], null, null, null} ; [ DW_TAG_class_type ] [line [[VAR_LINE]],
+// CHECK: [[VAR_ARGS]] = !{!{{.*}}}
diff --git a/test/CodeGenCXX/destructor-debug-info.cpp b/test/CodeGenCXX/destructor-debug-info.cpp
index f2e2a39..a8abfde 100644
--- a/test/CodeGenCXX/destructor-debug-info.cpp
+++ b/test/CodeGenCXX/destructor-debug-info.cpp
@@ -19,4 +19,4 @@
   }
 }
 // Check there is a line number entry for line 19 where b1 is destructed.
-// CHECK: i32 19, i32 0, metadata
+// CHECK: !MDLocation(line: 19,
diff --git a/test/CodeGenCXX/destructors.cpp b/test/CodeGenCXX/destructors.cpp
index bc9a683..1f05cae 100644
--- a/test/CodeGenCXX/destructors.cpp
+++ b/test/CodeGenCXX/destructors.cpp
@@ -185,6 +185,11 @@
     new D; // Force emission of D's vtable
   }
 
+  // CHECK4-LABEL: define internal void @_ZN5test312_GLOBAL__N_11CD2Ev(%"struct.test3::(anonymous namespace)::C"* %this) unnamed_addr
+  // CHECK4: invoke void @_ZN5test31BD2Ev(
+  // CHECK4: call void @_ZN5test31AD2Ev(
+  // CHECK4: ret void
+
   // CHECK4-LABEL: define internal void @_ZN5test312_GLOBAL__N_11DD0Ev(%"struct.test3::(anonymous namespace)::D"* %this) unnamed_addr
   // CHECK4: invoke void {{.*}} @_ZN5test312_GLOBAL__N_11CD2Ev
   // CHECK4: call void @_ZdlPv({{.*}}) [[NUW:#[0-9]+]]
@@ -204,15 +209,6 @@
   // CHECK4: call void @_ZN5test312_GLOBAL__N_11DD0Ev(
   // CHECK4: ret void
 
-  // CHECK4-LABEL: declare void @_ZN5test31BD2Ev(
-  // CHECK4-LABEL: declare void @_ZN5test31AD2Ev(
-
-  // CHECK4-LABEL: define internal void @_ZN5test312_GLOBAL__N_11CD2Ev(%"struct.test3::(anonymous namespace)::C"* %this) unnamed_addr
-  // CHECK4: invoke void @_ZN5test31BD2Ev(
-  // CHECK4: call void @_ZN5test31AD2Ev(
-  // CHECK4: ret void
-
-
   // CHECK4-LABEL: define internal void @_ZN5test312_GLOBAL__N_11CD0Ev(%"struct.test3::(anonymous namespace)::C"* %this) unnamed_addr
   // CHECK4: invoke void @_ZN5test312_GLOBAL__N_11CD2Ev(
   // CHECK4: call void @_ZdlPv({{.*}}) [[NUW]]
@@ -232,6 +228,9 @@
   // CHECK4: call void @_ZN5test312_GLOBAL__N_11CD0Ev(
   // CHECK4: ret void
 
+  // CHECK4-LABEL: declare void @_ZN5test31BD2Ev(
+  // CHECK4-LABEL: declare void @_ZN5test31AD2Ev(
+
   // CHECK4: attributes [[NUW]] = {{[{].*}} nounwind {{.*[}]}}
 }
 
diff --git a/test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp b/test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
index 89c9a61..193ee5f 100644
--- a/test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
+++ b/test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
@@ -53,26 +53,32 @@
 namespace Test4 {
   struct A {
     virtual void f();
+    virtual int operator-();
   };
 
   struct B final : A {
     virtual void f();
+    virtual int operator-();
   };
 
   // CHECK-LABEL: define void @_ZN5Test41fEPNS_1BE
   void f(B* d) {
     // CHECK: call void @_ZN5Test41B1fEv
     static_cast<A*>(d)->f();
+    // CHECK: call i32 @_ZN5Test41BngEv
+    -static_cast<A&>(*d);
   }
 }
 
 namespace Test5 {
   struct A {
     virtual void f();
+    virtual int operator-();
   };
 
   struct B : A {
     virtual void f();
+    virtual int operator-();
   };
 
   struct C final : B {
@@ -87,6 +93,15 @@
     // CHECK-NEXT: call void %[[FUNC]]
     static_cast<A*>(d)->f();
   }
+  // CHECK-LABEL: define void @_ZN5Test53fopEPNS_1CE
+  void fop(C* d) {
+    // FIXME: It should be possible to devirtualize this case, but that is
+    // not implemented yet.
+    // CHECK: getelementptr
+    // CHECK-NEXT: %[[FUNC:.*]] = load
+    // CHECK-NEXT: call i32 %[[FUNC]]
+    -static_cast<A&>(*d);
+  }
 }
 
 namespace Test6 {
@@ -165,6 +180,9 @@
     virtual A *f() {
       return 0;
     }
+    virtual A *operator-() {
+      return 0;
+    }
   };
   struct RC final : public RA {
     virtual C *f() {
@@ -173,6 +191,12 @@
       x->b = 2;
       return x;
     }
+    virtual C *operator-() {
+      C *x = new C();
+      x->a = 1;
+      x->b = 2;
+      return x;
+    }
   };
   // CHECK: define {{.*}} @_ZN5Test91fEPNS_2RCE
   A *f(RC *x) {
@@ -187,4 +211,17 @@
     // CHECK-NEXT: = call {{.*}} %[[FUNC]]
     return static_cast<RA*>(x)->f();
   }
+  // CHECK: define {{.*}} @_ZN5Test93fopEPNS_2RCE
+  A *fop(RC *x) {
+    // FIXME: It should be possible to devirtualize this case, but that is
+    // not implemented yet.
+    // CHECK: load
+    // CHECK: bitcast
+    // CHECK: [[F_PTR_RA:%.+]] = bitcast
+    // CHECK: [[VTABLE:%.+]] = load {{.+}} [[F_PTR_RA]]
+    // CHECK: [[VFN:%.+]] = getelementptr inbounds {{.+}} [[VTABLE]], i{{[0-9]+}} 1
+    // CHECK-NEXT: %[[FUNC:.*]] = load {{.+}} [[VFN]]
+    // CHECK-NEXT: = call {{.*}} %[[FUNC]]
+    return -static_cast<RA&>(*x);
+  }
 }
diff --git a/test/CodeGenCXX/dllexport-members.cpp b/test/CodeGenCXX/dllexport-members.cpp
index d913c09..5b2af1e 100644
--- a/test/CodeGenCXX/dllexport-members.cpp
+++ b/test/CodeGenCXX/dllexport-members.cpp
@@ -110,9 +110,9 @@
 
   // MSC-DAG: @"\01?StaticField@ExportMembers@@2HA"               = dllexport global i32 1, align 4
   // MSC-DAG: @"\01?StaticConstField@ExportMembers@@2HB"          = dllexport constant i32 1, align 4
-  // MSC-DAG: @"\01?StaticConstFieldEqualInit@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, align 4
-  // MSC-DAG: @"\01?StaticConstFieldBraceInit@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, align 4
-  // MSC-DAG: @"\01?ConstexprField@ExportMembers@@2HB"            = weak_odr dllexport constant i32 1, align 4
+  // MSC-DAG: @"\01?StaticConstFieldEqualInit@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+  // MSC-DAG: @"\01?StaticConstFieldBraceInit@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+  // MSC-DAG: @"\01?ConstexprField@ExportMembers@@2HB"            = weak_odr dllexport constant i32 1, comdat, align 4
   // GNU-DAG: @_ZN13ExportMembers11StaticFieldE                   = dllexport global i32 1, align 4
   // GNU-DAG: @_ZN13ExportMembers16StaticConstFieldE              = dllexport constant i32 1, align 4
   // GNU-DAG: @_ZN13ExportMembers25StaticConstFieldEqualInitE     = dllexport constant i32 1, align 4
@@ -233,9 +233,9 @@
 
   // MSC-DAG: @"\01?StaticField@Nested@ExportMembers@@2HA"               = dllexport global i32 1, align 4
   // MSC-DAG: @"\01?StaticConstField@Nested@ExportMembers@@2HB"          = dllexport constant i32 1, align 4
-  // MSC-DAG: @"\01?StaticConstFieldEqualInit@Nested@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, align 4
-  // MSC-DAG: @"\01?StaticConstFieldBraceInit@Nested@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, align 4
-  // MSC-DAG: @"\01?ConstexprField@Nested@ExportMembers@@2HB"            = weak_odr dllexport constant i32 1, align 4
+  // MSC-DAG: @"\01?StaticConstFieldEqualInit@Nested@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+  // MSC-DAG: @"\01?StaticConstFieldBraceInit@Nested@ExportMembers@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+  // MSC-DAG: @"\01?ConstexprField@Nested@ExportMembers@@2HB"            = weak_odr dllexport constant i32 1, comdat, align 4
   // GNU-DAG: @_ZN13ExportMembers6Nested11StaticFieldE                   = dllexport global i32 1, align 4
   // GNU-DAG: @_ZN13ExportMembers6Nested16StaticConstFieldE              = dllexport constant i32 1, align 4
   // GNU-DAG: @_ZN13ExportMembers6Nested25StaticConstFieldEqualInitE     = dllexport constant i32 1, align 4
@@ -599,21 +599,21 @@
 template<typename T> const int MemVarTmpl::ExportedStaticVar;
 
 // Export implicit instantiation of an exported member variable template.
-// MSC-DAG: @"\01??$ExportedStaticVar@UImplicitInst_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, align 4
-// GNU-DAG: @_ZN10MemVarTmpl17ExportedStaticVarI21ImplicitInst_ExportedEE       = weak_odr dllexport constant i32 1, align 4
+// MSC-DAG: @"\01??$ExportedStaticVar@UImplicitInst_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+// GNU-DAG: @_ZN10MemVarTmpl17ExportedStaticVarI21ImplicitInst_ExportedEE       = weak_odr dllexport constant i32 1, comdat, align 4
 int useMemVarTmpl() { return MemVarTmpl::ExportedStaticVar<ImplicitInst_Exported>; }
 
 // Export explicit instantiation declaration of an exported member variable
 // template.
-// MSC-DAG: @"\01??$ExportedStaticVar@UExplicitDecl_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, align 4
-// GNU-DAG: @_ZN10MemVarTmpl17ExportedStaticVarI21ExplicitDecl_ExportedEE       = weak_odr dllexport constant i32 1, align 4
+// MSC-DAG: @"\01??$ExportedStaticVar@UExplicitDecl_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+// GNU-DAG: @_ZN10MemVarTmpl17ExportedStaticVarI21ExplicitDecl_ExportedEE       = weak_odr dllexport constant i32 1, comdat, align 4
 extern template const int MemVarTmpl::ExportedStaticVar<ExplicitDecl_Exported>;
        template const int MemVarTmpl::ExportedStaticVar<ExplicitDecl_Exported>;
 
 // Export explicit instantiation definition of an exported member variable
 // template.
-// MSC-DAG: @"\01??$ExportedStaticVar@UExplicitInst_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, align 4
-// GNU-DAG: @_ZN10MemVarTmpl17ExportedStaticVarI21ExplicitInst_ExportedEE       = weak_odr dllexport constant i32 1, align 4
+// MSC-DAG: @"\01??$ExportedStaticVar@UExplicitInst_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+// GNU-DAG: @_ZN10MemVarTmpl17ExportedStaticVarI21ExplicitInst_ExportedEE       = weak_odr dllexport constant i32 1, comdat, align 4
 template const int MemVarTmpl::ExportedStaticVar<ExplicitInst_Exported>;
 
 // Export specialization of an exported member variable template.
@@ -630,15 +630,15 @@
 
 // Export explicit instantiation declaration of a non-exported member variable
 // template.
-// MSC-DAG: @"\01??$StaticVar@UExplicitDecl_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, align 4
-// GNU-DAG: @_ZN10MemVarTmpl9StaticVarI21ExplicitDecl_ExportedEE        = weak_odr dllexport constant i32 1, align 4
+// MSC-DAG: @"\01??$StaticVar@UExplicitDecl_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+// GNU-DAG: @_ZN10MemVarTmpl9StaticVarI21ExplicitDecl_ExportedEE        = weak_odr dllexport constant i32 1, comdat, align 4
 extern template __declspec(dllexport) const int MemVarTmpl::StaticVar<ExplicitDecl_Exported>;
        template __declspec(dllexport) const int MemVarTmpl::StaticVar<ExplicitDecl_Exported>;
 
 // Export explicit instantiation definition of a non-exported member variable
 // template.
-// MSC-DAG: @"\01??$StaticVar@UExplicitInst_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, align 4
-// GNU-DAG: @_ZN10MemVarTmpl9StaticVarI21ExplicitInst_ExportedEE        = weak_odr dllexport constant i32 1, align 4
+// MSC-DAG: @"\01??$StaticVar@UExplicitInst_Exported@@@MemVarTmpl@@2HB" = weak_odr dllexport constant i32 1, comdat, align 4
+// GNU-DAG: @_ZN10MemVarTmpl9StaticVarI21ExplicitInst_ExportedEE        = weak_odr dllexport constant i32 1, comdat, align 4
 template __declspec(dllexport) const int MemVarTmpl::StaticVar<ExplicitInst_Exported>;
 
 // Export specialization of a non-exported member variable template.
diff --git a/test/CodeGenCXX/dllexport.cpp b/test/CodeGenCXX/dllexport.cpp
index 0878dff..5532a7d 100644
--- a/test/CodeGenCXX/dllexport.cpp
+++ b/test/CodeGenCXX/dllexport.cpp
@@ -1,7 +1,7 @@
-// RUN: %clang_cc1 -triple i686-windows-msvc   -emit-llvm -std=c++1y -O1 -mconstructor-aliases -disable-llvm-optzns -o - %s | FileCheck --check-prefix=MSC --check-prefix=M32 %s
-// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -std=c++1y -O0 -o - %s | FileCheck --check-prefix=MSC --check-prefix=M64 %s
-// RUN: %clang_cc1 -triple i686-windows-gnu    -emit-llvm -std=c++1y -O0 -o - %s | FileCheck --check-prefix=GNU --check-prefix=G32 %s
-// RUN: %clang_cc1 -triple x86_64-windows-gnu  -emit-llvm -std=c++1y -O0 -o - %s | FileCheck --check-prefix=GNU --check-prefix=G64 %s
+// RUN: %clang_cc1 -triple i686-windows-msvc   -emit-llvm -std=c++1y -O1 -mconstructor-aliases -disable-llvm-optzns -o - %s -w | FileCheck --check-prefix=MSC --check-prefix=M32 %s
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -std=c++1y -O0 -o - %s -w | FileCheck --check-prefix=MSC --check-prefix=M64 %s
+// RUN: %clang_cc1 -triple i686-windows-gnu    -emit-llvm -std=c++1y -O0 -o - %s -w | FileCheck --check-prefix=GNU --check-prefix=G32 %s
+// RUN: %clang_cc1 -triple x86_64-windows-gnu  -emit-llvm -std=c++1y -O0 -o - %s -w | FileCheck --check-prefix=GNU --check-prefix=G64 %s
 
 // Helper structs to make templates more expressive.
 struct ImplicitInst_Exported {};
@@ -82,8 +82,8 @@
   return x++;
 };
 
-// MSC-DAG: @"\01?x@?1??inlineStaticLocalsFunc@@YAHXZ@4HA" = weak_odr dllexport global i32 0
-// MSC-DAG: @"\01??_B?1??inlineStaticLocalsFunc@@YAHXZ@51" = weak_odr dllexport global i32 0
+// MSC-DAG: @"\01?x@?1??inlineStaticLocalsFunc@@YAHXZ@4HA" = weak_odr dllexport global i32 0, comdat
+// MSC-DAG: @"\01??_B?1??inlineStaticLocalsFunc@@YAHXZ@51" = weak_odr dllexport global i32 0, comdat
 // Note: MinGW doesn't seem to export the static local here.
 inline int __declspec(dllexport) inlineStaticLocalsFunc() {
   static int x = f();
@@ -110,43 +110,43 @@
 USEVAR(VarTmplImplicitDef<ImplicitInst_Exported>)
 
 // Export definition.
-// MSC-DAG: @"\01??$VarTmplInit1@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z12VarTmplInit1I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmplInit1@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z12VarTmplInit1I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 template<typename T> __declspec(dllexport) int VarTmplInit1 = 1;
 INSTVAR(VarTmplInit1<ExplicitInst_Exported>)
 
-// MSC-DAG: @"\01??$VarTmplInit2@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z12VarTmplInit2I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmplInit2@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z12VarTmplInit2I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 template<typename T> int __declspec(dllexport) VarTmplInit2 = 1;
 INSTVAR(VarTmplInit2<ExplicitInst_Exported>)
 
 // Declare, then export definition.
-// MSC-DAG: @"\01??$VarTmplDeclInit@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z15VarTmplDeclInitI21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmplDeclInit@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z15VarTmplDeclInitI21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 template<typename T> __declspec(dllexport) extern int VarTmplDeclInit;
 template<typename T>                              int VarTmplDeclInit = 1;
 INSTVAR(VarTmplDeclInit<ExplicitInst_Exported>)
 
 // Redeclarations
-// MSC-DAG: @"\01??$VarTmplRedecl1@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z14VarTmplRedecl1I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmplRedecl1@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z14VarTmplRedecl1I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 template<typename T> __declspec(dllexport) extern int VarTmplRedecl1;
 template<typename T> __declspec(dllexport)        int VarTmplRedecl1 = 1;
 INSTVAR(VarTmplRedecl1<ExplicitInst_Exported>)
 
-// MSC-DAG: @"\01??$VarTmplRedecl2@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z14VarTmplRedecl2I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmplRedecl2@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z14VarTmplRedecl2I21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 template<typename T> __declspec(dllexport) extern int VarTmplRedecl2;
 template<typename T>                              int VarTmplRedecl2 = 1;
 INSTVAR(VarTmplRedecl2<ExplicitInst_Exported>)
 
-// MSC-DAG: @"\01??$ExternalVarTmpl@UExplicitInst_Exported@@@ns@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_ZN2ns15ExternalVarTmplI21ExplicitInst_ExportedEE        = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$ExternalVarTmpl@UExplicitInst_Exported@@@ns@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_ZN2ns15ExternalVarTmplI21ExplicitInst_ExportedEE        = weak_odr dllexport global i32 1, comdat, align 4
 namespace ns { template<typename T> __declspec(dllexport) int ExternalVarTmpl = 1; }
 INSTVAR(ns::ExternalVarTmpl<ExplicitInst_Exported>)
 
-// MSC-DAG: @"\01??$ExternalAutoTypeVarTmpl@UExplicitInst_Exported@@@@3UExternal@@A" = weak_odr dllexport global %struct.External zeroinitializer, align 4
-// GNU-DAG: @_Z23ExternalAutoTypeVarTmplI21ExplicitInst_ExportedE                    = weak_odr dllexport global %struct.External zeroinitializer, align 4
+// MSC-DAG: @"\01??$ExternalAutoTypeVarTmpl@UExplicitInst_Exported@@@@3UExternal@@A" = weak_odr dllexport global %struct.External zeroinitializer, comdat, align 4
+// GNU-DAG: @_Z23ExternalAutoTypeVarTmplI21ExplicitInst_ExportedE                    = weak_odr dllexport global %struct.External zeroinitializer, comdat, align 4
 template<typename T> __declspec(dllexport) auto ExternalAutoTypeVarTmpl = External();
 template External ExternalAutoTypeVarTmpl<ExplicitInst_Exported>;
 
@@ -155,19 +155,19 @@
 template<typename T> __declspec(dllexport) int ExportedVarTmpl = 1;
 
 // Export implicit instantiation of an exported variable template.
-// MSC-DAG: @"\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z15ExportedVarTmplI21ImplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z15ExportedVarTmplI21ImplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 USEVAR(ExportedVarTmpl<ImplicitInst_Exported>)
 
 // Export explicit instantiation declaration of an exported variable template.
-// MSC-DAG: @"\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z15ExportedVarTmplI21ExplicitDecl_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z15ExportedVarTmplI21ExplicitDecl_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 extern template int ExportedVarTmpl<ExplicitDecl_Exported>;
        template int ExportedVarTmpl<ExplicitDecl_Exported>;
 
 // Export explicit instantiation definition of an exported variable template.
-// MSC-DAG: @"\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z15ExportedVarTmplI21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$ExportedVarTmpl@UImplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z15ExportedVarTmplI21ExplicitInst_ExportedE          = weak_odr dllexport global i32 1, comdat, align 4
 template __declspec(dllexport) int ExportedVarTmpl<ExplicitInst_Exported>;
 
 // Export specialization of an exported variable template.
@@ -187,14 +187,14 @@
 
 
 // Export explicit instantiation declaration of a non-exported variable template.
-// MSC-DAG: @"\01??$VarTmpl@UExplicitDecl_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z7VarTmplI21ExplicitDecl_ExportedE           = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmpl@UExplicitDecl_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z7VarTmplI21ExplicitDecl_ExportedE           = weak_odr dllexport global i32 1, comdat, align 4
 extern template __declspec(dllexport) int VarTmpl<ExplicitDecl_Exported>;
        template __declspec(dllexport) int VarTmpl<ExplicitDecl_Exported>;
 
 // Export explicit instantiation definition of a non-exported variable template.
-// MSC-DAG: @"\01??$VarTmpl@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, align 4
-// GNU-DAG: @_Z7VarTmplI21ExplicitInst_ExportedE           = weak_odr dllexport global i32 1, align 4
+// MSC-DAG: @"\01??$VarTmpl@UExplicitInst_Exported@@@@3HA" = weak_odr dllexport global i32 1, comdat, align 4
+// GNU-DAG: @_Z7VarTmplI21ExplicitInst_ExportedE           = weak_odr dllexport global i32 1, comdat, align 4
 template __declspec(dllexport) int VarTmpl<ExplicitInst_Exported>;
 
 // Export specialization of a non-exported variable template.
@@ -511,15 +511,16 @@
 // U<int>'s assignment operator is emitted.
 // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable({{[0-9]+}}) %struct.U* @"\01??4?$U@H@@QAEAAU0@ABU0@@Z"
 
-struct __declspec(dllexport) W { virtual void foo() {} };
+struct __declspec(dllexport) W { virtual void foo(); };
+void W::foo() {}
 // Default ctor:
 // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.W* @"\01??0W@@QAE@XZ"
 // Copy ctor:
 // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.W* @"\01??0W@@QAE@ABU0@@Z"
 // vftable:
-// M32-DAG: [[W_VTABLE:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast (%rtti.CompleteObjectLocator* @"\01??_R4W@@6B@" to i8*), i8* bitcast (void (%struct.W*)* @"\01?foo@W@@UAEXXZ" to i8*)], comdat $"\01??_7W@@6B@"
+// M32-DAG: [[W_VTABLE:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast (%rtti.CompleteObjectLocator* @"\01??_R4W@@6B@" to i8*), i8* bitcast (void (%struct.W*)* @"\01?foo@W@@UAEXXZ" to i8*)], comdat($"\01??_7W@@6B@")
 // M32-DAG: @"\01??_7W@@6B@" = dllexport unnamed_addr alias getelementptr inbounds ([2 x i8*]* [[W_VTABLE]], i32 0, i32 1)
-// G32-DAG: @_ZTV1W = weak_odr dllexport unnamed_addr constant [3 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTI1W to i8*), i8* bitcast (void (%struct.W*)* @_ZN1W3fooEv to i8*)]
+// G32-DAG: @_ZTV1W = dllexport unnamed_addr constant [3 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTI1W to i8*), i8* bitcast (void (%struct.W*)* @_ZN1W3fooEv to i8*)]
 
 struct __declspec(dllexport) X : public virtual W {};
 // vbtable:
@@ -573,17 +574,19 @@
 
 // MS ignores DLL attributes on partial specializations.
 template <typename T> struct PartiallySpecializedClassTemplate {};
-template <typename T> struct __declspec(dllexport) PartiallySpecializedClassTemplate<T*> { void f() {} };
+template <typename T> struct __declspec(dllexport) PartiallySpecializedClassTemplate<T*> { void f(); };
+template <typename T> void PartiallySpecializedClassTemplate<T*>::f() {}
 USEMEMFUNC(PartiallySpecializedClassTemplate<void*>, f);
 // M32-DAG: define linkonce_odr x86_thiscallcc void @"\01?f@?$PartiallySpecializedClassTemplate@PAX@@QAEXXZ"
 // G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN33PartiallySpecializedClassTemplateIPvE1fEv
 
 // Attributes on explicit specializations are honored.
 template <typename T> struct ExplicitlySpecializedClassTemplate {};
-template <> struct __declspec(dllexport) ExplicitlySpecializedClassTemplate<void*> { void f() {} };
+template <> struct __declspec(dllexport) ExplicitlySpecializedClassTemplate<void*> { void f(); };
+void ExplicitlySpecializedClassTemplate<void*>::f() {}
 USEMEMFUNC(ExplicitlySpecializedClassTemplate<void*>, f);
-// M32-DAG: define weak_odr dllexport x86_thiscallcc void @"\01?f@?$ExplicitlySpecializedClassTemplate@PAX@@QAEXXZ"
-// G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN34ExplicitlySpecializedClassTemplateIPvE1fEv
+// M32-DAG: define dllexport x86_thiscallcc void @"\01?f@?$ExplicitlySpecializedClassTemplate@PAX@@QAEXXZ"
+// G32-DAG: define dllexport x86_thiscallcc void @_ZN34ExplicitlySpecializedClassTemplateIPvE1fEv
 
 // MS inherits DLL attributes to partial specializations.
 template <typename T> struct __declspec(dllexport) PartiallySpecializedExportedClassTemplate {};
@@ -615,26 +618,58 @@
 struct __declspec(dllexport) ExportedDerivedClass : NonExportedBaseClass {};
 // M32-DAG: weak_odr dllexport x86_thiscallcc void @"\01??1ExportedDerivedClass@@UAE@XZ"
 
+// Do not assert about generating code for constexpr functions twice during explicit instantiation (PR21718).
+template <typename T> struct ExplicitInstConstexprMembers {
+  // Copy assignment operator
+  // M32-DAG: define weak_odr dllexport x86_thiscallcc dereferenceable(1) %struct.ExplicitInstConstexprMembers* @"\01??4?$ExplicitInstConstexprMembers@X@@QAEAAU0@ABU0@@Z"
+
+  constexpr ExplicitInstConstexprMembers() {}
+  // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExplicitInstConstexprMembers* @"\01??0?$ExplicitInstConstexprMembers@X@@QAE@XZ"
+
+  ExplicitInstConstexprMembers(const ExplicitInstConstexprMembers&) = default;
+  // M32-DAG: define weak_odr dllexport x86_thiscallcc %struct.ExplicitInstConstexprMembers* @"\01??0?$ExplicitInstConstexprMembers@X@@QAE@ABU0@@Z"
+
+  constexpr int f() const { return 42; }
+  // M32-DAG: define weak_odr dllexport x86_thiscallcc i32 @"\01?f@?$ExplicitInstConstexprMembers@X@@QBEHXZ"
+};
+template struct __declspec(dllexport) ExplicitInstConstexprMembers<void>;
+
+template <typename T> struct ExplicitInstantiationDeclTemplate { void f() {} };
+extern template struct __declspec(dllexport) ExplicitInstantiationDeclTemplate<int>;
+USEMEMFUNC(ExplicitInstantiationDeclTemplate<int>, f);
+// M32-DAG: {{declare|define available_externally}} x86_thiscallcc void @"\01?f@?$ExplicitInstantiationDeclTemplate@H@@QAEXXZ"
+
+template <typename T> struct __declspec(dllexport) ExplicitInstantiationDeclExportedTemplate { void f() {} };
+extern template struct ExplicitInstantiationDeclExportedTemplate<int>;
+USEMEMFUNC(ExplicitInstantiationDeclExportedTemplate<int>, f);
+// M32-DAG: {{declare|define available_externally}} x86_thiscallcc void @"\01?f@?$ExplicitInstantiationDeclExportedTemplate@H@@QAEXXZ"
+
 
 //===----------------------------------------------------------------------===//
 // Classes with template base classes
 //===----------------------------------------------------------------------===//
 
-template <typename T> struct ClassTemplate { void func() {} };
-template <typename T> struct __declspec(dllexport) ExportedClassTemplate { void func() {} };
+template <typename T> struct ClassTemplate { void func(); };
+template <typename T> void ClassTemplate<T>::func() {}
+template <typename T> struct __declspec(dllexport) ExportedClassTemplate { void func(); };
+template <typename T> void ExportedClassTemplate<T>::func() {}
 template <typename T> struct __declspec(dllimport) ImportedClassTemplate { void func(); };
 template <typename T> void ImportedClassTemplate<T>::func() {}
 
 template <typename T> struct ExplicitlySpecializedTemplate { void func() {} };
-template <> struct ExplicitlySpecializedTemplate<int> { void func() {} };
+template <> struct ExplicitlySpecializedTemplate<int> { void func(); };
+void ExplicitlySpecializedTemplate<int>::func() {}
 template <typename T> struct ExplicitlyExportSpecializedTemplate { void func() {} };
-template <> struct __declspec(dllexport) ExplicitlyExportSpecializedTemplate<int> { void func() {} };
+template <> struct __declspec(dllexport) ExplicitlyExportSpecializedTemplate<int> { void func(); };
+void ExplicitlyExportSpecializedTemplate<int>::func() {}
 template <typename T> struct ExplicitlyImportSpecializedTemplate { void func(); };
 template <> struct __declspec(dllimport) ExplicitlyImportSpecializedTemplate<int> { void func(); };
 
-template <typename T> struct ExplicitlyInstantiatedTemplate { void func() {} };
+template <typename T> struct ExplicitlyInstantiatedTemplate { void func(); };
+template <typename T> void ExplicitlyInstantiatedTemplate<T>::func() {}
 template struct ExplicitlyInstantiatedTemplate<int>;
-template <typename T> struct ExplicitlyExportInstantiatedTemplate { void func() {} };
+template <typename T> struct ExplicitlyExportInstantiatedTemplate { void func(); };
+template <typename T> void ExplicitlyExportInstantiatedTemplate<T>::func() {}
 template struct __declspec(dllexport) ExplicitlyExportInstantiatedTemplate<int>;
 template <typename T> struct ExplicitlyImportInstantiatedTemplate { void func(); };
 template struct __declspec(dllimport) ExplicitlyImportInstantiatedTemplate<int>;
@@ -675,14 +710,14 @@
 // Base class already specialized without dll attribute.
 struct __declspec(dllexport) DerivedFromExplicitlySpecializedTemplate : public ExplicitlySpecializedTemplate<int> {};
 USEMEMFUNC(DerivedFromExplicitlySpecializedTemplate, func)
-// M32-DAG: define linkonce_odr x86_thiscallcc void @"\01?func@?$ExplicitlySpecializedTemplate@H@@QAEXXZ"
-// G32-DAG: define linkonce_odr x86_thiscallcc void @_ZN29ExplicitlySpecializedTemplateIiE4funcEv
+// M32-DAG: define x86_thiscallcc void @"\01?func@?$ExplicitlySpecializedTemplate@H@@QAEXXZ"
+// G32-DAG: define x86_thiscallcc void @_ZN29ExplicitlySpecializedTemplateIiE4funcEv
 
 // Base class alredy specialized with export attribute.
 struct __declspec(dllexport) DerivedFromExplicitlyExportSpecializedTemplate : public ExplicitlyExportSpecializedTemplate<int> {};
 USEMEMFUNC(DerivedFromExplicitlyExportSpecializedTemplate, func)
-// M32-DAG: define weak_odr dllexport x86_thiscallcc void @"\01?func@?$ExplicitlyExportSpecializedTemplate@H@@QAEXXZ"
-// G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN35ExplicitlyExportSpecializedTemplateIiE4funcEv
+// M32-DAG: define dllexport x86_thiscallcc void @"\01?func@?$ExplicitlyExportSpecializedTemplate@H@@QAEXXZ"
+// G32-DAG: define dllexport x86_thiscallcc void @_ZN35ExplicitlyExportSpecializedTemplateIiE4funcEv
 
 // Base class already specialized with import attribute.
 struct __declspec(dllexport) DerivedFromExplicitlyImportSpecializedTemplate : public ExplicitlyImportSpecializedTemplate<int> {};
diff --git a/test/CodeGenCXX/dllimport.cpp b/test/CodeGenCXX/dllimport.cpp
index 5ebedd9..73f6023 100644
--- a/test/CodeGenCXX/dllimport.cpp
+++ b/test/CodeGenCXX/dllimport.cpp
@@ -1,13 +1,13 @@
-// RUN: %clang_cc1 -triple i686-windows-msvc   -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s -DMSABI | FileCheck --check-prefix=MSC --check-prefix=M32 %s
-// RUN: %clang_cc1 -triple x86_64-windows-msvc -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s -DMSABI | FileCheck --check-prefix=MSC --check-prefix=M64 %s
-// RUN: %clang_cc1 -triple i686-windows-gnu    -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s         | FileCheck --check-prefix=GNU --check-prefix=G32 %s
-// RUN: %clang_cc1 -triple x86_64-windows-gnu  -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s         | FileCheck --check-prefix=GNU --check-prefix=G64 %s
-// RUN: %clang_cc1 -triple i686-windows-msvc   -fno-rtti -emit-llvm -std=c++1y -O1 -o - %s -DMSABI | FileCheck --check-prefix=MO1 %s
-// RUN: %clang_cc1 -triple i686-windows-gnu    -fno-rtti -emit-llvm -std=c++1y -O1 -o - %s         | FileCheck --check-prefix=GO1 %s
+// RUN: %clang_cc1 -triple i686-windows-msvc   -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s -DMSABI -w | FileCheck --check-prefix=MSC --check-prefix=M32 %s
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s -DMSABI -w | FileCheck --check-prefix=MSC --check-prefix=M64 %s
+// RUN: %clang_cc1 -triple i686-windows-gnu    -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s         -w | FileCheck --check-prefix=GNU --check-prefix=G32 %s
+// RUN: %clang_cc1 -triple x86_64-windows-gnu  -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s         -w | FileCheck --check-prefix=GNU --check-prefix=G64 %s
+// RUN: %clang_cc1 -triple i686-windows-msvc   -fno-rtti -emit-llvm -std=c++1y -O1 -o - %s -DMSABI -w | FileCheck --check-prefix=MO1 %s
+// RUN: %clang_cc1 -triple i686-windows-gnu    -fno-rtti -emit-llvm -std=c++1y -O1 -o - %s         -w | FileCheck --check-prefix=GO1 %s
 
 // CHECK-NOT doesn't play nice with CHECK-DAG, so use separate run lines.
-// RUN: %clang_cc1 -triple i686-windows-msvc   -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s -DMSABI | FileCheck --check-prefix=MSC2 %s
-// RUN: %clang_cc1 -triple i686-windows-gnu    -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s         | FileCheck --check-prefix=GNU2 %s
+// RUN: %clang_cc1 -triple i686-windows-msvc   -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s -DMSABI -w | FileCheck --check-prefix=MSC2 %s
+// RUN: %clang_cc1 -triple i686-windows-gnu    -fno-rtti -emit-llvm -std=c++1y -O0 -o - %s         -w | FileCheck --check-prefix=GNU2 %s
 
 // Helper structs to make templates more expressive.
 struct ImplicitInst_Imported {};
@@ -243,7 +243,7 @@
 USE(noinline)
 
 // MSC2-NOT: @"\01?alwaysInline@@YAXXZ"()
-// GNU2-NOT: @_Z12alwaysInlinev()
+// GNU-DAG: define linkonce_odr void @_Z12alwaysInlinev() {{.*}} comdat {
 __declspec(dllimport) __attribute__((always_inline)) inline void alwaysInline() {}
 USE(alwaysInline)
 
@@ -728,19 +728,22 @@
 //===----------------------------------------------------------------------===//
 
 template <typename T> struct ClassTemplate { void func() {} };
-template <typename T> struct __declspec(dllexport) ExportedClassTemplate { void func() {} };
+template <typename T> struct __declspec(dllexport) ExportedClassTemplate { void func(); };
+template <typename T> void ExportedClassTemplate<T>::func() {}
 template <typename T> struct __declspec(dllimport) ImportedClassTemplate { void func(); };
 
 template <typename T> struct ExplicitlySpecializedTemplate { void func() {} };
 template <> struct ExplicitlySpecializedTemplate<int> { void func() {} };
 template <typename T> struct ExplicitlyExportSpecializedTemplate { void func() {} };
-template <> struct __declspec(dllexport) ExplicitlyExportSpecializedTemplate<int> { void func() {} };
+template <> struct __declspec(dllexport) ExplicitlyExportSpecializedTemplate<int> { void func(); };
+void ExplicitlyExportSpecializedTemplate<int>::func() {}
 template <typename T> struct ExplicitlyImportSpecializedTemplate { void func() {} };
 template <> struct __declspec(dllimport) ExplicitlyImportSpecializedTemplate<int> { void func(); };
 
 template <typename T> struct ExplicitlyInstantiatedTemplate { void func() {} };
 template struct ExplicitlyInstantiatedTemplate<int>;
-template <typename T> struct ExplicitlyExportInstantiatedTemplate { void func() {} };
+template <typename T> struct ExplicitlyExportInstantiatedTemplate { void func(); };
+template <typename T> void ExplicitlyExportInstantiatedTemplate<T>::func() {}
 template struct __declspec(dllexport) ExplicitlyExportInstantiatedTemplate<int>;
 template <typename T> struct ExplicitlyImportInstantiatedTemplate { void func(); };
 template struct __declspec(dllimport) ExplicitlyImportInstantiatedTemplate<int>;
@@ -787,8 +790,8 @@
 // Base class alredy specialized with export attribute.
 struct __declspec(dllimport) DerivedFromExplicitlyExportSpecializedTemplate : public ExplicitlyExportSpecializedTemplate<int> {};
 USEMEMFUNC(ExplicitlyExportSpecializedTemplate<int>, func)
-// M32-DAG: define weak_odr dllexport x86_thiscallcc void @"\01?func@?$ExplicitlyExportSpecializedTemplate@H@@QAEXXZ"
-// G32-DAG: define weak_odr dllexport x86_thiscallcc void @_ZN35ExplicitlyExportSpecializedTemplateIiE4funcEv
+// M32-DAG: define dllexport x86_thiscallcc void @"\01?func@?$ExplicitlyExportSpecializedTemplate@H@@QAEXXZ"
+// G32-DAG: define dllexport x86_thiscallcc void @_ZN35ExplicitlyExportSpecializedTemplateIiE4funcEv
 
 // Base class already specialized with import attribute.
 struct __declspec(dllimport) DerivedFromExplicitlyImportSpecializedTemplate : public ExplicitlyImportSpecializedTemplate<int> {};
diff --git a/test/CodeGenCXX/exceptions-seh.cpp b/test/CodeGenCXX/exceptions-seh.cpp
new file mode 100644
index 0000000..5f93cb1
--- /dev/null
+++ b/test/CodeGenCXX/exceptions-seh.cpp
@@ -0,0 +1,98 @@
+// RUN: %clang_cc1 -std=c++11 -fblocks -fms-extensions %s -triple=x86_64-windows-msvc -emit-llvm \
+// RUN:         -o - -mconstructor-aliases -fcxx-exceptions -fexceptions | \
+// RUN:         FileCheck %s --check-prefix=CHECK --check-prefix=CXXEH
+// RUN: %clang_cc1 -std=c++11 -fblocks -fms-extensions %s -triple=x86_64-windows-msvc -emit-llvm \
+// RUN:         -o - -mconstructor-aliases -O1 -disable-llvm-optzns | \
+// RUN:         FileCheck %s --check-prefix=CHECK --check-prefix=NOCXX
+
+extern "C" void might_throw();
+
+struct HasCleanup {
+  HasCleanup();
+  ~HasCleanup();
+  int padding;
+};
+
+extern "C" void use_cxx() {
+  HasCleanup x;
+  might_throw();
+}
+
+// Make sure we use __CxxFrameHandler3 for C++ EH.
+
+// CXXEH-LABEL: define void @use_cxx()
+// CXXEH: call %struct.HasCleanup* @"\01??0HasCleanup@@QEAA@XZ"(%struct.HasCleanup* %{{.*}})
+// CXXEH: invoke void @might_throw()
+// CXXEH:       to label %[[cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CXXEH: [[cont]]
+// CXXEH: call void @"\01??1HasCleanup@@QEAA@XZ"(%struct.HasCleanup* %{{.*}})
+// CXXEH: ret void
+//
+// CXXEH: [[lpad]]
+// CXXEH: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)
+// CXXEH-NEXT: cleanup
+// CXXEH: call void @"\01??1HasCleanup@@QEAA@XZ"(%struct.HasCleanup* %{{.*}})
+// CXXEH: br label %[[resume:[^ ]*]]
+//
+// CXXEH: [[resume]]
+// CXXEH: resume
+
+// NOCXX-LABEL: define void @use_cxx()
+// NOCXX-NOT: invoke
+// NOCXX: call %struct.HasCleanup* @"\01??0HasCleanup@@QEAA@XZ"(%struct.HasCleanup* %{{.*}})
+// NOCXX-NOT: invoke
+// NOCXX: call void @might_throw()
+// NOCXX-NOT: invoke
+// NOCXX: call void @"\01??1HasCleanup@@QEAA@XZ"(%struct.HasCleanup* %{{.*}})
+// NOCXX-NOT: invoke
+// NOCXX: ret void
+
+extern "C" void use_seh() {
+  __try {
+    might_throw();
+  } __except(1) {
+  }
+}
+
+// Make sure we use __C_specific_handler for SEH.
+
+// CHECK-LABEL: define void @use_seh()
+// CHECK: invoke void @might_throw() #[[NOINLINE:[0-9]+]]
+// CHECK:       to label %[[cont:[^ ]*]] unwind label %[[lpad:[^ ]*]]
+//
+// CHECK: [[cont]]
+// CHECK: br label %[[ret:[^ ]*]]
+//
+// CHECK: [[lpad]]
+// CHECK: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*)
+// CHECK-NEXT: catch i8*
+//
+// CHECK: br label %[[ret]]
+//
+// CHECK: [[ret]]
+// CHECK: ret void
+
+void use_seh_in_lambda() {
+  ([]() {
+    __try {
+      might_throw();
+    } __except(1) {
+    }
+  })();
+  HasCleanup x;
+  might_throw();
+}
+
+// CXXEH-LABEL: define void @"\01?use_seh_in_lambda@@YAXXZ"()
+// CXXEH: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__CxxFrameHandler3 to i8*)
+
+// NOCXX-LABEL: define void @"\01?use_seh_in_lambda@@YAXXZ"()
+// NOCXX-NOT: invoke
+// NOCXX: ret void
+
+// CHECK-LABEL: define internal void @"\01??R<lambda_0>@?use_seh_in_lambda@@YAXXZ@QEBAXXZ"(%class.anon* %this)
+// CHECK: invoke void @might_throw() #[[NOINLINE]]
+// CHECK: landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*)
+
+// CHECK: attributes #[[NOINLINE]] = { {{.*noinline.*}} }
diff --git a/test/CodeGenCXX/exceptions.cpp b/test/CodeGenCXX/exceptions.cpp
index 5016e9a..c1c678d 100644
--- a/test/CodeGenCXX/exceptions.cpp
+++ b/test/CodeGenCXX/exceptions.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - -fcxx-exceptions -fexceptions | FileCheck %s
+// RUN: %clang_cc1 %s -triple=x86_64-linux-gnu -emit-llvm -o - -fcxx-exceptions -fexceptions | FileCheck %s
 
 typedef typeof(sizeof(0)) size_t;
 
@@ -71,7 +71,7 @@
 
   //   rdar://11904428
   //   Terminate landing pads should call __cxa_begin_catch first.
-  // CHECK:      define linkonce_odr hidden void @__clang_call_terminate(i8*) [[NI_NR_NUW:#[0-9]+]]
+  // CHECK:      define linkonce_odr hidden void @__clang_call_terminate(i8*) [[NI_NR_NUW:#[0-9]+]] comdat
   // CHECK-NEXT:   [[T0:%.*]] = call i8* @__cxa_begin_catch(i8* %0) [[NUW:#[0-9]+]]
   // CHECK-NEXT:   call void @_ZSt9terminatev() [[NR_NUW:#[0-9]+]]
   // CHECK-NEXT:   unreachable
diff --git a/test/CodeGenCXX/explicit-instantiation.cpp b/test/CodeGenCXX/explicit-instantiation.cpp
index 5bd0678..6076444 100644
--- a/test/CodeGenCXX/explicit-instantiation.cpp
+++ b/test/CodeGenCXX/explicit-instantiation.cpp
@@ -90,6 +90,19 @@
   // CHECK-OPT: define available_externally i32 @_ZN17LateInstantiation1fIiEEiv(
 }
 
+namespace PR21718 {
+// The linkage of a used constexpr member function can change from linkonce_odr
+// to weak_odr after explicit instantiation without errors about defining the
+// same function twice.
+template <typename T>
+struct S {
+// CHECK-LABEL: define weak_odr i32 @_ZN7PR217181SIiE1fEv
+  __attribute__((used)) constexpr int f() { return 0; }
+};
+int g() { return S<int>().f(); }
+template struct S<int>;
+}
+
 // Check that we emit definitions from explicit instantiations even when they
 // occur prior to the definition itself.
 template <typename T> struct S {
diff --git a/test/CodeGenCXX/function-template-specialization.cpp b/test/CodeGenCXX/function-template-specialization.cpp
index eb099df..7728f3d 100644
--- a/test/CodeGenCXX/function-template-specialization.cpp
+++ b/test/CodeGenCXX/function-template-specialization.cpp
@@ -1,4 +1,8 @@
 // RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple %s -o - | FileCheck %s
+
+// CHECK-DAG: _ZZN7PR219047GetDataIiEERKibE1i = internal global i32 4
+// CHECK-DAG: _ZZN7PR219047GetDataIiEERKibE1i_0 = internal global i32 2
+
 template<typename T, typename U>
 T* next(T* ptr, const U& diff);
 
@@ -24,3 +28,18 @@
   // CHECK: _Z4nextIdiEPT_S1_RKT0_
   dptr = next(dptr, diff);
 }
+
+namespace PR21904 {
+template <typename>
+const int &GetData(bool);
+
+template <>
+const int &GetData<int>(bool b) {
+  static int i = 4;
+  if (b) {
+    static int i = 2;
+    return i;
+  }
+  return i;
+}
+}
diff --git a/test/CodeGenCXX/globalinit-loc.cpp b/test/CodeGenCXX/globalinit-loc.cpp
index 113a26c..583f9c7 100644
--- a/test/CodeGenCXX/globalinit-loc.cpp
+++ b/test/CodeGenCXX/globalinit-loc.cpp
@@ -6,8 +6,8 @@
 //
 // CHECK: define internal void @_GLOBAL__sub_I_globalinit_loc.cpp
 // CHECK: !dbg ![[DBG:.*]]
-// CHECK: metadata !{metadata !"0x2e\00\00\00_GLOBAL__sub_I_globalinit_loc.cpp\000\00{{.*}}\000", {{.*}} ; [ DW_TAG_subprogram ] [line 0] [local] [def]
-// CHECK: ![[DBG]] = metadata !{i32 0, i32 0,
+// CHECK:  !"0x2e\00\00\00_GLOBAL__sub_I_globalinit_loc.cpp\000\00{{.*}}\000", {{.*}} ; [ DW_TAG_subprogram ] [line 0] [local] [def]
+// CHECK: ![[DBG]] = !MDLocation(line: 0,
 # 99 "someheader.h"
 class A {
 public:
diff --git a/test/CodeGenCXX/homogeneous-aggregates.cpp b/test/CodeGenCXX/homogeneous-aggregates.cpp
index 4800aac..94813f3 100644
--- a/test/CodeGenCXX/homogeneous-aggregates.cpp
+++ b/test/CodeGenCXX/homogeneous-aggregates.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=PPC
-// RUN: %clang_cc1 -mfloat-abi hard -triple armv7-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM32
+// RUN: %clang_cc1 -mfloat-abi hard -triple armv7-unknown-linux-gnueabi -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM32
 // RUN: %clang_cc1 -mfloat-abi hard -triple aarch64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64
 // RUN: %clang_cc1 -mfloat-abi hard -triple x86_64-unknown-windows-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=X64
 
@@ -46,7 +46,7 @@
 
 // PPC: define [3 x double] @_Z7func_D22D2([3 x double] %x.coerce)
 // ARM32: define arm_aapcs_vfpcc %struct.D2 @_Z7func_D22D2(%struct.D2 %x.coerce)
-// ARM64: define %struct.D2 @_Z7func_D22D2(double %x.0, double %x.1, double %x.2)
+// ARM64: define %struct.D2 @_Z7func_D22D2([3 x double] %x.coerce)
 // X64: define x86_vectorcallcc %struct.D2 @"\01_Z7func_D22D2@@24"(double %x.0, double %x.1, double %x.2)
 D2 CC func_D2(D2 x) { return x; }
 
@@ -57,7 +57,7 @@
 
 // PPC: define [4 x double] @_Z7func_D42D4([4 x double] %x.coerce)
 // ARM32: define arm_aapcs_vfpcc %struct.D4 @_Z7func_D42D4(%struct.D4 %x.coerce)
-// ARM64: define %struct.D4 @_Z7func_D42D4(double %x.0, double %x.1, double %x.2, double %x.3)
+// ARM64: define %struct.D4 @_Z7func_D42D4([4 x double] %x.coerce)
 D4 CC func_D4(D4 x) { return x; }
 
 D5 CC func_D5(D5 x) { return x; }
@@ -67,17 +67,9 @@
 // The C++ multiple inheritance expansion case is a little more complicated, so
 // do some extra checking.
 //
-// ARM64-LABEL: define %struct.D5 @_Z7func_D52D5(double %x.0, double %x.1, double %x.2)
-// ARM64: bitcast %struct.D5* %{{.*}} to %struct.I1*
-// ARM64: bitcast %struct.I1* %{{.*}} to %struct.Base2*
-// ARM64: getelementptr inbounds %struct.Base2* %{{.*}}, i32 0, i32 0
-// ARM64: store double %x.0, double*
-// ARM64: getelementptr inbounds i8* %{{.*}}, i64 8
-// ARM64: getelementptr inbounds %struct.Base2* %{{.*}}, i32 0, i32 0
-// ARM64: store double %x.1, double*
-// ARM64: getelementptr inbounds i8* %{{.*}}, i64 16
-// ARM64: getelementptr inbounds %struct.Base2* %{{.*}}, i32 0, i32 0
-// ARM64: store double %x.2, double*
+// ARM64-LABEL: define %struct.D5 @_Z7func_D52D5([3 x double] %x.coerce)
+// ARM64: bitcast %struct.D5* %{{.*}} to [3 x double]*
+// ARM64: store [3 x double] %x.coerce, [3 x double]*
 
 void call_D5(D5 *p) {
   func_D5(*p);
@@ -86,21 +78,8 @@
 // Check the call site.
 //
 // ARM64-LABEL: define void @_Z7call_D5P2D5(%struct.D5* %p)
-// ARM64: bitcast %struct.D5* %{{.*}} to %struct.I1*
-// ARM64: bitcast %struct.I1* %{{.*}} to %struct.Base2*
-// ARM64: getelementptr inbounds %struct.Base2* %{{.*}}, i32 0, i32 0
-// ARM64: load double*
-// ARM64: getelementptr inbounds i8* %{{.*}}, i64 8
-// ARM64: bitcast i8* %{{.*}} to %struct.I2*
-// ARM64: bitcast %struct.I2* %{{.*}} to %struct.Base2*
-// ARM64: getelementptr inbounds %struct.Base2* %{{.*}}, i32 0, i32 0
-// ARM64: load double*
-// ARM64: getelementptr inbounds i8* %{{.*}}, i64 16
-// ARM64: bitcast i8* %{{.*}} to %struct.I3*
-// ARM64: bitcast %struct.I3* %{{.*}} to %struct.Base2*
-// ARM64: getelementptr inbounds %struct.Base2* %{{.*}}, i32 0, i32 0
-// ARM64: load double*
-// ARM64: call %struct.D5 @_Z7func_D52D5(double %{{.*}}, double %{{.*}}, double %{{.*}})
+// ARM64: load [3 x double]*
+// ARM64: call %struct.D5 @_Z7func_D52D5([3 x double] %{{.*}})
 
 struct Empty { };
 struct Float1 { float x; };
@@ -108,7 +87,7 @@
 struct HVAWithEmptyBase : Float1, Empty, Float2 { float z; };
 
 // PPC: define void @_Z15with_empty_base16HVAWithEmptyBase([3 x float] %a.coerce)
-// ARM64: define void @_Z15with_empty_base16HVAWithEmptyBase(float %a.0, float %a.1, float %a.2)
+// ARM64: define void @_Z15with_empty_base16HVAWithEmptyBase([3 x float] %a.coerce)
 // ARM32: define arm_aapcs_vfpcc void @_Z15with_empty_base16HVAWithEmptyBase(%struct.HVAWithEmptyBase %a.coerce)
 void CC with_empty_base(HVAWithEmptyBase a) {}
 
@@ -121,7 +100,7 @@
 };
 
 // PPC: define void @_Z19with_empty_bitfield20HVAWithEmptyBitField([3 x float] %a.coerce)
-// ARM64: define void @_Z19with_empty_bitfield20HVAWithEmptyBitField(float %a.0, float %a.1, float %a.2)
+// ARM64: define void @_Z19with_empty_bitfield20HVAWithEmptyBitField([3 x float] %a.coerce)
 // ARM32: define arm_aapcs_vfpcc void @_Z19with_empty_bitfield20HVAWithEmptyBitField(%struct.HVAWithEmptyBitField %a.coerce)
 // X64: define x86_vectorcallcc void @"\01_Z19with_empty_bitfield20HVAWithEmptyBitField@@16"(float %a.0, float %a.1, float %a.2)
 void CC with_empty_bitfield(HVAWithEmptyBitField a) {}
diff --git a/test/CodeGenCXX/implicit-allocation-functions.cpp b/test/CodeGenCXX/implicit-allocation-functions.cpp
new file mode 100644
index 0000000..3b66a07
--- /dev/null
+++ b/test/CodeGenCXX/implicit-allocation-functions.cpp
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++11 %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK11
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++11 -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK11
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 -fno-sized-deallocation %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK11
+// RU N: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK14 -check-prefix=CHECK14UND
+// RU N: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK14 -check-prefix=CHECK14UND
+// RU N: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 -fdefine-sized-deallocation %s 2>&1 | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK14 -check-prefix=CHECK14DEFCOMDAT
+// RU N: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown -o - -std=c++14 -fdefine-sized-deallocation -fvisibility hidden %s 2>&1 | FileCheck %s -check-prefix=CHECKHID -check-prefix=CHECK14 -check-prefix=CHECK14DEFCOMDAT
+// RU N: %clang_cc1 -emit-llvm -triple x86_64-apple-macosx -o - -std=c++14 -fdefine-sized-deallocation %s | FileCheck %s -check-prefix=CHECKDEF -check-prefix=CHECK14 -check-prefix=CHECK14DEFNOCOMDAT
+
+// PR22419: Implicit sized deallocation functions always have default visibility.
+//   Generalized to all implicit allocation functions.
+
+// CHECK14-DAG: %struct.A = type { i8 }
+struct A { };
+
+// CHECKDEF-DAG: define void @_Z3fooP1A(%struct.A* %is)
+// CHECKHID-DAG: define hidden void @_Z3fooP1A(%struct.A* %is)
+void foo(A* is) {
+
+  // CHECK11-DAG: call noalias i8* @_Znwm(i64 1)
+  // CHECK14-DAG: call noalias i8* @_Znwm(i64 1)
+  is = new A();
+
+  // CHECK11-DAG: call void @_ZdlPv(i8* %{{.+}})
+  // CHECK14UND-DAG: br i1 icmp ne (void (i8*, i64)* @_ZdlPvm, void (i8*, i64)* null),
+  // CHECK14-DAG: call void @_ZdlPvm(i8* %{{.+}}, i64 1)
+  // CHECK14UND-DAG: call void @_ZdlPv(i8* %{{.+}})
+  delete is;
+}
+
+// CHECK11-DAG: declare noalias i8* @_Znwm(i64)
+// CHECK11-DAG: declare void @_ZdlPv(i8*)
+
+// CHECK14-DAG: declare noalias i8* @_Znwm(i64)
+// CHECK14UND-DAG: declare extern_weak void @_ZdlPvm(i8*, i64)
+// CHECK14DEFCOMDAT-DAG: define linkonce void @_ZdlPvm(i8*, i64) #{{[0-9]+}} comdat {
+// CHECK14DEFCOMDAT-DAG: declare void @_ZdlPv(i8*)
+// CHECK14DEFNOCOMDAT-DAG: define linkonce void @_ZdlPvm(i8*, i64) #{{[0-9]+}} {
+// CHECK14DEFNOCOMDAT-DAG: declare void @_ZdlPv(i8*)
+
+// CHECK14-DAG: %struct.B = type { i8 }
+struct B { ~B() { }};
+
+// CHECKDEF-DAG: define void @_Z1fP1B(%struct.B* %p)
+// CHECKHID-DAG: define hidden void @_Z1fP1B(%struct.B* %p)
+void f(B *p) {
+
+  // CHECK11-DAG: call noalias i8* @_Znam(i64 13)
+  // CHECK14-DAG: call noalias i8* @_Znam(i64 13)
+  p = new B[5];
+
+  // CHECK11-DAG: call void @_ZdaPv(i8* %{{.+}})
+  // CHECK14UND-DAG: br i1 icmp ne (void (i8*, i64)* @_ZdaPvm, void (i8*, i64)* null),
+  // CHECK14-DAG: call void @_ZdaPvm(i8* %{{.+}}, i64 %{{.+}})
+  // CHECK14UND-DAG: call void @_ZdaPv(i8* %{{.+}})
+  delete[] p;
+}
+
+// CHECK11-DAG: declare noalias i8* @_Znam(i64)
+// CHECK11-DAG: declare void @_ZdaPv(i8*)
+
+// CHECK14-DAG: declare noalias i8* @_Znam(i64)
+// CHECK14UND-DAG: declare extern_weak void @_ZdaPvm(i8*, i64)
+// CHECK14DEF-DAG: define linkonce void @_ZdaPvm(i8*, i64) #{{[0-9]+}} comdat {
+// CHECK14DEF-DAG: declare void @_ZdaPv(i8*)
+// CHECK14DEFNOCOMDAT-DAG: define linkonce void @_ZdaPvm(i8*, i64) #{{[0-9]+}} {
+// CHECK14DEFNOCOMDAT-DAG: declare void @_ZdaPv(i8*)
diff --git a/test/CodeGenCXX/implicit-record-visibility.cpp b/test/CodeGenCXX/implicit-record-visibility.cpp
new file mode 100644
index 0000000..701a203
--- /dev/null
+++ b/test/CodeGenCXX/implicit-record-visibility.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 %s -I%S -fvisibility hidden -triple x86_64-linux-gnu -emit-llvm -o - | FileCheck %s
+
+#include <stdarg.h>
+#include <typeinfo>
+
+// If struct __va_list_tag did not explicitly have default visibility, then
+// under -fvisibility hidden the type of function f, due to its va_list (aka
+// __builtin_va_list, aka __va_list_tag (*)[1]) parameter would be hidden:
+
+// CHECK: @_ZTSFvP13__va_list_tagE = linkonce_odr constant
+// CHECK: @_ZTIFvP13__va_list_tagE = linkonce_odr constant
+void f(va_list) { (void)typeid(f); }
diff --git a/test/CodeGenCXX/inheriting-constructor.cpp b/test/CodeGenCXX/inheriting-constructor.cpp
index 9394137..42080a2 100644
--- a/test/CodeGenCXX/inheriting-constructor.cpp
+++ b/test/CodeGenCXX/inheriting-constructor.cpp
@@ -21,8 +21,8 @@
 // CHECK-LABEL: define linkonce_odr void @_ZN1DC1IiEET_(
 // CHECK: call void @_ZN1DC2IiEET_(
 
-// CHECK-LABEL: define linkonce_odr void @_ZN1DC2IiEET_(
-// CHECK: call void @_ZN1CC2IiEET_(
-
 // CHECK-LABEL: define linkonce_odr void @_ZN1BC2Ei(
 // CHECK: call void @_ZN1AC2Ei(
+
+// CHECK-LABEL: define linkonce_odr void @_ZN1DC2IiEET_(
+// CHECK: call void @_ZN1CC2IiEET_(
diff --git a/test/CodeGenCXX/key-function-vtable.cpp b/test/CodeGenCXX/key-function-vtable.cpp
index 0ecd898..80ce497 100644
--- a/test/CodeGenCXX/key-function-vtable.cpp
+++ b/test/CodeGenCXX/key-function-vtable.cpp
@@ -41,13 +41,13 @@
 
 inline void X1::f() { }
 
-void use_X1(X1 *x1) { x1->f(); }
+void use_X1() { X1 x1; }
 
 // FIXME: The checks are extremely difficult to get right when the globals
 // aren't alphabetized
 // CHECK: @_ZTV2X1 = linkonce_odr unnamed_addr constant
 // CHECK: @_ZTV5testa = unnamed_addr constant [3 x i8*] [i8* null
 // CHECK: @_ZTV5testc = linkonce_odr unnamed_addr constant [3 x i8*] [i8* null
-// CHECK: @_ZTVN12_GLOBAL__N_15testgE = internal unnamed_addr constant [3 x i8*] [i8* null
-// CHECK: @_ZTV5teste = linkonce_odr unnamed_addr constant [3 x i8*] [i8* null
 // CHECK: @_ZTV5testb = linkonce_odr unnamed_addr constant [3 x i8*] [i8* null
+// CHECK: @_ZTV5teste = linkonce_odr unnamed_addr constant [3 x i8*] [i8* null
+// CHECK: @_ZTVN12_GLOBAL__N_15testgE = internal unnamed_addr constant [3 x i8*] [i8* null
diff --git a/test/CodeGenCXX/lambda-expressions-nested-linkage.cpp b/test/CodeGenCXX/lambda-expressions-nested-linkage.cpp
index accc5d2..9a44987 100644
--- a/test/CodeGenCXX/lambda-expressions-nested-linkage.cpp
+++ b/test/CodeGenCXX/lambda-expressions-nested-linkage.cpp
@@ -30,8 +30,16 @@
 }
 
 // CHECK-LABEL: define linkonce_odr i32 @_ZN15inline_function3fooEv
-// CHECK: define linkonce_odr void @_ZZN15inline_function3fooEvENKUliE_clEi
-// CHECK: define linkonce_odr signext i8 @_ZZZN15inline_function3fooEvENKUliE_clEiENKUlcE_clEc
+
+// CHECK-LABEL: define linkonce_odr void @_ZNK12non_template1L1tMUliE_clEi(%class.anon
+// CHECK-LABEL: define linkonce_odr i32 @_ZZNK12non_template1L1tMUliE_clEiENKUliE_clEi(%class.anon
+
+
+// CHECK-LABEL: define linkonce_odr void @_ZNK32lambdas_in_NSDMIs_template_class1LIiEUliE_clEi(%class.anon
+// CHECK-LABEL: define linkonce_odr i32 @_ZZNK32lambdas_in_NSDMIs_template_class1LIiEUliE_clEiENKUliE_clEi(%class.anon
+
+// CHECK-LABEL: define linkonce_odr void @_ZZN15inline_function3fooEvENKUliE_clEi
+// CHECK-LABEL: define linkonce_odr signext i8 @_ZZZN15inline_function3fooEvENKUliE_clEiENKUlcE_clEc
 namespace inline_function {
 inline int foo() {
   auto L = [](int a) {
@@ -43,8 +51,3 @@
 }
 int use = foo();
 }
-// CHECK: define linkonce_odr void @_ZNK32lambdas_in_NSDMIs_template_class1LIiEUliE_clEi(%class.anon
-// CHECK: define linkonce_odr i32 @_ZZNK32lambdas_in_NSDMIs_template_class1LIiEUliE_clEiENKUliE_clEi(%class.anon
-
-// CHECK: define linkonce_odr void @_ZNK12non_template1L1tMUliE_clEi(%class.anon
-// CHECK: define linkonce_odr i32 @_ZZNK12non_template1L1tMUliE_clEiENKUliE_clEi(%class.anon
diff --git a/test/CodeGenCXX/lambda-expressions.cpp b/test/CodeGenCXX/lambda-expressions.cpp
index 2f9a4f2..7fb2298 100644
--- a/test/CodeGenCXX/lambda-expressions.cpp
+++ b/test/CodeGenCXX/lambda-expressions.cpp
@@ -81,7 +81,7 @@
 };
 
 // PR14773
-// CHECK: [[ARRVAL:%[0-9a-zA-Z]*]] = load i32* getelementptr inbounds ([0 x i32]* bitcast (<{}>* @_ZZ14staticarrayrefvE5array to [0 x i32]*), i32 0, i64 0), align 4
+// CHECK: [[ARRVAL:%[0-9a-zA-Z]*]] = load i32* getelementptr inbounds ([0 x i32]* @_ZZ14staticarrayrefvE5array, i32 0, i64 0), align 4
 // CHECK-NEXT: store i32 [[ARRVAL]]
 void staticarrayref(){
   static int array[] = {};
@@ -91,15 +91,16 @@
   }();
 }
 
-// CHECK: define internal void @"_ZZ1hvEN3$_88__invokeEv"(%struct.A* noalias sret %agg.result) {{.*}} {
-// CHECK-NOT: =
-// CHECK: call void @"_ZZ1hvENK3$_8clEv"(%struct.A* sret %agg.result,
-// CHECK-NEXT: ret void
-struct A { ~A(); };
-void h() {
-  A (*h)() = [] { return A(); };
+// CHECK-LABEL: define internal i32* @"_ZZ11PR22071_funvENK3$_8clEv"
+// CHECK: ret i32* @PR22071_var
+int PR22071_var;
+int *PR22071_fun() {
+  constexpr int &y = PR22071_var;
+  return [&] { return &y; }();
 }
 
+// CHECK-LABEL: define internal void @"_ZZ1e1ES_bEN3$_4D2Ev"
+
 // CHECK-LABEL: define internal i32 @"_ZZ1fvEN3$_58__invokeEii"
 // CHECK: store i32
 // CHECK-NEXT: store i32
@@ -108,7 +109,14 @@
 // CHECK-NEXT: call i32 @"_ZZ1fvENK3$_5clEii"
 // CHECK-NEXT: ret i32
 
-// CHECK-LABEL: define internal void @"_ZZ1e1ES_bEN3$_4D2Ev"
+// CHECK-LABEL: define internal void @"_ZZ1hvEN3$_98__invokeEv"(%struct.A* noalias sret %agg.result) {{.*}} {
+// CHECK-NOT: =
+// CHECK: call void @"_ZZ1hvENK3$_9clEv"(%struct.A* sret %agg.result,
+// CHECK-NEXT: ret void
+struct A { ~A(); };
+void h() {
+  A (*h)() = [] { return A(); };
+}
 
 // <rdar://problem/12778708>
 struct XXX {};
diff --git a/test/CodeGenCXX/linetable-cleanup.cpp b/test/CodeGenCXX/linetable-cleanup.cpp
index 45c207c..0e64be1 100644
--- a/test/CodeGenCXX/linetable-cleanup.cpp
+++ b/test/CodeGenCXX/linetable-cleanup.cpp
@@ -4,8 +4,8 @@
 // simple return expressions.
 
 // CHECK: define {{.*}}foo
-// CHECK: call void @_ZN1CD1Ev(%class.C* {{.*}}), !dbg ![[CLEANUP:[0-9]+]]
-// CHECK: ret i32 0, !dbg ![[RET:[0-9]+]]
+// CHECK: call void @_ZN1CD1Ev(%class.C* {{.*}}), !dbg ![[RET:[0-9]+]]
+// CHECK: ret i32 0, !dbg ![[RET]]
 
 // CHECK: define {{.*}}bar
 // CHECK: ret void, !dbg ![[RETBAR:[0-9]+]]
@@ -23,16 +23,15 @@
 {
   C c;
   c.i = 42;
-  // This breakpoint should be at/before the cleanup code.
-  // CHECK: ![[CLEANUP]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
   return 0;
-  // CHECK: ![[RET]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // This breakpoint should be at/before the cleanup code.
+  // CHECK: ![[RET]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 
 void bar()
 {
   if (!foo())
-    // CHECK: {{.*}} = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+    // CHECK: {{.*}} = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
     return;
 
   if (foo()) {
@@ -40,21 +39,21 @@
     c.i = foo();
   }
   // Clang creates only a single ret instruction. Make sure it is at a useful line.
-  // CHECK: ![[RETBAR]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RETBAR]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 
 void baz()
 {
   if (!foo())
-    // CHECK: ![[SCOPE1:.*]] = metadata !{metadata !"0xb\00[[@LINE-1]]\00{{.*}}", {{.*}} ; [ DW_TAG_lexical_block ]
-    // CHECK: {{.*}} = metadata !{i32 [[@LINE+1]], i32 0, metadata ![[SCOPE1]], null}
+    // CHECK: ![[SCOPE1:.*]] = !{!"0xb\00[[@LINE-1]]\00{{.*}}", {{.*}} ; [ DW_TAG_lexical_block ]
+    // CHECK: {{.*}} = !MDLocation(line: [[@LINE+1]], scope: ![[SCOPE1]])
     return;
 
   if (foo()) {
     // no cleanup
-    // CHECK: {{.*}} = metadata !{i32 [[@LINE+2]], i32 0, metadata ![[SCOPE2:.*]], null}
-    // CHECK: ![[SCOPE2]] = metadata !{metadata !"0xb\00[[@LINE-3]]\00{{.*}}", {{.*}} ; [ DW_TAG_lexical_block ]
+    // CHECK: {{.*}} = !MDLocation(line: [[@LINE+2]], scope: ![[SCOPE2:.*]])
+    // CHECK: ![[SCOPE2]] = !{!"0xb\00[[@LINE-3]]\00{{.*}}", {{.*}} ; [ DW_TAG_lexical_block ]
     return;
   }
-  // CHECK: ![[RETBAZ]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RETBAZ]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
diff --git a/test/CodeGenCXX/linetable-eh.cpp b/test/CodeGenCXX/linetable-eh.cpp
index 4ef037a..6d9b3a9 100644
--- a/test/CodeGenCXX/linetable-eh.cpp
+++ b/test/CodeGenCXX/linetable-eh.cpp
@@ -4,18 +4,18 @@
 // entries for the code that triggered it.
 
 // CHECK: call void @llvm.dbg.declare
-// CHECK: call void @llvm.dbg.declare(metadata !{{{.*}}}, metadata ![[CURRENT_ADDR:.*]], metadata !{{.*}}), !dbg ![[DBG1:.*]]
+// CHECK: call void @llvm.dbg.declare(metadata {{.*}}, metadata ![[CURRENT_ADDR:.*]], metadata !{{.*}}), !dbg ![[DBG1:.*]]
 // CHECK: unwind label %{{.*}}, !dbg ![[DBG1]]
 // CHECK: store i64 %{{.*}}, i64* %current_address, align 8, !dbg ![[DBG4:.*]]
-// CHECK-NEXT: call void @llvm.dbg.declare(metadata !{{{.*}}}, metadata ![[FOUND_IT:.*]], metadata !{{.*}}), !dbg ![[DBG2:.*]]
+// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}, metadata ![[FOUND_IT:.*]], metadata !{{.*}}), !dbg ![[DBG2:.*]]
 // CHECK: = landingpad
 // CHECK-NEXT: cleanup, !dbg ![[DBG3:.*]]
 // CHECK-DAG: ![[CURRENT_ADDR]] = {{.*}} [current_address]
 // CHECK-DAG: ![[FOUND_IT]] = {{.*}} [found_it]
-// CHECK-DAG: ![[DBG1]] = metadata !{i32 256,
-// CHECK-DAG: ![[DBG2]] = metadata !{i32 257,
-// CHECK-DAG: ![[DBG3]] = metadata !{i32 268,
-// CHECK-DAG: ![[DBG4]] = metadata !{i32 256,
+// CHECK-DAG: ![[DBG1]] = !MDLocation(line: 256,
+// CHECK-DAG: ![[DBG2]] = !MDLocation(line: 257,
+// CHECK-DAG: ![[DBG3]] = !MDLocation(line: 268,
+// CHECK-DAG: ![[DBG4]] = !MDLocation(line: 256,
 typedef unsigned long long uint64_t;
 template<class _Tp> class shared_ptr {
 public:
diff --git a/test/CodeGenCXX/linetable-fnbegin.cpp b/test/CodeGenCXX/linetable-fnbegin.cpp
index 9ae43d4..b0a03f7 100644
--- a/test/CodeGenCXX/linetable-fnbegin.cpp
+++ b/test/CodeGenCXX/linetable-fnbegin.cpp
@@ -4,10 +4,10 @@
 // CHECK: define{{.*}}bar
 // CHECK-NOT: define
 // CHECK: ret {{.*}}, !dbg [[DBG:.*]]
-// CHECK: [[HPP:.*]] = metadata !{metadata !"./template.hpp",
-// CHECK: [[SP:.*]] = metadata !{metadata !"0x2e\00{{.*}}", metadata [[HPP]],{{.*}}[ DW_TAG_subprogram ] [line 22] [def] [bar]
+// CHECK: [[HPP:.*]] = !{!"./template.hpp",
+// CHECK: [[SP:.*]] = !{!"0x2e\00{{.*}}", [[HPP]],{{.*}}[ DW_TAG_subprogram ] [line 22] [def] [bar]
 // We shouldn't need a lexical block for this function.
-// CHECK: [[DBG]] = metadata !{i32 23, i32 0, metadata [[SP]], null}
+// CHECK: [[DBG]] = !MDLocation(line: 23, scope: [[SP]])
 
 
 # 1 "./template.h" 1
diff --git a/test/CodeGenCXX/lpad-linetable.cpp b/test/CodeGenCXX/lpad-linetable.cpp
index dba2ad6..c81191b 100644
--- a/test/CodeGenCXX/lpad-linetable.cpp
+++ b/test/CodeGenCXX/lpad-linetable.cpp
@@ -4,7 +4,7 @@
 // CHECK: ret i32
 // CHECK: landingpad {{.*}}
 // CHECK-NEXT: !dbg ![[LPAD:[0-9]+]]
-// CHECK: ![[LPAD]] = metadata !{i32 24, i32 0, metadata !{{.*}}, null}
+// CHECK: ![[LPAD]] = !MDLocation(line: 24, scope: !{{.*}})
 
 # 1 "/usr/include/c++/4.2.1/vector" 1 3
 typedef long unsigned int __darwin_size_t;
diff --git a/test/CodeGenCXX/mangle-abi-examples.cpp b/test/CodeGenCXX/mangle-abi-examples.cpp
index 6fb82cf..832956f 100644
--- a/test/CodeGenCXX/mangle-abi-examples.cpp
+++ b/test/CodeGenCXX/mangle-abi-examples.cpp
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 %s -emit-llvm -triple %itanium_abi_triple -o - | FileCheck %s
 
-// CHECK: @_ZTVZ3foovEN1C1DE =
 // CHECK: @_ZTVZN1A3fooEiE1B =
+// CHECK: @_ZTVZ3foovEN1C1DE =
 // CHECK: define {{.*}} @_ZZZ3foovEN1C3barEvEN1E3bazEv(
 
 // Itanium C++ ABI examples.
diff --git a/test/CodeGenCXX/mangle-exprs.cpp b/test/CodeGenCXX/mangle-exprs.cpp
index ee7f244..ee2d546 100644
--- a/test/CodeGenCXX/mangle-exprs.cpp
+++ b/test/CodeGenCXX/mangle-exprs.cpp
@@ -293,3 +293,39 @@
   // CHECK-LABEL: define weak_odr void @_ZN5test62f8IiEEvDTcvT_dtptL_ZNS_2zpEE4uuss1iE
 }
 
+namespace test7 {
+  struct A { int x[3]; };
+  struct B { B(int, int); } extern b;
+  struct C { C(B); };
+  struct D { D(C); };
+  struct E { E(std::initializer_list<int>); };
+  struct F { F(E); };
+
+  template<class T> decltype(A{1,2},T()) fA1(T t) {}
+  template<class T> decltype(A({1,2}),T()) fA2(T t) {}
+  template<class T> decltype(B{1,2},T()) fB1(T t) {}
+  template<class T> decltype(B({1,2}),T()) fB2(T t) {}
+  template<class T> decltype(C{{1,2}},T()) fC1(T t) {}
+  template<class T> decltype(C({1,2}),T()) fC2(T t) {}
+  template<class T> decltype(D{b},T()) fD1(T t) {}
+  template<class T> decltype(D(b),T()) fD2(T t) {}
+  template<class T> decltype(E{1,2},T()) fE1(T t) {}
+  template<class T> decltype(E({1,2}),T()) fE2(T t) {}
+  template<class T> decltype(F{{1,2}},T()) fF1(T t) {}
+  template<class T> decltype(F({1,2}),T()) fF2(T t) {}
+
+  int main() {
+    fA1(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fA1IiEEDTcmtlNS_1AELi1ELi2EEcvT__EES2_
+    fA2(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fA2IiEEDTcmcvNS_1AEilLi1ELi2EEcvT__EES2_
+    fB1(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fB1IiEEDTcmtlNS_1BELi1ELi2EEcvT__EES2_
+    fB2(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fB2IiEEDTcmcvNS_1BEilLi1ELi2EEcvT__EES2_
+    fC1(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fC1IiEEDTcmtlNS_1CEilLi1ELi2EEEcvT__EES2_
+    fC2(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fC2IiEEDTcmcvNS_1CEilLi1ELi2EEcvT__EES2_
+    fD1(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fD1IiEEDTcmtlNS_1DEL_ZNS_1bEEEcvT__EES2_
+    fD2(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fD2IiEEDTcmcvNS_1DEL_ZNS_1bEEcvT__EES2_
+    fE1(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fE1IiEEDTcmtlNS_1EELi1ELi2EEcvT__EES2_
+    fE2(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fE2IiEEDTcmcvNS_1EEilLi1ELi2EEcvT__EES2_
+    fF1(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fF1IiEEDTcmtlNS_1FEilLi1ELi2EEEcvT__EES2_
+    fF2(1); // CHECK-LABEL: define {{.*}} @_ZN5test73fF2IiEEDTcmcvNS_1FEilLi1ELi2EEcvT__EES2_
+  }
+}
diff --git a/test/CodeGenCXX/mangle-lambdas.cpp b/test/CodeGenCXX/mangle-lambdas.cpp
index e8d3f19..1b784f3 100644
--- a/test/CodeGenCXX/mangle-lambdas.cpp
+++ b/test/CodeGenCXX/mangle-lambdas.cpp
@@ -1,9 +1,9 @@
-// RUN: %clang_cc1 -std=c++11 -triple x86_64-apple-macosx10.7.0 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-apple-macosx10.7.0 -emit-llvm -o - %s -w | FileCheck %s
 
-// CHECK: @_ZZNK7PR12917IJiiEE1nMUlvE_clEvE1n = linkonce_odr global i32 0
-// CHECK: @_ZZZN7PR12917IJicdEEC1EicdEd_NKUlvE_clEvE1n = linkonce_odr global i32 0
-// CHECK: @_ZZZN7PR12917IJicdEEC1EicdEd0_NKUlvE_clEvE1n = linkonce_odr global i32 0
 // CHECK: @_ZZZN7PR12917IJicdEEC1EicdEd1_NKUlvE_clEvE1n = linkonce_odr global i32 0
+// CHECK: @_ZZZN7PR12917IJicdEEC1EicdEd0_NKUlvE_clEvE1n = linkonce_odr global i32 0
+// CHECK: @_ZZZN7PR12917IJicdEEC1EicdEd_NKUlvE_clEvE1n = linkonce_odr global i32 0
+// CHECK: @_ZZNK7PR12917IJiiEE1nMUlvE_clEvE1n = linkonce_odr global i32 0
 
 // CHECK-LABEL: define linkonce_odr void @_Z11inline_funci
 inline void inline_func(int n) {
@@ -192,8 +192,40 @@
   };
   void B::h() { f(); }
 }
+
 // CHECK-LABEL: define linkonce_odr dereferenceable({{[0-9]+}}) %"struct.PR12123::A"* @_ZZN7PR121231B1fERKSt9type_infoEd_NKUlvE_clEv
 
+// Check linkage of the various lambdas.
+// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUlvE_clEv
+// CHECK: ret i32 1
+// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUlvE0_clEv
+// CHECK: ret i32
+// CHECK-LABEL: define linkonce_odr double @_ZZ11inline_funciENKUlvE1_clEv
+// CHECK: ret double
+// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUliE_clEi
+// CHECK: ret i32
+// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUlvE2_clEv
+// CHECK: ret i32 17
+
+// CHECK-LABEL: define linkonce_odr void @_ZN7MembersC2Ev
+// CHECK: call i32 @_ZNK7Members1xMUlvE_clEv
+// CHECK-NEXT: call i32 @_ZNK7Members1xMUlvE0_clE
+// CHECK-NEXT: add nsw i32
+// CHECK: call i32 @_ZNK7Members1yMUlvE_clEv
+// CHECK: ret void
+
+
+// Check the linkage of the lambdas used in test_Members.
+// CHECK-LABEL: define linkonce_odr i32 @_ZNK7Members1xMUlvE_clEv
+// CHECK: ret i32 1
+// CHECK-LABEL: define linkonce_odr i32 @_ZNK7Members1xMUlvE0_clEv
+// CHECK: ret i32 2
+// CHECK-LABEL: define linkonce_odr i32 @_ZNK7Members1yMUlvE_clEv
+// CHECK: ret i32 3
+
+// CHECK-LABEL: define linkonce_odr void @_Z1fIZZNK23TestNestedInstantiationclEvENKUlvE_clEvEUlvE_EvT_
+
+
 namespace PR12808 {
   template <typename> struct B {
     int a;
@@ -209,7 +241,6 @@
   // CHECK-LABEL: define linkonce_odr i32 @_ZZZN7PR128081bIiEEviENKUlvE_clEvENKUlvE_clEv
 }
 
-// CHECK-LABEL: define linkonce_odr void @_Z1fIZZNK23TestNestedInstantiationclEvENKUlvE_clEvEUlvE_EvT_
 
 struct Members {
   int x = [] { return 1; }() + [] { return 2; }();
@@ -217,13 +248,7 @@
 };
 
 void test_Members() {
-  // CHECK-LABEL: define linkonce_odr void @_ZN7MembersC2Ev
-  // CHECK: call i32 @_ZNK7Members1xMUlvE_clEv
-  // CHECK-NEXT: call i32 @_ZNK7Members1xMUlvE0_clE
-  // CHECK-NEXT: add nsw i32
-  // CHECK: call i32 @_ZNK7Members1yMUlvE_clEv
   Members members;
-  // CHECK: ret void
 }
 
 template<typename P> void f(P) { }
@@ -239,23 +264,3 @@
 void test_NestedInstantiation() {
   TestNestedInstantiation()();
 }
-
-// Check the linkage of the lambdas used in test_Members.
-// CHECK-LABEL: define linkonce_odr i32 @_ZNK7Members1xMUlvE_clEv
-// CHECK: ret i32 1
-// CHECK-LABEL: define linkonce_odr i32 @_ZNK7Members1xMUlvE0_clEv
-// CHECK: ret i32 2
-// CHECK-LABEL: define linkonce_odr i32 @_ZNK7Members1yMUlvE_clEv
-// CHECK: ret i32 3
-
-// Check linkage of the various lambdas.
-// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUlvE_clEv
-// CHECK: ret i32 1
-// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUlvE0_clEv
-// CHECK: ret i32
-// CHECK-LABEL: define linkonce_odr double @_ZZ11inline_funciENKUlvE1_clEv
-// CHECK: ret double
-// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUliE_clEi
-// CHECK: ret i32
-// CHECK-LABEL: define linkonce_odr i32 @_ZZ11inline_funciENKUlvE2_clEv
-// CHECK: ret i32 17
diff --git a/test/CodeGenCXX/mangle-local-anonymous-unions.cpp b/test/CodeGenCXX/mangle-local-anonymous-unions.cpp
new file mode 100644
index 0000000..9187c1a
--- /dev/null
+++ b/test/CodeGenCXX/mangle-local-anonymous-unions.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -emit-llvm -triple %itanium_abi_triple -o - | FileCheck %s
+
+// CHECK-DAG: @_ZZ2f0vE1a
+// CHECK-DAG: @_ZZ2f0vE1c
+// CHECK-DAG: @_ZZ2f0vE1e_0
+inline int f0() {
+  static union {
+    int a;
+    long int b;
+  };
+
+  static union {
+    int c;
+    double d;
+  };
+
+  if (0) {
+    static union {
+      int e;
+      int f;
+    };
+  }
+  static union {
+    int e;
+    int f;
+  };
+
+  return a+c;
+}
+
+inline void nop() {
+  static union {
+    union {
+    };
+  };
+}
+
+int f1 (int a, int c) {
+  nop();
+  return a+c+f0();
+}
+
diff --git a/test/CodeGenCXX/mangle-local-class-vtables.cpp b/test/CodeGenCXX/mangle-local-class-vtables.cpp
index 078d735..c90353e 100644
--- a/test/CodeGenCXX/mangle-local-class-vtables.cpp
+++ b/test/CodeGenCXX/mangle-local-class-vtables.cpp
@@ -1,24 +1,24 @@
 // RUN: %clang_cc1 %s -emit-llvm -triple %itanium_abi_triple -o - | FileCheck %s
 
-// CHECK: @_ZTVZN1J1KEvE1C = {{.*}} @_ZTIZN1J1KEvE1C {{.*}} @_ZZN1J1KEvENK1C1FEv 
-// CHECK: @_ZTIZN1J1KEvE1C = {{.*}} @_ZTSZN1J1KEvE1C
-// CHECK: @_ZTVZ1GvE1C_1 = {{.*}} @_ZTIZ1GvE1C_1 {{.*}} @_ZZ1GvENK1C1FE_1v 
-// CHECK: @_ZTIZ1GvE1C_1 = {{.*}} @_ZTSZ1GvE1C_1
-// CHECK: @_ZTVZ1GvE1C_0 = {{.*}} @_ZTIZ1GvE1C_0 {{.*}} @_ZZ1GvENK1C1FE_0v 
-// CHECK: @_ZTIZ1GvE1C_0 = {{.*}} @_ZTSZ1GvE1C_0
-// CHECK: @_ZTVZ1GvE1C = {{.*}} @_ZTIZ1GvE1C {{.*}} @_ZZ1GvENK1C1FEv 
+// CHECK: @_ZTVZ1GvE1C = {{.*}} @_ZTIZ1GvE1C {{.*}} @_ZZ1GvENK1C1FEv
 // CHECK: @_ZTIZ1GvE1C = {{.*}} @_ZTSZ1GvE1C
+// CHECK: @_ZTVZ1GvE1C_0 = {{.*}} @_ZTIZ1GvE1C_0 {{.*}} @_ZZ1GvENK1C1FE_0v
+// CHECK: @_ZTIZ1GvE1C_0 = {{.*}} @_ZTSZ1GvE1C_0
+// CHECK: @_ZTVZ1GvE1C_1 = {{.*}} @_ZTIZ1GvE1C_1 {{.*}} @_ZZ1GvENK1C1FE_1v
+// CHECK: @_ZTIZ1GvE1C_1 = {{.*}} @_ZTSZ1GvE1C_1
+// CHECK: @_ZTVZN1J1KEvE1C = {{.*}} @_ZTIZN1J1KEvE1C {{.*}} @_ZZN1J1KEvENK1C1FEv
+// CHECK: @_ZTIZN1J1KEvE1C = {{.*}} @_ZTSZN1J1KEvE1C
 
-// CHECK: define {{.*}} @_ZZN1J1KEvEN1CC2Ev(
-// CHECK: define {{.*}} @_ZZN1J1KEvENK1C1FEv(
-// CHECK: define {{.*}} @_ZZ1GvEN1CC2E_1v(
-// CHECK: define {{.*}} @_ZZ1GvENK1C1FE_1v(
-// CHECK: define {{.*}} @_ZZ1GvENK1C1HE_1v(
+// CHECK: define {{.*}} @_ZZ1GvEN1CC2Ev(
+// CHECK: define {{.*}} @_ZZ1GvENK1C1FEv(
 // CHECK: define {{.*}} @_ZZ1GvEN1CC2E_0v(
 // CHECK: define {{.*}} @_ZZ1GvENK1C1FE_0v(
 // CHECK: define {{.*}} @_ZZ1GvENK1C1GE_0v(
-// CHECK: define {{.*}} @_ZZ1GvEN1CC2Ev(
-// CHECK: define {{.*}} @_ZZ1GvENK1C1FEv(
+// CHECK: define {{.*}} @_ZZ1GvEN1CC2E_1v(
+// CHECK: define {{.*}} @_ZZ1GvENK1C1FE_1v(
+// CHECK: define {{.*}} @_ZZ1GvENK1C1HE_1v(
+// CHECK: define {{.*}} @_ZZN1J1KEvEN1CC2Ev(
+// CHECK: define {{.*}} @_ZZN1J1KEvENK1C1FEv(
 
 struct I { 
   virtual void F() const = 0;
diff --git a/test/CodeGenCXX/mangle-local-classes-nested.cpp b/test/CodeGenCXX/mangle-local-classes-nested.cpp
index cee541f..5daf0c0 100644
--- a/test/CodeGenCXX/mangle-local-classes-nested.cpp
+++ b/test/CodeGenCXX/mangle-local-classes-nested.cpp
@@ -6,10 +6,10 @@
 // CHECK: define {{.*}} @_ZZ2L1vEN1S2L2Ev(
 // CHECK: define {{.*}} @_ZZ2L1vEN1S2L2E_0v(
 // CHECK: define {{.*}} @_ZZ1FvEN1S1T1S1T1GEv(
-// CHECK: define {{.*}} @_ZZZ2L1vEN1S2L2E_0vEN1S3L3cEv(
-// CHECK: define {{.*}} @_ZZZ2L1vEN1S2L2E_0vEN1S3L3dE_0v(
 // CHECK: define {{.*}} @_ZZZ2L1vEN1S2L2EvEN1S3L3aEv(
 // CHECK: define {{.*}} @_ZZZ2L1vEN1S2L2EvEN1S3L3bE_0v(
+// CHECK: define {{.*}} @_ZZZ2L1vEN1S2L2E_0vEN1S3L3cEv(
+// CHECK: define {{.*}} @_ZZZ2L1vEN1S2L2E_0vEN1S3L3dE_0v(
 
 void L1() {
   {
diff --git a/test/CodeGenCXX/mangle-ms-abi-examples.cpp b/test/CodeGenCXX/mangle-ms-abi-examples.cpp
index 5dc9d2e..d6ff94b 100644
--- a/test/CodeGenCXX/mangle-ms-abi-examples.cpp
+++ b/test/CodeGenCXX/mangle-ms-abi-examples.cpp
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -fms-extensions -fno-rtti -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s
 
-// CHECK: @"\01??_7D@C@?1??foo@@YAXXZ@6B@" =
 // CHECK: @"\01??_7B@?1??foo@A@@QAEXH@Z@6B@" =
+// CHECK: @"\01??_7D@C@?1??foo@@YAXXZ@6B@" =
 // CHECK: define {{.*}} @"\01?baz@E@?3??bar@C@?1??foo@@YAXXZ@QAEXXZ@QAEXXZ"(
 
 // Microsoft Visual C++ ABI examples.
diff --git a/test/CodeGenCXX/mangle-ms-cxx11.cpp b/test/CodeGenCXX/mangle-ms-cxx11.cpp
index ded08b9..fe7121e 100644
--- a/test/CodeGenCXX/mangle-ms-cxx11.cpp
+++ b/test/CodeGenCXX/mangle-ms-cxx11.cpp
@@ -56,6 +56,12 @@
 // CHECK: "\01?DeducedType@@3HA"
 auto DeducedType = 30;
 
+// CHECK-DAG: @"\01?Char16Var@@3_SA"
+char16_t Char16Var;
+
+// CHECK-DAG: @"\01?Char32Var@@3_UA"
+char32_t Char32Var;
+
 // CHECK: "\01?LRef@@YAXAAH@Z"
 void LRef(int& a) { }
 
diff --git a/test/CodeGenCXX/mangle-ms-string-literals.cpp b/test/CodeGenCXX/mangle-ms-string-literals.cpp
index a77a04f..e5ebc08 100644
--- a/test/CodeGenCXX/mangle-ms-string-literals.cpp
+++ b/test/CodeGenCXX/mangle-ms-string-literals.cpp
@@ -719,3 +719,9 @@
 // CHECK: @"\01??_C@_1EK@KFPEBLPK@?$AA0?$AA1?$AA2?$AA3?$AA4?$AA5?$AA6?$AA7?$AA8?$AA9?$AA0?$AA1?$AA2?$AA3?$AA4?$AA5?$AA6?$AA7?$AA8?$AA9?$AA0?$AA1?$AA2?$AA3?$AA4?$AA5?$AA6?$AA7?$AA8?$AA9?$AAA?$AAB@"
 const wchar_t *UnicodeLiteral = L"\ud7ff";
 // CHECK: @"\01??_C@_13IIHIAFKH@?W?$PP?$AA?$AA@"
+const char *U8Literal = u8"hi";
+// CHECK: @"\01??_C@_02PCEFGMJL@hi?$AA@"
+const char16_t *U16Literal = u"hi";
+// CHECK: @"\01??_C@_05OMLEGLOC@h?$AAi?$AA?$AA?$AA@"
+const char32_t *U32Literal = U"hi";
+// CHECK: @"\01??_C@_0M@GFNAJIPG@h?$AA?$AA?$AAi?$AA?$AA?$AA?$AA?$AA?$AA?$AA@"
diff --git a/test/CodeGenCXX/mangle-ms-templates.cpp b/test/CodeGenCXX/mangle-ms-templates.cpp
index 31fda20..46ab251 100644
--- a/test/CodeGenCXX/mangle-ms-templates.cpp
+++ b/test/CodeGenCXX/mangle-ms-templates.cpp
@@ -24,6 +24,12 @@
   IntTemplate() {}
 };
 
+template<unsigned param>
+class UnsignedIntTemplate {
+public:
+  UnsignedIntTemplate() {}
+};
+
 template<long long param>
 class LongLongTemplate {
  public:
@@ -133,6 +139,10 @@
   IntTemplate<-11> neg_11;
 // CHECK: call {{.*}} @"\01??0?$IntTemplate@$0?L@@@QAE@XZ"
 // X64: call {{.*}} @"\01??0?$IntTemplate@$0?L@@@QEAA@XZ"
+  
+  UnsignedIntTemplate<4294967295> ffffffff;
+// CHECK: call {{.*}} @"\01??0?$UnsignedIntTemplate@$0PPPPPPPP@@@QAE@XZ"
+// X64: call {{.*}} @"\01??0?$UnsignedIntTemplate@$0PPPPPPPP@@@QEAA@XZ"
 
   LongLongTemplate<-9223372036854775807LL-1LL> int64_min;
 // CHECK: call {{.*}} @"\01??0?$LongLongTemplate@$0?IAAAAAAAAAAAAAAA@@@QAE@XZ"
diff --git a/test/CodeGenCXX/mangle-subst-std.cpp b/test/CodeGenCXX/mangle-subst-std.cpp
index 678956e..b06f798 100644
--- a/test/CodeGenCXX/mangle-subst-std.cpp
+++ b/test/CodeGenCXX/mangle-subst-std.cpp
@@ -3,14 +3,15 @@
 // Check mangling of Vtables, VTTs, and construction vtables that
 // involve standard substitutions.
 
+
 // CHECK: @_ZTVSd = linkonce_odr unnamed_addr constant 
 // CHECK: @_ZTTSd = linkonce_odr unnamed_addr constant
 // CHECK: @_ZTCSd0_Si = linkonce_odr unnamed_addr constant 
 // CHECK: @_ZTCSd16_So = linkonce_odr unnamed_addr constant
-// CHECK: @_ZTVSo = linkonce_odr unnamed_addr constant
-// CHECK: @_ZTTSo = linkonce_odr unnamed_addr constant
 // CHECK: @_ZTVSi = linkonce_odr unnamed_addr constant
 // CHECK: @_ZTTSi = linkonce_odr unnamed_addr constant
+// CHECK: @_ZTVSo = linkonce_odr unnamed_addr constant
+// CHECK: @_ZTTSo = linkonce_odr unnamed_addr constant
 
 namespace std {
   struct A { A(); };
diff --git a/test/CodeGenCXX/mangle-subst.cpp b/test/CodeGenCXX/mangle-subst.cpp
index 30360ae..09326e2 100644
--- a/test/CodeGenCXX/mangle-subst.cpp
+++ b/test/CodeGenCXX/mangle-subst.cpp
@@ -80,3 +80,19 @@
 void f(void (B::*)(), A, A, void (B::*)(A), void (A::*)()) { }
 
 }
+
+namespace ManglePrefix {
+template <typename>
+struct X {
+  template <typename>
+  struct Y {
+    typedef int type;
+    typedef int type2;
+  };
+};
+template <typename T>
+typename X<T>::template Y<T>::type f(typename X<T>::template Y<T>::type2) { return 0; }
+
+// CHECK: @_ZN12ManglePrefix1fIiEENS_1XIT_E1YIS2_E4typeENS5_5type2E
+template int f<int>(int);
+}
diff --git a/test/CodeGenCXX/mangle-template.cpp b/test/CodeGenCXX/mangle-template.cpp
index 998096a..aaae4b2 100644
--- a/test/CodeGenCXX/mangle-template.cpp
+++ b/test/CodeGenCXX/mangle-template.cpp
@@ -4,7 +4,7 @@
 namespace test1 {
 int x;
 template <int& D> class T { };
-// CHECK: void @_ZN5test12f0ENS_1TILZNS_1xEEEE(
+// CHECK: void @_ZN5test12f0ENS_1TIL_ZNS_1xEEEE(
 void f0(T<x> a0) {}
 }
 
@@ -12,7 +12,7 @@
 // CHECK: void @_ZN5test12f0Ef
 void f0(float) {}
 template<void (&)(float)> struct t1 {};
-// CHECK: void @_ZN5test12f1ENS_2t1ILZNS_2f0EfEEE(
+// CHECK: void @_ZN5test12f1ENS_2t1IL_ZNS_2f0EfEEE(
 void f1(t1<f0> a0) {}
 }
 
@@ -20,8 +20,7 @@
 // CHECK: void @_ZN5test22f0Ef
 void f0(float) {}
 template<void (*)(float)> struct t1 {};
-// FIXME: Fails because we don't treat as an expression.
-// CHECK-FIXME: void @_ZN5test22f1ENS_2t1IXadL_ZNS_2f0EfEEEE(
+// CHECK: void @_ZN5test22f1ENS_2t1IXadL_ZNS_2f0EfEEEE(
 void f1(t1<f0> a0) {}
 }
 
@@ -29,8 +28,7 @@
 // CHECK: void @test3_f0
 extern "C" void test3_f0(float) {}
 template<void (&)(float)> struct t1 {};
-// FIXME: Fails because we tack on a namespace.
-// CHECK-FIXME: void @_ZN5test32f1ENS_2t1ILZ8test3_f0EEE(
+// CHECK: void @_ZN5test32f1ENS_2t1IL_Z8test3_f0EEE(
 void f1(t1<test3_f0> a0) {}
 }
 
@@ -38,8 +36,7 @@
 // CHECK: void @test4_f0
 extern "C" void test4_f0(float) {}
 template<void (*)(float)> struct t1 {};
-// FIXME: Fails because we don't treat as an expression.
-// CHECK-FIXME: void @_ZN5test42f1ENS_2t1IXadL_Z8test4_f0EEEE(
+// CHECK: void @_ZN5test42f1ENS_2t1IXadL_Z8test4_f0EEEE(
 void f1(t1<test4_f0> a0) {}
 }
 
@@ -49,22 +46,20 @@
 
 namespace test5 {
 template<void (&)(float)> struct t1 {};
-// CHECK: void @_ZN5test52f1ENS_2t1ILZ8test5_f0EEE(
+// CHECK: void @_ZN5test52f1ENS_2t1IL_Z8test5_f0EEE(
 void f1(t1<test5_f0> a0) {}
 
 template<int (&)(int)> struct t2 {};
-// CHECK: void @_ZN5test52f2ENS_2t2ILZ4mainEEE
+// CHECK: void @_ZN5test52f2ENS_2t2IL_Z4mainEEE
 void f2(t2<main> a0) {}
 }
 
-// FIXME: This fails.
 namespace test6 {
 struct A { void im0(float); };
 // CHECK: void @_ZN5test61A3im0Ef
 void A::im0(float) {}
 template <void(A::*)(float)> class T { };
-// FIXME: Fails because we don't treat as an expression.
-// CHECK-FAIL: void @_ZN5test62f0ENS_1TIXadL_ZNS_1A3im0EfEEEE(
+// CHECK: void @_ZN5test62f0ENS_1TIXadL_ZNS_1A3im0EfEEEE(
 void f0(T<&A::im0> a0) {}
 }
 
@@ -164,11 +159,11 @@
   void use() {
     // CHECK-LABEL: define internal void @_ZN6test124testIFivEXadL_ZNS_L1fEvEEEEvv(
     test<int(), &f>();
-    // CHECK-LABEL: define internal void @_ZN6test124testIRFivELZNS_L1fEvEEEvv(
+    // CHECK-LABEL: define internal void @_ZN6test124testIRFivEL_ZNS_L1fEvEEEvv(
     test<int(&)(), f>();
     // CHECK-LABEL: define internal void @_ZN6test124testIPKiXadL_ZNS_L1nEEEEEvv(
     test<const int*, &n>();
-    // CHECK-LABEL: define internal void @_ZN6test124testIRKiLZNS_L1nEEEEvv(
+    // CHECK-LABEL: define internal void @_ZN6test124testIRKiL_ZNS_L1nEEEEvv(
     test<const int&, n>();
   }
 }
diff --git a/test/CodeGenCXX/mangle.cpp b/test/CodeGenCXX/mangle.cpp
index 9af0d9d..630a251 100644
--- a/test/CodeGenCXX/mangle.cpp
+++ b/test/CodeGenCXX/mangle.cpp
@@ -455,7 +455,7 @@
   void g(zed<&foo::bar>*)
   {}
 }
-// CHECK-LABEL: define weak_odr void @_ZN5test81AILZNS_1B5valueEEE3incEv
+// CHECK-LABEL: define weak_odr void @_ZN5test81AIL_ZNS_1B5valueEEE3incEv
 namespace test8 {
   template <int &counter> class A { void inc() { counter++; } };
   class B { public: static int value; };
@@ -577,10 +577,10 @@
   template <typename T> void f(S<&T::operator&>) {}
   template void f<A>(S<&A::operator&>);
 
-  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_plEEE
-  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_miEEE
-  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_mlEEE
-  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_anEEE
+  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_onplEEE
+  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_onmiEEE
+  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_onmlEEE
+  // CHECK-LABEL: define weak_odr void @_ZN6test181fINS_1AEEEvNS_1SIXadsrT_onanEEE
 }
 
 // rdar://problem/8332117
@@ -601,11 +601,11 @@
 
   // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_1fIiEEEE(
   template void g<A>(S<&A::f<int> >);
-  // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_plEEE(
+  // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_onplEEE(
   template void g<A>(S<&A::operator+>);
-  // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_cviEEE(
+  // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_oncviEEE(
   template void g<A>(S<&A::operator int>);
-  // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_miIdEEEE(
+  // CHECK-LABEL: define weak_odr void @_ZN6test191gINS_1AEEEvNS_1SIXadsrT_onmiIdEEEE(
   template void g<A>(S<&A::operator-<double> >);
 }
 
@@ -839,7 +839,7 @@
   template<typename T>
   void f1(decltype(sizeof(&T::template operator+<int>))) {}
 
-  // CHECK-LABEL: define weak_odr void @_ZN6test352f1INS_1AEEEvDTszadsrT_plIiEE
+  // CHECK-LABEL: define weak_odr void @_ZN6test352f1INS_1AEEEvDTszadsrT_onplIiEE
   template void f1<A>(__SIZE_TYPE__);
 }
 
@@ -1013,3 +1013,61 @@
   auto v = fin<S>;
   // CHECK-LABEL: declare void @_ZN6test503finINS_1SEEET_ILi3EES2_ILi4EE()
 }
+
+namespace test51 {
+  template <typename T>
+  decltype(T().~T()) fun() {}
+  template void fun<int>();
+  // CHECK-LABEL: @_ZN6test513funIiEEDTcldtcvT__EdnS1_EEv
+  template void fun<X>();
+  // CHECK-LABEL: @_ZN6test513funI1XEEDTcldtcvT__EdnS2_EEv
+  template void fun<S1<int> >();
+  // CHECK-LABEL: @_ZN6test513funI2S1IiEEEDTcldtcvT__EdnS3_EEv
+
+  enum E {};
+  template <typename T>
+  struct X {
+    struct Y {};
+  };
+
+  template <typename T>
+  decltype(S1<T>().~S1<T>()) fun1() {};
+  template <typename U, typename T>
+  decltype(U().~S1<T>()) fun2() {}
+  template <typename U, typename T>
+  decltype(S1<T>().~U()) fun3() {}
+  template <typename T>
+  decltype(S1<T>().~S1<T>(), S1<T>().~S1<T>()) fun4() {};
+  template <typename T>
+  decltype(S1<int>().~S1<T>()) fun5(){};
+  template <template <typename T> class U>
+  decltype(S1<int>().~U<int>()) fun6(){};
+  template <typename T>
+  decltype(E().E::~T()) fun7() {}
+  template <template <typename> class U>
+  decltype(X<int>::Y().U<int>::Y::~Y()) fun8() {}
+  template void fun1<int>();
+  // CHECK-LABEL: @_ZN6test514fun1IiEEDTcldtcv2S1IT_E_Edn2S1IS2_EEEv
+  template void fun2<S1<int>, int>();
+  // CHECK-LABEL: @_ZN6test514fun2I2S1IiEiEEDTcldtcvT__Edn2S1IT0_EEEv
+  template void fun3<S1<int>, int>();
+  // CHECK-LABEL: @_ZN6test514fun3I2S1IiEiEEDTcldtcvS1_IT0_E_EdnT_EEv
+  template void fun4<int>();
+  // CHECK-LABEL: @_ZN6test514fun4IiEEDTcmcldtcv2S1IT_E_Edn2S1IS2_EEcldtcvS3__Edn2S1IS2_EEEv
+  template void fun5<int>();
+  // CHECK-LABEL: @_ZN6test514fun5IiEEDTcldtcv2S1IiE_Edn2S1IT_EEEv
+  template void fun6<S1>();
+  // CHECK-LABEL: @_ZN6test514fun6I2S1EEDTcldtcvS1_IiE_EdnT_IiEEEv
+  template void fun7<E>();
+  // CHECK-LABEL: @_ZN6test514fun7INS_1EEEEDTcldtcvS1__Esr1EEdnT_EEv
+  template void fun8<X>();
+}
+
+namespace test52 {
+struct X {};
+void operator+(X);
+template <typename... T>
+auto f4(T... x) -> decltype(operator+(x...));
+// CHECK-LABEL: @_ZN6test522f4IJNS_1XEEEEDTclonplspfp_EEDpT_
+void use() { f4(X{}); }
+}
diff --git a/test/CodeGenCXX/member-function-pointers.cpp b/test/CodeGenCXX/member-function-pointers.cpp
index fb06fa7..8ae57b2 100644
--- a/test/CodeGenCXX/member-function-pointers.cpp
+++ b/test/CodeGenCXX/member-function-pointers.cpp
@@ -6,6 +6,8 @@
 
 // PNaCl uses the same representation of method pointers as ARM.
 // RUN: %clang_cc1 %s -emit-llvm -o - -triple=le32-unknown-nacl | FileCheck -check-prefix GLOBAL-ARM %s
+// MIPS uses the same representation of method pointers as ARM.
+// RUN: %clang_cc1 %s -emit-llvm -o - -triple=mips-unknown-linux-gnu | FileCheck -check-prefix GLOBAL-ARM %s
 
 struct A { int a; void f(); virtual void vf1(); virtual void vf2(); };
 struct B { int b; virtual void g(); };
diff --git a/test/CodeGenCXX/member-functions.cpp b/test/CodeGenCXX/member-functions.cpp
index 1773c67..1d2a60d 100644
--- a/test/CodeGenCXX/member-functions.cpp
+++ b/test/CodeGenCXX/member-functions.cpp
@@ -74,12 +74,11 @@
   T result = t1 + t2;
 }
 
-// S::~S()
-// CHECK: define linkonce_odr void @_ZN1SD2Ev{{.*}} unnamed_addr
-
 // S::S()
 // CHECK: define linkonce_odr void @_ZN1SC2Ev{{.*}} unnamed_addr
 
 // S::v()
 // CHECK: define linkonce_odr void @_ZN1S1vEv{{.*}}unnamed_addr
 
+// S::~S()
+// CHECK: define linkonce_odr void @_ZN1SD2Ev{{.*}} unnamed_addr
diff --git a/test/CodeGenCXX/member-init-anon-union.cpp b/test/CodeGenCXX/member-init-anon-union.cpp
index b488fa7..6c2f90d 100644
--- a/test/CodeGenCXX/member-init-anon-union.cpp
+++ b/test/CodeGenCXX/member-init-anon-union.cpp
@@ -43,6 +43,18 @@
 B b1;
 B b2(0);
 
+// CHECK: define {{.*}}@"[[CONSTRUCT_GLOBAL]]C2Ev"
+// CHECK-NOT: }
+// CHECK: call {{.*}}@_Z6make_a
+
+// CHECK: define {{.*}}@"[[CONSTRUCT_LOCAL]]C2Ev"
+// CHECK-NOT: }
+// CHECK: store i32 81
+
+// CHECK-LABEL: define {{.*}} @_ZN1BC2Ev(
+// CHECK: call void @_ZN1AC1Ev(
+// CHECK: store i32 123,
+// CHECK: }
 
 // CHECK-LABEL: define {{.*}} @_ZN1BC2Ei(
 // CHECK-NOT: call void @_ZN1AC1Ev(
@@ -51,17 +63,3 @@
 // CHECK-NOT: call void @_ZN1AC1Ev(
 // CHECK-NOT: store i32 123,
 // CHECK: }
-
-// CHECK-LABEL: define {{.*}} @_ZN1BC2Ev(
-// CHECK: call void @_ZN1AC1Ev(
-// CHECK: store i32 123,
-// CHECK: }
-
-
-// CHECK: define {{.*}}@"[[CONSTRUCT_LOCAL]]C2Ev"
-// CHECK-NOT: }
-// CHECK: store i32 81
-
-// CHECK: define {{.*}}@"[[CONSTRUCT_GLOBAL]]C2Ev"
-// CHECK-NOT: }
-// CHECK: call {{.*}}@_Z6make_a
diff --git a/test/CodeGenCXX/microsoft-abi-member-pointers.cpp b/test/CodeGenCXX/microsoft-abi-member-pointers.cpp
index f403aff..d22844a 100644
--- a/test/CodeGenCXX/microsoft-abi-member-pointers.cpp
+++ b/test/CodeGenCXX/microsoft-abi-member-pointers.cpp
@@ -15,6 +15,16 @@
 // CHECK: @"\01?b@PR20947@@3AAPQB@1@HA" = global %[[opaque1]]* null, align 4
 }
 
+namespace PR20017 {
+template <typename T>
+struct A {
+  int T::*m_fn1() { return nullptr; }
+};
+struct B;
+auto a = &A<B>::m_fn1;
+// CHECK-DAG: @"\01?a@PR20017@@3P8?$A@UB@PR20017@@@1@AEPQB@1@HXZQ21@" = global i8* bitcast ({ i32, i32, i32 } ({{.*}}*)* @"\01?m_fn1@?$A@UB@PR20017@@@PR20017@@QAEPQB@2@HXZ" to i8*), align 4
+}
+
 #ifndef INCOMPLETE_VIRTUAL
 struct B1 {
   void foo();
@@ -608,7 +618,7 @@
 // CHECK: store { i8*, i32 } { i8* bitcast (void (%"struct.Test4::C"*, ...)* @"\01??_9C@Test4@@$BA@AE" to i8*), i32 4 }, { i8*, i32 }* %{{.*}}
 //
 
-// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@Test4@@$BA@AE"(%"struct.Test4::C"* %this, ...)
+// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@Test4@@$BA@AE"(%"struct.Test4::C"* %this, ...) {{.*}} comdat
 // CHECK-NOT:  getelementptr
 // CHECK:  load void (%"struct.Test4::C"*, ...)*** %{{.*}}
 // CHECK:  getelementptr inbounds void (%"struct.Test4::C"*, ...)** %{{.*}}, i64 0
diff --git a/test/CodeGenCXX/microsoft-abi-methods.cpp b/test/CodeGenCXX/microsoft-abi-methods.cpp
index 579e549..aa3141c 100644
--- a/test/CodeGenCXX/microsoft-abi-methods.cpp
+++ b/test/CodeGenCXX/microsoft-abi-methods.cpp
@@ -75,6 +75,9 @@
 // CHECK: %{{[.0-9A-Z_a-z]+}} = call x86_thiscallcc %class.Base* @"\01??0Base@@QAE@XZ"
 // CHECK: ret
 
+// Make sure that the Base constructor definition uses the right CC:
+// CHECK: define linkonce_odr x86_thiscallcc %class.Base* @"\01??0Base@@QAE@XZ"
+
 // Make sure that the Base destructor call in the Child denstructor uses
 // the right calling convention:
 // CHECK: define linkonce_odr x86_thiscallcc void @"\01??1Child@@QAE@XZ"
@@ -83,7 +86,4 @@
 
 // Make sure that the Base destructor definition uses the right CC:
 // CHECK: define linkonce_odr x86_thiscallcc void @"\01??1Base@@QAE@XZ"
-
-// Make sure that the Base constructor definition uses the right CC:
-// CHECK: define linkonce_odr x86_thiscallcc %class.Base* @"\01??0Base@@QAE@XZ"
 }
diff --git a/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp b/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
index b1c1482..b5293e0 100644
--- a/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
+++ b/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
@@ -150,35 +150,35 @@
   Left l;
   // CHECK: define {{.*}} @"\01??0Left@@QAE@XZ"
   // CHECK-NOT: getelementptr
-  // CHECK:   store [1 x i8*]* @"\01??_7Left@@6B@"
+  // CHECK:   store i32 (...)** bitcast ([1 x i8*]* @"\01??_7Left@@6B@" to i32 (...)**)
   // CHECK: ret
 
   Right r;
   // CHECK: define {{.*}} @"\01??0Right@@QAE@XZ"
   // CHECK-NOT: getelementptr
-  // CHECK:   store [1 x i8*]* @"\01??_7Right@@6B@"
+  // CHECK:   store i32 (...)** bitcast ([1 x i8*]* @"\01??_7Right@@6B@" to i32 (...)**)
   // CHECK: ret
 
   ChildOverride co;
   // CHECK: define {{.*}} @"\01??0ChildOverride@@QAE@XZ"
   // CHECK:   %[[THIS:.*]] = load %struct.ChildOverride**
-  // CHECK:   %[[VFPTR:.*]] = bitcast %struct.ChildOverride* %[[THIS]] to [1 x i8*]**
-  // CHECK:   store [1 x i8*]* @"\01??_7ChildOverride@@6BLeft@@@", [1 x i8*]** %[[VFPTR]]
+  // CHECK:   %[[VFPTR:.*]] = bitcast %struct.ChildOverride* %[[THIS]] to i32 (...)***
+  // CHECK:   store i32 (...)** bitcast ([1 x i8*]* @"\01??_7ChildOverride@@6BLeft@@@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
   // CHECK:   %[[THIS_i8:.*]] = bitcast %struct.ChildOverride* %[[THIS]] to i8*
   // CHECK:   %[[VFPTR_i8:.*]] = getelementptr inbounds i8* %[[THIS_i8]], i32 4
-  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to [1 x i8*]**
-  // CHECK:   store [1 x i8*]* @"\01??_7ChildOverride@@6BRight@@@", [1 x i8*]** %[[VFPTR]]
+  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to i32 (...)***
+  // CHECK:   store i32 (...)** bitcast ([1 x i8*]* @"\01??_7ChildOverride@@6BRight@@@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
   // CHECK: ret
 
   GrandchildOverride gc;
   // CHECK: define {{.*}} @"\01??0GrandchildOverride@@QAE@XZ"
   // CHECK:   %[[THIS:.*]] = load %struct.GrandchildOverride**
-  // CHECK:   %[[VFPTR:.*]] = bitcast %struct.GrandchildOverride* %[[THIS]] to [1 x i8*]**
-  // CHECK:   store [1 x i8*]* @"\01??_7GrandchildOverride@@6BLeft@@@", [1 x i8*]** %[[VFPTR]]
+  // CHECK:   %[[VFPTR:.*]] = bitcast %struct.GrandchildOverride* %[[THIS]] to i32 (...)***
+  // CHECK:   store i32 (...)** bitcast ([1 x i8*]* @"\01??_7GrandchildOverride@@6BLeft@@@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
   // CHECK:   %[[THIS_i8:.*]] = bitcast %struct.GrandchildOverride* %[[THIS]] to i8*
   // CHECK:   %[[VFPTR_i8:.*]] = getelementptr inbounds i8* %[[THIS_i8]], i32 4
-  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to [1 x i8*]**
-  // CHECK:   store [1 x i8*]* @"\01??_7GrandchildOverride@@6BRight@@@", [1 x i8*]** %[[VFPTR]]
+  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to i32 (...)***
+  // CHECK:   store i32 (...)** bitcast ([1 x i8*]* @"\01??_7GrandchildOverride@@6BRight@@@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
   // CHECK: ret
 }
 
diff --git a/test/CodeGenCXX/microsoft-abi-rtti.cpp b/test/CodeGenCXX/microsoft-abi-rtti.cpp
index 062f597..10aca6e 100644
--- a/test/CodeGenCXX/microsoft-abi-rtti.cpp
+++ b/test/CodeGenCXX/microsoft-abi-rtti.cpp
@@ -26,242 +26,242 @@
 struct A2 : Z2, Y2 {};
 struct B2 : virtual A2 { B2() {} virtual void f() {} } b2;
 
-// CHECK: @"\01??_R4B2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 8, i32 4, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" }
-// CHECK: @"\01??_R0?AUB2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB2@@\00" }
-// CHECK: @"\01??_R3B2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 4, %rtti.BaseClassDescriptor** getelementptr inbounds ([5 x %rtti.BaseClassDescriptor*]* @"\01??_R2B2@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2B2@@8" = linkonce_odr constant [5 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B2@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A2@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@Z2@@8", %rtti.BaseClassDescriptor* @"\01??_R13A@3EA@Y2@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@B2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i8*), i32 3, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" }
-// CHECK: @"\01??_R1A@A@3FA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), i32 2, i32 0, i32 0, i32 4, i32 80, %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }
-// CHECK: @"\01??_R0?AUA2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA2@@\00" }
-// CHECK: @"\01??_R3A2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 1, i32 3, %rtti.BaseClassDescriptor** getelementptr inbounds ([4 x %rtti.BaseClassDescriptor*]* @"\01??_R2A2@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2A2@@8" = linkonce_odr constant [4 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A2@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EA@Y2@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), i32 2, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }
-// CHECK: @"\01??_R1A@?0A@EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" }
-// CHECK: @"\01??_R0?AUZ2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUZ2@@\00" }
-// CHECK: @"\01??_R3Z2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2Z2@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2Z2@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R13?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), i32 0, i32 4, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }
-// CHECK: @"\01??_R0?AUY2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY2@@\00" }
-// CHECK: @"\01??_R3Y2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2Y2@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2Y2@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y2@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }
-// CHECK: @"\01??_R1A@A@3EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" }
-// CHECK: @"\01??_R13A@3EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), i32 0, i32 4, i32 0, i32 4, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }
-// CHECK: @"\01??_R4B2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 12, i32 8, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" }
-// CHECK: @"\01??_R4A2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }
-// CHECK: @"\01??_R4A2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }
-// CHECK: @"\01??_R4Y2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }
-// CHECK: @"\01??_R4Z2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" }
-// CHECK: @"\01??_R4B1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 8, i32 4, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" }
-// CHECK: @"\01??_R0?AUB1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB1@@\00" }
-// CHECK: @"\01??_R3B1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2B1@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2B1@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A1@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@B1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" }
-// CHECK: @"\01??_R1A@A@3FA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 80, %rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" }
-// CHECK: @"\01??_R0?AUA1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA1@@\00" }
-// CHECK: @"\01??_R3A1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2A1@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2A1@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A1@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" }
-// CHECK: @"\01??_R4A1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" }
-// CHECK: @"\01??_R4Y1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" }
-// CHECK: @"\01??_R0?AUY1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY1@@\00" }
-// CHECK: @"\01??_R3Y1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 6, %rtti.BaseClassDescriptor** getelementptr inbounds ([7 x %rtti.BaseClassDescriptor*]* @"\01??_R2Y1@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2Y1@@8" = linkonce_odr constant [7 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@Y1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i8*), i32 5, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" }
-// CHECK: @"\01??_R1A@?0A@EA@W1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i8*), i32 2, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" }
-// CHECK: @"\01??_R0?AUW1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUW1@@\00" }
-// CHECK: @"\01??_R3W1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, %rtti.BaseClassDescriptor** getelementptr inbounds ([4 x %rtti.BaseClassDescriptor*]* @"\01??_R2W1@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2W1@@8" = linkonce_odr constant [4 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@A@3FA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i8*), i32 1, i32 0, i32 0, i32 4, i32 80, %rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" }
-// CHECK: @"\01??_R0?AUV1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUV1@@\00" }
-// CHECK: @"\01??_R3V1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2V1@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2V1@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" }
-// CHECK: @"\01??_R1A@?0A@EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" }
-// CHECK: @"\01??_R0?AUX1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUX1@@\00" }
-// CHECK: @"\01??_R3X1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2X1@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2X1@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@A@3EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" }
-// CHECK: @"\01??_R4W1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" }
-// CHECK: @"\01??_R4V1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" }
-// CHECK: @"\01??_R4X1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" }
-// CHECK: @"\01??_R4C@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" }
-// CHECK: @"\01??_R0?AUC@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUC@@\00" }
-// CHECK: @"\01??_R3C@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, %rtti.BaseClassDescriptor** getelementptr inbounds ([4 x %rtti.BaseClassDescriptor*]* @"\01??_R2C@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2C@@8" = linkonce_odr constant [4 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@C@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EA@B@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EA@A@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@C@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i8*), i32 2, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" }
-// CHECK: @"\01??_R13?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i8*), i32 1, i32 4, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" }
-// CHECK: @"\01??_R0?AUB@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUB@@\00" }
-// CHECK: @"\01??_R3B@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2B@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2B@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" }
-// CHECK: @"\01??_R1A@?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" }
-// CHECK: @"\01??_R0?AUA@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUA@@\00" }
-// CHECK: @"\01??_R3A@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2A@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2A@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R13?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i8*), i32 0, i32 4, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" }
-// CHECK: @"\01??_R4Y@@6BZ@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" }
-// CHECK: @"\01??_R0?AVY@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVY@@\00" }
-// CHECK: @"\01??_R3Y@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 9, %rtti.BaseClassDescriptor** getelementptr inbounds ([10 x %rtti.BaseClassDescriptor*]* @"\01??_R2Y@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2Y@@8" = linkonce_odr constant [10 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@Z@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EN@W@@8", %rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@M@@8", %rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@N@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33FN@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33EJ@X@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33FN@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33EJ@X@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@Y@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i8*), i32 8, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" }
-// CHECK: @"\01??_R1A@?0A@EN@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" }
-// CHECK: @"\01??_R0?AVZ@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVZ@@\00" }
-// CHECK: @"\01??_R3Z@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2Z@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2Z@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" }
-// CHECK: @"\01??_R13?0A@EN@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i8*), i32 4, i32 4, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" }
-// CHECK: @"\01??_R0?AVW@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVW@@\00" }
-// CHECK: @"\01??_R3W@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 5, %rtti.BaseClassDescriptor** getelementptr inbounds ([6 x %rtti.BaseClassDescriptor*]* @"\01??_R2W@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2W@@8" = linkonce_odr constant [6 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EN@M@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EN@N@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FN@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EJ@X@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i8*), i32 4, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" }
-// CHECK: @"\01??_R13?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i8*), i32 1, i32 4, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" }
-// CHECK: @"\01??_R0?AUM@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUM@@\00" }
-// CHECK: @"\01??_R3M@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2M@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2M@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@M@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@N@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" }
-// CHECK: @"\01??_R1A@?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }
-// CHECK: @"\01??_R0?AUN@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUN@@\00" }
-// CHECK: @"\01??_R3N@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2N@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2N@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@N@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }
-// CHECK: @"\01??_R13?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 4, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }
-// CHECK: @"\01??_R1A@A@3FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), i32 1, i32 0, i32 0, i32 4, i32 93, %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }
-// CHECK: @"\01??_R0?AVV@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVV@@\00" }
-// CHECK: @"\01??_R3V@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2V@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2V@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@?0A@EA@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }
-// CHECK: @"\01??_R1A@?0A@EA@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }
-// CHECK: @"\01??_R0?AUX@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUX@@\00" }
-// CHECK: @"\01??_R3X@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2X@@8", i32 0, i32 0) }
-// CHECK: @"\01??_R2X@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8", %rtti.BaseClassDescriptor* null]
-// CHECK: @"\01??_R1A@A@3EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 73, %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }
-// CHECK: @"\01??_R17?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i8*), i32 1, i32 8, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" }
-// CHECK: @"\01??_R17?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 8, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }
-// CHECK: @"\01??_R1A@33FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), i32 1, i32 0, i32 4, i32 4, i32 93, %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }
-// CHECK: @"\01??_R1A@33EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), i32 0, i32 0, i32 4, i32 4, i32 73, %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }
-// CHECK: @"\01??_R4Y@@6BW@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 8, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" }
-// CHECK: @"\01??_R4W@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" }
-// CHECK: @"\01??_R4Z@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" }
-// CHECK: @"\01??_R4V@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }
-// CHECK: @"\01??_R4X@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }
+// CHECK-DAG: @"\01??_R4B2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 8, i32 4, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUB2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB2@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3B2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 4, %rtti.BaseClassDescriptor** getelementptr inbounds ([5 x %rtti.BaseClassDescriptor*]* @"\01??_R2B2@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2B2@@8" = linkonce_odr constant [5 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B2@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A2@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@Z2@@8", %rtti.BaseClassDescriptor* @"\01??_R13A@3EA@Y2@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@B2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i8*), i32 3, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@A@3FA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), i32 2, i32 0, i32 0, i32 4, i32 80, %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUA2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA2@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3A2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 1, i32 3, %rtti.BaseClassDescriptor** getelementptr inbounds ([4 x %rtti.BaseClassDescriptor*]* @"\01??_R2A2@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2A2@@8" = linkonce_odr constant [4 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A2@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EA@Y2@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), i32 2, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUZ2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUZ2@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3Z2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2Z2@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2Z2@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R13?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), i32 0, i32 4, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUY2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY2@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3Y2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2Y2@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2Y2@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y2@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@A@3EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" }, comdat
+// CHECK-DAG: @"\01??_R13A@3EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), i32 0, i32 4, i32 0, i32 4, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }, comdat
+// CHECK-DAG: @"\01??_R4B2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 12, i32 8, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" }, comdat
+// CHECK-DAG: @"\01??_R4A2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }, comdat
+// CHECK-DAG: @"\01??_R4A2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" }, comdat
+// CHECK-DAG: @"\01??_R4Y2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" }, comdat
+// CHECK-DAG: @"\01??_R4Z2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" }, comdat
+// CHECK-DAG: @"\01??_R4B1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 8, i32 4, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUB1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB1@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3B1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2B1@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2B1@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A1@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@B1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@A@3FA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 80, %rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUA1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA1@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3A1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2A1@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2A1@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A1@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" }, comdat
+// CHECK-DAG: @"\01??_R4A1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" }, comdat
+// CHECK-DAG: @"\01??_R4Y1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUY1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY1@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3Y1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 6, %rtti.BaseClassDescriptor** getelementptr inbounds ([7 x %rtti.BaseClassDescriptor*]* @"\01??_R2Y1@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2Y1@@8" = linkonce_odr constant [7 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@Y1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i8*), i32 5, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@W1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i8*), i32 2, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUW1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUW1@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3W1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, %rtti.BaseClassDescriptor** getelementptr inbounds ([4 x %rtti.BaseClassDescriptor*]* @"\01??_R2W1@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2W1@@8" = linkonce_odr constant [4 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@A@3FA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i8*), i32 1, i32 0, i32 0, i32 4, i32 80, %rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUV1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUV1@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3V1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2V1@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2V1@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V1@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUX1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUX1@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3X1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2X1@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2X1@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@A@3EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" }, comdat
+// CHECK-DAG: @"\01??_R4W1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" }, comdat
+// CHECK-DAG: @"\01??_R4V1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" }, comdat
+// CHECK-DAG: @"\01??_R4X1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" }, comdat
+// CHECK-DAG: @"\01??_R4C@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUC@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUC@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3C@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, %rtti.BaseClassDescriptor** getelementptr inbounds ([4 x %rtti.BaseClassDescriptor*]* @"\01??_R2C@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2C@@8" = linkonce_odr constant [4 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@C@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EA@B@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EA@A@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@C@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i8*), i32 2, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" }, comdat
+// CHECK-DAG: @"\01??_R13?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i8*), i32 1, i32 4, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUB@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUB@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3B@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2B@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2B@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUA@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUA@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3A@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2A@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2A@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R13?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i8*), i32 0, i32 4, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" }, comdat
+// CHECK-DAG: @"\01??_R4Y@@6BZ@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AVY@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVY@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3Y@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 9, %rtti.BaseClassDescriptor** getelementptr inbounds ([10 x %rtti.BaseClassDescriptor*]* @"\01??_R2Y@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2Y@@8" = linkonce_odr constant [10 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@Z@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EN@W@@8", %rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@M@@8", %rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@N@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33FN@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33EJ@X@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33FN@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@33EJ@X@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@Y@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i8*), i32 8, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EN@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AVZ@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVZ@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3Z@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2Z@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2Z@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" }, comdat
+// CHECK-DAG: @"\01??_R13?0A@EN@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i8*), i32 4, i32 4, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AVW@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVW@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3W@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 5, %rtti.BaseClassDescriptor** getelementptr inbounds ([6 x %rtti.BaseClassDescriptor*]* @"\01??_R2W@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2W@@8" = linkonce_odr constant [6 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EN@M@@8", %rtti.BaseClassDescriptor* @"\01??_R13?0A@EN@N@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3FN@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@A@3EJ@X@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i8*), i32 4, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" }, comdat
+// CHECK-DAG: @"\01??_R13?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i8*), i32 1, i32 4, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUM@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUM@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3M@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2M@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2M@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@M@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@N@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUN@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUN@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3N@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2N@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2N@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@N@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }, comdat
+// CHECK-DAG: @"\01??_R13?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 4, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@A@3FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), i32 1, i32 0, i32 0, i32 4, i32 93, %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AVV@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVV@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3V@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, %rtti.BaseClassDescriptor** getelementptr inbounds ([3 x %rtti.BaseClassDescriptor*]* @"\01??_R2V@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2V@@8" = linkonce_odr constant [3 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V@@8", %rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), i32 1, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@?0A@EA@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), i32 0, i32 0, i32 -1, i32 0, i32 64, %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }, comdat
+// CHECK-DAG: @"\01??_R0?AUX@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUX@@\00" }, comdat
+// CHECK-DAG: @"\01??_R3X@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, %rtti.BaseClassDescriptor** getelementptr inbounds ([2 x %rtti.BaseClassDescriptor*]* @"\01??_R2X@@8", i32 0, i32 0) }, comdat
+// CHECK-DAG: @"\01??_R2X@@8" = linkonce_odr constant [2 x %rtti.BaseClassDescriptor*] [%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8", %rtti.BaseClassDescriptor* null], comdat
+// CHECK-DAG: @"\01??_R1A@A@3EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), i32 0, i32 0, i32 0, i32 4, i32 73, %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }, comdat
+// CHECK-DAG: @"\01??_R17?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i8*), i32 1, i32 8, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" }, comdat
+// CHECK-DAG: @"\01??_R17?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i8*), i32 0, i32 8, i32 -1, i32 0, i32 77, %rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@33FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), i32 1, i32 0, i32 4, i32 4, i32 93, %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }, comdat
+// CHECK-DAG: @"\01??_R1A@33EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), i32 0, i32 0, i32 4, i32 4, i32 73, %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }, comdat
+// CHECK-DAG: @"\01??_R4Y@@6BW@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 8, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" }, comdat
+// CHECK-DAG: @"\01??_R4W@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 4, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" }, comdat
+// CHECK-DAG: @"\01??_R4Z@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" }, comdat
+// CHECK-DAG: @"\01??_R4V@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" }, comdat
+// CHECK-DAG: @"\01??_R4X@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 0, i32 0, i32 0, i8* bitcast (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i8*), %rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" }, comdat
 
-// X64: @"\01??_R4B2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 16, i32 4, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4B2@@6BZ2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUB2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB2@@\00" }
-// X64: @"\01??_R3B2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 4, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([5 x i32]* @"\01??_R2B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2B2@@8" = linkonce_odr constant [5 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17A@3EA@Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@B2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 3, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@A@3FA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 0, i32 4, i32 80, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUA2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA2@@\00" }
-// X64: @"\01??_R3A2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 1, i32 3, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([4 x i32]* @"\01??_R2A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2A2@@8" = linkonce_odr constant [4 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EA@Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUZ2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUZ2@@\00" }
-// X64: @"\01??_R3Z2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2Z2@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R17?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUY2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY2@@\00" }
-// X64: @"\01??_R3Y2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2Y2@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@A@3EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R17A@3EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 0, i32 4, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4B2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 24, i32 12, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4B2@@6BY2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4A2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4A2@@6BZ2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4A2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4A2@@6BY2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4Y2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y2@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4Z2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Z2@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4B1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 16, i32 4, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4B1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUB1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB1@@\00" }
-// X64: @"\01??_R3B1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2B1@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@B1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@A@3FA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 80, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUA1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA1@@\00" }
-// X64: @"\01??_R3A1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2A1@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4A1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4A1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4Y1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUY1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY1@@\00" }
-// X64: @"\01??_R3Y1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 6, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([7 x i32]* @"\01??_R2Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2Y1@@8" = linkonce_odr constant [7 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@Y1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 5, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EA@W1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUW1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUW1@@\00" }
-// X64: @"\01??_R3W1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([4 x i32]* @"\01??_R2W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2W1@@8" = linkonce_odr constant [4 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@A@3FA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 0, i32 4, i32 80, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUV1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUV1@@\00" }
-// X64: @"\01??_R3V1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2V1@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUX1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUX1@@\00" }
-// X64: @"\01??_R3X1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2X1@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@A@3EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4W1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4W1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4V1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4V1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4X1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4X1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4C@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4C@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUC@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUC@@\00" }
-// X64: @"\01??_R3C@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([4 x i32]* @"\01??_R2C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2C@@8" = linkonce_odr constant [4 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EA@B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EA@A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@C@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R17?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 8, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUB@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUB@@\00" }
-// X64: @"\01??_R3B@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2B@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUA@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUA@@\00" }
-// X64: @"\01??_R3A@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2A@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R17?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4Y@@6BZ@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y@@6BZ@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AVY@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVY@@\00" }
-// X64: @"\01??_R3Y@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 9, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([10 x i32]* @"\01??_R2Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2Y@@8" = linkonce_odr constant [10 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1BA@?0A@EN@M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1BA@?0A@EN@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73FN@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73EJ@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73FN@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73EJ@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@Y@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 8, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EN@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AVZ@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVZ@@\00" }
-// X64: @"\01??_R3Z@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2Z@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R17?0A@EN@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 4, i32 8, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AVW@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVW@@\00" }
-// X64: @"\01??_R3W@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 5, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([6 x i32]* @"\01??_R2W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2W@@8" = linkonce_odr constant [6 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FN@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EJ@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 4, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R17?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 8, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUM@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUM@@\00" }
-// X64: @"\01??_R3M@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2M@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUN@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUN@@\00" }
-// X64: @"\01??_R3N@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2N@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R17?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@A@3FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 0, i32 4, i32 93, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AVV@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVV@@\00" }
-// X64: @"\01??_R3V@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2V@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@?0A@EA@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@?0A@EA@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R0?AUX@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUX@@\00" }
-// X64: @"\01??_R3X@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R2X@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0]
-// X64: @"\01??_R1A@A@3EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 73, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1BA@?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 16, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1BA@?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 16, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@73FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 8, i32 4, i32 93, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R1A@73EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 8, i32 4, i32 73, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4Y@@6BW@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 16, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y@@6BW@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4W@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4W@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4Z@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Z@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4V@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4V@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
-// X64: @"\01??_R4X@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4X@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }
+// X64-DAG: @"\01??_R4B2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 16, i32 4, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4B2@@6BZ2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUB2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB2@@\00" }, comdat
+// X64-DAG: @"\01??_R3B2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 4, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([5 x i32]* @"\01??_R2B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2B2@@8" = linkonce_odr constant [5 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17A@3EA@Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@B2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 3, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@A@3FA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 0, i32 4, i32 80, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUA2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA2@@\00" }, comdat
+// X64-DAG: @"\01??_R3A2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 1, i32 3, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([4 x i32]* @"\01??_R2A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2A2@@8" = linkonce_odr constant [4 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EA@Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@A2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUZ2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUZ2@@\00" }, comdat
+// X64-DAG: @"\01??_R3Z2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2Z2@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R17?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUY2@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY2@@\00" }, comdat
+// X64-DAG: @"\01??_R3Y2@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2Y2@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@A@3EA@Z2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R17A@3EA@Y2@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 0, i32 4, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4B2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 24, i32 12, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4B2@@6BY2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4A2@@6BZ2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4A2@@6BZ2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4A2@@6BY2@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4A2@@6BY2@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4Y2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y2@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4Z2@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUZ2@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z2@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Z2@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4B1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 16, i32 4, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4B1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUB1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUB1@@\00" }, comdat
+// X64-DAG: @"\01??_R3B1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2B1@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@B1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUB1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@A@3FA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 80, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUA1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUA1@@\00" }, comdat
+// X64-DAG: @"\01??_R3A1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2A1@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@A1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4A1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUA1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4A1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4Y1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUY1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUY1@@\00" }, comdat
+// X64-DAG: @"\01??_R3Y1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 6, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([7 x i32]* @"\01??_R2Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2Y1@@8" = linkonce_odr constant [7 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@Y1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUY1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 5, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@W1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUW1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUW1@@\00" }, comdat
+// X64-DAG: @"\01??_R3W1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([4 x i32]* @"\01??_R2W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2W1@@8" = linkonce_odr constant [4 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@A@3FA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 0, i32 4, i32 80, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUV1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUV1@@\00" }, comdat
+// X64-DAG: @"\01??_R3V1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2V1@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@V1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUX1@@@8" = linkonce_odr global %rtti.TypeDescriptor8 { i8** @"\01??_7type_info@@6B@", i8* null, [9 x i8] c".?AUX1@@\00" }, comdat
+// X64-DAG: @"\01??_R3X1@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2X1@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@A@3EA@X1@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4W1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUW1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4W1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4V1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUV1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4V1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4X1@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor8* @"\01??_R0?AUX1@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X1@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4X1@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4C@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4C@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUC@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUC@@\00" }, comdat
+// X64-DAG: @"\01??_R3C@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 3, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([4 x i32]* @"\01??_R2C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2C@@8" = linkonce_odr constant [4 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EA@B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EA@A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@C@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUC@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 2, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3C@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R17?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 8, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUB@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUB@@\00" }, comdat
+// X64-DAG: @"\01??_R3B@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2B@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@B@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUB@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3B@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUA@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUA@@\00" }, comdat
+// X64-DAG: @"\01??_R3A@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2A@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R17?0A@EA@A@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUA@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3A@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4Y@@6BZ@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y@@6BZ@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AVY@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVY@@\00" }, comdat
+// X64-DAG: @"\01??_R3Y@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 9, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([10 x i32]* @"\01??_R2Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2Y@@8" = linkonce_odr constant [10 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1BA@?0A@EN@M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1BA@?0A@EN@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73FN@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73EJ@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73FN@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@73EJ@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@Y@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 8, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EN@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AVZ@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVZ@@\00" }, comdat
+// X64-DAG: @"\01??_R3Z@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2Z@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@Z@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R17?0A@EN@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 4, i32 8, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AVW@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVW@@\00" }, comdat
+// X64-DAG: @"\01??_R3W@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 3, i32 5, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([6 x i32]* @"\01??_R2W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2W@@8" = linkonce_odr constant [6 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R17?0A@EN@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3FN@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@A@3EJ@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@W@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 4, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R17?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 8, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUM@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUM@@\00" }, comdat
+// X64-DAG: @"\01??_R3M@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2M@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EN@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUN@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUN@@\00" }, comdat
+// X64-DAG: @"\01??_R3N@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2N@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R17?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 8, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@A@3FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 0, i32 4, i32 93, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AVV@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AVV@@\00" }, comdat
+// X64-DAG: @"\01??_R3V@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 2, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([3 x i32]* @"\01??_R2V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2V@@8" = linkonce_odr constant [3 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@?0A@EA@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 -1, i32 0, i32 64, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R0?AUX@@@8" = linkonce_odr global %rtti.TypeDescriptor7 { i8** @"\01??_7type_info@@6B@", i8* null, [8 x i8] c".?AUX@@\00" }, comdat
+// X64-DAG: @"\01??_R3X@@8" = linkonce_odr constant %rtti.ClassHierarchyDescriptor { i32 0, i32 0, i32 1, i32 trunc (i64 sub nuw nsw (i64 ptrtoint ([2 x i32]* @"\01??_R2X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R2X@@8" = linkonce_odr constant [2 x i32] [i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.BaseClassDescriptor* @"\01??_R1A@?0A@EA@X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0], comdat
+// X64-DAG: @"\01??_R1A@A@3EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 0, i32 4, i32 73, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1BA@?0A@EN@M@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUM@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 16, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3M@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1BA@?0A@EN@N@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUN@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 16, i32 -1, i32 0, i32 77, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3N@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@73FN@V@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 1, i32 0, i32 8, i32 4, i32 93, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R1A@73EJ@X@@8" = linkonce_odr constant %rtti.BaseClassDescriptor { i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 0, i32 0, i32 8, i32 4, i32 73, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4Y@@6BW@@@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 16, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVY@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Y@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Y@@6BW@@@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4W@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 8, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVW@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3W@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4W@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4Z@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVZ@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3Z@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4Z@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4V@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AVV@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3V@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4V@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
+// X64-DAG: @"\01??_R4X@@6B@" = linkonce_odr constant %rtti.CompleteObjectLocator { i32 1, i32 0, i32 0, i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.TypeDescriptor7* @"\01??_R0?AUX@@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.ClassHierarchyDescriptor* @"\01??_R3X@@8" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32), i32 trunc (i64 sub nuw nsw (i64 ptrtoint (%rtti.CompleteObjectLocator* @"\01??_R4X@@6B@" to i64), i64 ptrtoint (i8* @__ImageBase to i64)) to i32) }, comdat
diff --git a/test/CodeGenCXX/microsoft-abi-static-initializers.cpp b/test/CodeGenCXX/microsoft-abi-static-initializers.cpp
index 76d7e9e..0873592 100644
--- a/test/CodeGenCXX/microsoft-abi-static-initializers.cpp
+++ b/test/CodeGenCXX/microsoft-abi-static-initializers.cpp
@@ -28,11 +28,11 @@
 // See @llvm.global_ctors above.
 __declspec(selectany) S selectany1;
 __declspec(selectany) S selectany2;
-// CHECK: define linkonce_odr void @"\01??__Eselectany1@@YAXXZ"()
+// CHECK: define linkonce_odr void @"\01??__Eselectany1@@YAXXZ"() {{.*}} comdat
 // CHECK-NOT: @"\01??_Bselectany1
 // CHECK: call x86_thiscallcc %struct.S* @"\01??0S@@QAE@XZ"
 // CHECK: ret void
-// CHECK: define linkonce_odr void @"\01??__Eselectany2@@YAXXZ"()
+// CHECK: define linkonce_odr void @"\01??__Eselectany2@@YAXXZ"() {{.*}} comdat
 // CHECK-NOT: @"\01??_Bselectany2
 // CHECK: call x86_thiscallcc %struct.S* @"\01??0S@@QAE@XZ"
 // CHECK: ret void
@@ -133,7 +133,7 @@
   return s;
 }
 
-// CHECK-LABEL: define linkonce_odr dereferenceable({{[0-9]+}}) %struct.S* @"\01?UnreachableStatic@@YAAAUS@@XZ"()
+// CHECK-LABEL: define linkonce_odr dereferenceable({{[0-9]+}}) %struct.S* @"\01?UnreachableStatic@@YAAAUS@@XZ"() {{.*}} comdat
 // CHECK: and i32 {{.*}}, 2
 // CHECK: or i32 {{.*}}, 2
 // CHECK: ret
@@ -143,7 +143,7 @@
   return TheS;
 }
 
-// CHECK-LABEL: define linkonce_odr dereferenceable({{[0-9]+}}) %struct.S* @"\01?getS@@YAAAUS@@XZ"
+// CHECK-LABEL: define linkonce_odr dereferenceable({{[0-9]+}}) %struct.S* @"\01?getS@@YAAAUS@@XZ"() {{.*}} comdat
 // CHECK: load i32* @"\01??_B?1??getS@@YAAAUS@@XZ@51"
 // CHECK: and i32 {{.*}}, 1
 // CHECK: icmp ne i32 {{.*}}, 0
@@ -158,7 +158,7 @@
 // CHECK: ret %struct.S* @"\01?TheS@?1??getS@@YAAAUS@@XZ@4U2@A"
 
 inline int enum_in_function() {
-  // CHECK-LABEL: define linkonce_odr i32 @"\01?enum_in_function@@YAHXZ"()
+  // CHECK-LABEL: define linkonce_odr i32 @"\01?enum_in_function@@YAHXZ"() {{.*}} comdat
   static enum e { foo, bar, baz } x;
   // CHECK: @"\01?x@?1??enum_in_function@@YAHXZ@4W4e@?1??1@YAHXZ@A"
   static int y;
@@ -169,7 +169,7 @@
 struct T {
   enum e { foo, bar, baz };
   int enum_in_struct() {
-    // CHECK-LABEL: define linkonce_odr x86_thiscallcc i32 @"\01?enum_in_struct@T@@QAEHXZ"
+    // CHECK-LABEL: define linkonce_odr x86_thiscallcc i32 @"\01?enum_in_struct@T@@QAEHXZ"({{.*}}) {{.*}} comdat
     static int x;
     // CHECK: @"\01?x@?1??enum_in_struct@T@@QAEHXZ@4HA"
     return x++;
@@ -177,7 +177,7 @@
 };
 
 inline int switch_test(int x) {
-  // CHECK-LABEL: define linkonce_odr i32 @"\01?switch_test@@YAHH@Z"(i32 %x)
+  // CHECK-LABEL: define linkonce_odr i32 @"\01?switch_test@@YAHH@Z"(i32 %x) {{.*}} comdat
   switch (x) {
     static int a;
     // CHECK: @"\01?a@?3??switch_test@@YAHH@Z@4HA"
@@ -198,7 +198,7 @@
 
 int f();
 inline void switch_test2() {
-  // CHECK-LABEL: define linkonce_odr void @"\01?switch_test2@@YAXXZ"()
+  // CHECK-LABEL: define linkonce_odr void @"\01?switch_test2@@YAXXZ"() {{.*}} comdat
   // CHECK: @"\01?x@?2??switch_test2@@YAXXZ@4HA"
   switch (1) default: static int x = f();
 }
@@ -213,7 +213,7 @@
   template struct __declspec(dllimport) A<int>;
 
   inline int switch_test3() {
-    // CHECK-LABEL: define linkonce_odr i32 @"\01?switch_test3@DynamicDLLImportInitVSMangling@@YAHXZ"
+    // CHECK-LABEL: define linkonce_odr i32 @"\01?switch_test3@DynamicDLLImportInitVSMangling@@YAHXZ"() {{.*}} comdat
     static int local;
     // CHECK: @"\01?local@?1??switch_test3@DynamicDLLImportInitVSMangling@@YAHXZ@4HA"
     return local++;
@@ -231,16 +231,16 @@
   DynamicDLLImportInitVSMangling::switch_test3();
 }
 
-// CHECK: define linkonce_odr void @"\01??__Efoo@?$B@H@@2VA@@A@YAXXZ"()
+// CHECK: define linkonce_odr void @"\01??__Efoo@?$B@H@@2VA@@A@YAXXZ"() {{.*}} comdat
 // CHECK-NOT: and
 // CHECK-NOT: ?_Bfoo@
 // CHECK: call x86_thiscallcc %class.A* @"\01??0A@@QAE@XZ"
 // CHECK: call i32 @atexit(void ()* @"\01??__Ffoo@?$B@H@@2VA@@A@YAXXZ")
 // CHECK: ret void
 
-// CHECK: define linkonce_odr x86_thiscallcc %class.A* @"\01??0A@@QAE@XZ"
+// CHECK: define linkonce_odr x86_thiscallcc %class.A* @"\01??0A@@QAE@XZ"({{.*}}) {{.*}} comdat
 
-// CHECK: define linkonce_odr x86_thiscallcc void @"\01??1A@@QAE@XZ"
+// CHECK: define linkonce_odr x86_thiscallcc void @"\01??1A@@QAE@XZ"({{.*}}) {{.*}} comdat
 
 // CHECK: define internal void @"\01??__Ffoo@?$B@H@@2VA@@A@YAXXZ"
 // CHECK: call x86_thiscallcc void @"\01??1A@@QAE@XZ"{{.*}}foo
diff --git a/test/CodeGenCXX/microsoft-abi-structors.cpp b/test/CodeGenCXX/microsoft-abi-structors.cpp
index 0bc4c42..93d1c24 100644
--- a/test/CodeGenCXX/microsoft-abi-structors.cpp
+++ b/test/CodeGenCXX/microsoft-abi-structors.cpp
@@ -19,7 +19,7 @@
 void no_constructor_destructor_infinite_recursion() {
   A a;
 
-// CHECK:      define linkonce_odr x86_thiscallcc %"class.basic::A"* @"\01??0A@basic@@QAE@XZ"(%"class.basic::A"* returned %this)
+// CHECK:      define linkonce_odr x86_thiscallcc %"class.basic::A"* @"\01??0A@basic@@QAE@XZ"(%"class.basic::A"* returned %this) {{.*}} comdat {{.*}} {
 // CHECK:        [[THIS_ADDR:%[.0-9A-Z_a-z]+]] = alloca %"class.basic::A"*, align 4
 // CHECK-NEXT:   store %"class.basic::A"* %this, %"class.basic::A"** [[THIS_ADDR]], align 4
 // CHECK-NEXT:   [[T1:%[.0-9A-Z_a-z]+]] = load %"class.basic::A"** [[THIS_ADDR]]
@@ -46,7 +46,7 @@
 
 struct C {
   virtual ~C() {
-// DTORS:      define linkonce_odr x86_thiscallcc i8* @"\01??_GC@basic@@UAEPAXI@Z"(%"struct.basic::C"* %this, i32 %should_call_delete)
+// DTORS:      define linkonce_odr x86_thiscallcc i8* @"\01??_GC@basic@@UAEPAXI@Z"(%"struct.basic::C"* %this, i32 %should_call_delete) {{.*}} comdat {{.*}} {
 // DTORS:        store i32 %should_call_delete, i32* %[[SHOULD_DELETE_VAR:[0-9a-z._]+]], align 4
 // DTORS:        store i8* %{{.*}}, i8** %[[RETVAL:[0-9a-z._]+]]
 // DTORS:        %[[SHOULD_DELETE_VALUE:[0-9a-z._]+]] = load i32* %[[SHOULD_DELETE_VAR]]
@@ -75,8 +75,8 @@
 void check_vftable_offset() {
   C c;
 // The vftable pointer should point at the beginning of the vftable.
-// CHECK: [[THIS_PTR:%[0-9]+]] = bitcast %"struct.basic::C"* {{.*}} to [2 x i8*]**
-// CHECK: store [2 x i8*]* @"\01??_7C@basic@@6B@", [2 x i8*]** [[THIS_PTR]]
+// CHECK: [[THIS_PTR:%[0-9]+]] = bitcast %"struct.basic::C"* {{.*}} to i32 (...)***
+// CHECK: store i32 (...)** bitcast ([2 x i8*]* @"\01??_7C@basic@@6B@" to i32 (...)**), i32 (...)*** [[THIS_PTR]]
 }
 
 void call_complete_dtor(C *obj_ptr) {
@@ -206,7 +206,7 @@
 void foo() {
   F f;
 }
-// DTORS3-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_DF@test2@@UAE@XZ"
+// DTORS3-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_DF@test2@@UAE@XZ"({{.*}} {{.*}} comdat
 //      Do an adjustment from C* to F*.
 // DTORS3:   getelementptr i8* %{{.*}}, i32 20
 // DTORS3:   bitcast i8* %{{.*}} to %"struct.test2::F"*
@@ -365,7 +365,7 @@
 }
 
 // The complete dtor should call the base dtors for D and the vbase A (once).
-// CHECK: define linkonce_odr x86_thiscallcc void @"\01??_DD@dtors@@QAE@XZ"
+// CHECK: define linkonce_odr x86_thiscallcc void @"\01??_DD@dtors@@QAE@XZ"({{.*}}) {{.*}} comdat
 // CHECK-NOT: call
 // CHECK: call x86_thiscallcc void @"\01??1D@dtors@@QAE@XZ"
 // CHECK-NOT: call
diff --git a/test/CodeGenCXX/microsoft-abi-thunks.cpp b/test/CodeGenCXX/microsoft-abi-thunks.cpp
index 843bc89..5ca04fe 100644
--- a/test/CodeGenCXX/microsoft-abi-thunks.cpp
+++ b/test/CodeGenCXX/microsoft-abi-thunks.cpp
@@ -31,12 +31,12 @@
   C();
 
   virtual ~C();
-  // MANGLING-DAG: @"\01??1C@@UAE@XZ"
-  // MANGLING-DAG: @"\01??_GC@@UAEPAXI@Z"
-  // MANGLING-DAG: @"\01??_EC@@W3AEPAXI@Z"
-  // MANGLING-X64-DAG: @"\01??1C@@UEAA@XZ"
-  // MANGLING-X64-DAG: @"\01??_GC@@UEAAPEAXI@Z"
-  // MANGLING-X64-DAG: @"\01??_EC@@W7EAAPEAXI@Z"
+  // MANGLING-DAG: declare {{.*}} @"\01??1C@@UAE@XZ"({{.*}})
+  // MANGLING-DAG: define {{.*}} @"\01??_GC@@UAEPAXI@Z"({{.*}})
+  // MANGLING-DAG: define {{.*}} @"\01??_EC@@W3AEPAXI@Z"({{.*}}) {{.*}} comdat
+  // MANGLING-X64-DAG: declare {{.*}} @"\01??1C@@UEAA@XZ"({{.*}})
+  // MANGLING-X64-DAG: define {{.*}} @"\01??_GC@@UEAAPEAXI@Z"({{.*}})
+  // MANGLING-X64-DAG: define {{.*}} @"\01??_EC@@W7EAAPEAXI@Z"({{.*}}) {{.*}} comdat
 
   // Overrides public_f() of two subobjects with distinct vfptrs, thus needs a thunk.
   virtual void public_f();
@@ -61,7 +61,7 @@
 
 C::C() {}  // Emits vftable and forces thunk generation.
 
-// CODEGEN-LABEL: define linkonce_odr x86_thiscallcc i8* @"\01??_EC@@W3AEPAXI@Z"(%struct.C* %this, i32 %should_call_delete)
+// CODEGEN-LABEL: define linkonce_odr x86_thiscallcc i8* @"\01??_EC@@W3AEPAXI@Z"(%struct.C* %this, i32 %should_call_delete) {{.*}} comdat
 // CODEGEN:   getelementptr i8* {{.*}}, i32 -4
 // FIXME: should actually call _EC, not _GC.
 // CODEGEN:   call x86_thiscallcc i8* @"\01??_GC@@UAEPAXI@Z"
diff --git a/test/CodeGenCXX/microsoft-abi-try-throw.cpp b/test/CodeGenCXX/microsoft-abi-try-throw.cpp
index 95c2cbd..6b83307 100644
--- a/test/CodeGenCXX/microsoft-abi-try-throw.cpp
+++ b/test/CodeGenCXX/microsoft-abi-try-throw.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -emit-llvm-only %s -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -verify -DTRY
-// RUN: %clang_cc1 -emit-llvm-only %s -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -verify -DTHROW
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW
 
 void external();
 
@@ -10,14 +10,17 @@
 int main() {
   int rv = 0;
 #ifdef TRY
-  try { // expected-error {{cannot compile this try statement yet}}
-    external();
+  try {
+    external(); // TRY: invoke void @"\01?external@@YAXXZ"
   } catch (int) {
     rv = 1;
+    // TRY: call i8* @llvm.eh.begincatch
+    // TRY: call void @llvm.eh.endcatch
   }
 #endif
 #ifdef THROW
-  throw int(42); // expected-error {{cannot compile this throw expression yet}}
+  // THROW: call void @"\01?terminate@@YAXXZ"
+  throw int(42);
 #endif
   return rv;
 }
diff --git a/test/CodeGenCXX/microsoft-abi-vftables.cpp b/test/CodeGenCXX/microsoft-abi-vftables.cpp
index ce2ed2d..f832596 100644
--- a/test/CodeGenCXX/microsoft-abi-vftables.cpp
+++ b/test/CodeGenCXX/microsoft-abi-vftables.cpp
@@ -9,7 +9,7 @@
   virtual ~S();
 } s;
 
-// RTTI-DAG: [[VTABLE_S:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast ({{.*}} @"\01??_R4S@@6B@" to i8*), i8* bitcast ({{.*}} @"\01??_GS@@UAEPAXI@Z" to i8*)], comdat $"\01??_7S@@6B@"
+// RTTI-DAG: [[VTABLE_S:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast ({{.*}} @"\01??_R4S@@6B@" to i8*), i8* bitcast ({{.*}} @"\01??_GS@@UAEPAXI@Z" to i8*)], comdat($"\01??_7S@@6B@")
 // RTTI-DAG: @"\01??_7S@@6B@" = unnamed_addr alias getelementptr inbounds ([2 x i8*]* [[VTABLE_S]], i32 0, i32 1)
 
 // NO-RTTI-DAG: @"\01??_7S@@6B@" = linkonce_odr unnamed_addr constant [1 x i8*] [i8* bitcast ({{.*}} @"\01??_GS@@UAEPAXI@Z" to i8*)]
@@ -26,7 +26,7 @@
   virtual ~V();
 } v;
 
-// RTTI-DAG: [[VTABLE_V:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast ({{.*}} @"\01??_R4V@@6B@" to i8*), i8* bitcast ({{.*}} @"\01??_GV@@UAEPAXI@Z" to i8*)], comdat $"\01??_7V@@6B@"
+// RTTI-DAG: [[VTABLE_V:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast ({{.*}} @"\01??_R4V@@6B@" to i8*), i8* bitcast ({{.*}} @"\01??_GV@@UAEPAXI@Z" to i8*)], comdat($"\01??_7V@@6B@")
 // RTTI-DAG: @"\01??_7V@@6B@" = dllexport unnamed_addr alias getelementptr inbounds ([2 x i8*]* [[VTABLE_V]], i32 0, i32 1)
 
 // NO-RTTI-DAG: @"\01??_7V@@6B@" = weak_odr dllexport unnamed_addr constant [1 x i8*] [i8* bitcast ({{.*}} @"\01??_GV@@UAEPAXI@Z" to i8*)]
@@ -36,7 +36,7 @@
   virtual ~W();
 } w;
 }
-// RTTI-DAG: [[VTABLE_W:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast ({{.*}} @"\01??_R4W@?A@@6B@" to i8*), i8* bitcast ({{.*}} @"\01??_GW@?A@@UAEPAXI@Z" to i8*)], comdat $"\01??_7W@?A@@6B@"
-// RTTI-DAG: @"\01??_7W@?A@@6B@" = internal unnamed_addr alias getelementptr inbounds ([2 x i8*]* @1, i32 0, i32 1)
+// RTTI-DAG: [[VTABLE_W:@.*]] = private unnamed_addr constant [2 x i8*] [i8* bitcast ({{.*}} @"\01??_R4W@?A@@6B@" to i8*), i8* bitcast ({{.*}} @"\01??_GW@?A@@UAEPAXI@Z" to i8*)], comdat($"\01??_7W@?A@@6B@")
+// RTTI-DAG: @"\01??_7W@?A@@6B@" = internal unnamed_addr alias getelementptr inbounds ([2 x i8*]* @2, i32 0, i32 1)
 
 // NO-RTTI-DAG: @"\01??_7W@?A@@6B@" = internal unnamed_addr constant [1 x i8*] [i8* bitcast ({{.*}} @"\01??_GW@?A@@UAEPAXI@Z" to i8*)]
diff --git a/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp b/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
index c851f55..7a00a73 100644
--- a/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
+++ b/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
@@ -32,8 +32,8 @@
   // ...
   // CHECK:   %[[THIS_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
   // CHECK:   %[[VFPTR_i8:.*]] = getelementptr inbounds i8* %[[THIS_i8]], i32 %{{.*}}
-  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to [3 x i8*]**
-  // CHECK:   store [3 x i8*]* @"\01??_7B@@6B@", [3 x i8*]** %[[VFPTR]]
+  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to i32 (...)***
+  // CHECK:   store i32 (...)** bitcast ([3 x i8*]* @"\01??_7B@@6B@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
 
   // Initialize vtorDisp:
   // CHECK:   %[[THIS_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
@@ -65,8 +65,8 @@
   // ...
   // CHECK:   %[[THIS_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
   // CHECK:   %[[VFPTR_i8:.*]] = getelementptr inbounds i8* %[[THIS_i8]], i32 %{{.*}}
-  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to [3 x i8*]**
-  // CHECK:   store [3 x i8*]* @"\01??_7B@@6B@", [3 x i8*]** %[[VFPTR]]
+  // CHECK:   %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to i32 (...)***
+  // CHECK:   store i32 (...)** bitcast ([3 x i8*]* @"\01??_7B@@6B@" to i32 (...)**), i32 (...)*** %[[VFPTR]]
 
   // Initialize vtorDisp:
   // CHECK:   %[[THIS_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
@@ -245,9 +245,9 @@
 D::D() {
   // CHECK-LABEL: define x86_thiscallcc %"struct.multiple_vbases::D"* @"\01??0D@multiple_vbases@@QAE@XZ"
   // Just make sure we emit 3 vtordisps after initializing vfptrs.
-  // CHECK: store [1 x i8*]* @"\01??_7D@multiple_vbases@@6BA@1@@", [1 x i8*]** %{{.*}}
-  // CHECK: store [1 x i8*]* @"\01??_7D@multiple_vbases@@6BB@1@@", [1 x i8*]** %{{.*}}
-  // CHECK: store [1 x i8*]* @"\01??_7D@multiple_vbases@@6BC@1@@", [1 x i8*]** %{{.*}}
+  // CHECK: store i32 (...)** bitcast ([1 x i8*]* @"\01??_7D@multiple_vbases@@6BA@1@@" to i32 (...)**), i32 (...)*** %{{.*}}
+  // CHECK: store i32 (...)** bitcast ([1 x i8*]* @"\01??_7D@multiple_vbases@@6BB@1@@" to i32 (...)**), i32 (...)*** %{{.*}}
+  // CHECK: store i32 (...)** bitcast ([1 x i8*]* @"\01??_7D@multiple_vbases@@6BC@1@@" to i32 (...)**), i32 (...)*** %{{.*}}
   // ...
   // CHECK: store i32 %{{.*}}, i32* %{{.*}}
   // CHECK: store i32 %{{.*}}, i32* %{{.*}}
@@ -396,8 +396,8 @@
   // In this case "this" points to the most derived class, so no GEPs needed.
   // CHECK-NOT: getelementptr
   // CHECK-NOT: bitcast
-  // CHECK: %[[VFPTR_i8:.*]] = bitcast %"struct.test4::C"* %{{.*}} to [1 x i8*]**
-  // CHECK: store [1 x i8*]* @"\01??_7C@test4@@6BB@1@@", [1 x i8*]** %[[VFPTR_i8]]
+  // CHECK: %[[VFPTR_i8:.*]] = bitcast %"struct.test4::C"* %{{.*}} to i32 (...)***
+  // CHECK: store i32 (...)** bitcast ([1 x i8*]* @"\01??_7C@test4@@6BB@1@@" to i32 (...)**), i32 (...)*** %[[VFPTR_i8]]
 
   foo(this);
   // CHECK: ret
@@ -431,8 +431,8 @@
   // In this case "this" points to the most derived class, so no GEPs needed.
   // CHECK-NOT: getelementptr
   // CHECK-NOT: bitcast
-  // CHECK: %[[VFPTR_i8:.*]] = bitcast %"struct.test4::E"* %{{.*}} to [1 x i8*]**
-  // CHECK: store [1 x i8*]* @"\01??_7E@test4@@6BD@1@@", [1 x i8*]** %[[VFPTR_i8]]
+  // CHECK: %[[VFPTR_i8:.*]] = bitcast %"struct.test4::E"* %{{.*}} to i32 (...)***
+  // CHECK: store i32 (...)** bitcast ([1 x i8*]* @"\01??_7E@test4@@6BD@1@@" to i32 (...)**), i32 (...)*** %[[VFPTR_i8]]
   foo(this);
 }
 
diff --git a/test/CodeGenCXX/microsoft-abi-virtual-member-pointers.cpp b/test/CodeGenCXX/microsoft-abi-virtual-member-pointers.cpp
index b5db7c7..8f1ff36 100644
--- a/test/CodeGenCXX/microsoft-abi-virtual-member-pointers.cpp
+++ b/test/CodeGenCXX/microsoft-abi-virtual-member-pointers.cpp
@@ -62,7 +62,9 @@
 
 // Thunk for calling the 1st virtual function in C with no parameters.
 // CHECK32-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@@$BA@AE"(%struct.C* %this, ...)
+// CHECK32: #[[ATTR:[0-9]+]]
 // CHECK32-NOT:             unnamed_addr
+// CHECK32:                 comdat
 // CHECK32: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 0
 // CHECK32: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK32: musttail call x86_thiscallcc void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
@@ -70,7 +72,9 @@
 // CHECK32: }
 //
 // CHECK64-LABEL: define linkonce_odr void @"\01??_9C@@$BA@AA"(%struct.C* %this, ...)
+// CHECK64: #[[ATTR:[0-9]+]]
 // CHECK64-NOT:             unnamed_addr
+// CHECK64:                 comdat
 // CHECK64: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 0
 // CHECK64: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK64: musttail call void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
@@ -79,6 +83,7 @@
 
 // Thunk for calling the 2nd virtual function in C, taking int and double as parameters, returning int.
 // CHECK32-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@@$B3AE"(%struct.C* %this, ...)
+// CHECK32: #[[ATTR]] comdat
 // CHECK32: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 1
 // CHECK32: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK32: musttail call x86_thiscallcc void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
@@ -86,6 +91,7 @@
 // CHECK32: }
 //
 // CHECK64-LABEL: define linkonce_odr void @"\01??_9C@@$B7AA"(%struct.C* %this, ...)
+// CHECK64: #[[ATTR]] comdat
 // CHECK64: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 1
 // CHECK64: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK64: musttail call void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
@@ -94,6 +100,7 @@
 
 // Thunk for calling the 3rd virtual function in C, taking an int parameter, returning a struct.
 // CHECK32-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@@$B7AE"(%struct.C* %this, ...)
+// CHECK32: #[[ATTR]] comdat
 // CHECK32: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 2
 // CHECK32: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK32: musttail call x86_thiscallcc void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
@@ -101,6 +108,7 @@
 // CHECK32: }
 //
 // CHECK64-LABEL: define linkonce_odr void @"\01??_9C@@$BBA@AA"(%struct.C* %this, ...)
+// CHECK64: #[[ATTR]] comdat
 // CHECK64: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 2
 // CHECK64: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK64: musttail call void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
@@ -109,6 +117,7 @@
 
 // Thunk for calling the virtual function in internal class D.
 // CHECK32-LABEL: define internal x86_thiscallcc void @"\01??_9D@?A@@$BA@AE"(%"struct.(anonymous namespace)::D"* %this, ...)
+// CHECK32: #[[ATTR]]
 // CHECK32: [[VPTR:%.*]] = getelementptr inbounds void (%"struct.(anonymous namespace)::D"*, ...)** %{{.*}}, i64 0
 // CHECK32: [[CALLEE:%.*]] = load void (%"struct.(anonymous namespace)::D"*, ...)** [[VPTR]]
 // CHECK32: musttail call x86_thiscallcc void (%"struct.(anonymous namespace)::D"*, ...)* [[CALLEE]](%"struct.(anonymous namespace)::D"* %{{.*}}, ...)
@@ -116,6 +125,7 @@
 // CHECK32: }
 //
 // CHECK64-LABEL: define internal void @"\01??_9D@?A@@$BA@AA"(%"struct.(anonymous namespace)::D"* %this, ...)
+// CHECK64: #[[ATTR]]
 // CHECK64: [[VPTR:%.*]] = getelementptr inbounds void (%"struct.(anonymous namespace)::D"*, ...)** %{{.*}}, i64 0
 // CHECK64: [[CALLEE:%.*]] = load void (%"struct.(anonymous namespace)::D"*, ...)** [[VPTR]]
 // CHECK64: musttail call void (%"struct.(anonymous namespace)::D"*, ...)* [[CALLEE]](%"struct.(anonymous namespace)::D"* %{{.*}}, ...)
@@ -124,16 +134,18 @@
 
 // Thunk for calling the fourth virtual function in C, taking a struct parameter
 // and returning a struct.
-// CHECK32-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@@$BM@AE"(%struct.C* %this, ...)
+// CHECK32-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@@$BM@AE"(%struct.C* %this, ...) {{.*}} comdat
 // CHECK32: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 3
 // CHECK32: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK32: musttail call x86_thiscallcc void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
 // CHECK32-NEXT: ret void
 // CHECK32: }
 //
-// CHECK64-LABEL: define linkonce_odr void @"\01??_9C@@$BBI@AA"(%struct.C* %this, ...)
+// CHECK64-LABEL: define linkonce_odr void @"\01??_9C@@$BBI@AA"(%struct.C* %this, ...) {{.*}} comdat
 // CHECK64: [[VPTR:%.*]] = getelementptr inbounds void (%struct.C*, ...)** %{{.*}}, i64 3
 // CHECK64: [[CALLEE:%.*]] = load void (%struct.C*, ...)** [[VPTR]]
 // CHECK64: musttail call void (%struct.C*, ...)* [[CALLEE]](%struct.C* %{{.*}}, ...)
 // CHECK64: ret void
 // CHECK64: }
+
+// CHECK32: #[[ATTR]] = {{{.*}}"thunk"{{.*}}}
diff --git a/test/CodeGenCXX/microsoft-abi-vmemptr-conflicts.cpp b/test/CodeGenCXX/microsoft-abi-vmemptr-conflicts.cpp
index 35ff4f3..896b768 100644
--- a/test/CodeGenCXX/microsoft-abi-vmemptr-conflicts.cpp
+++ b/test/CodeGenCXX/microsoft-abi-vmemptr-conflicts.cpp
@@ -23,7 +23,7 @@
 // CHECK: call x86_thiscallcc void bitcast (void (%"struct.num_params::C"*, ...)* @"\01??_9C@num_params@@$BA@AE" to void (%"struct.num_params::C"*, i32)*)(%"struct.num_params::C"* %{{.*}}, i32 0)
 // CHECK: call x86_thiscallcc void bitcast (void (%"struct.num_params::C"*, ...)* @"\01??_9C@num_params@@$BA@AE" to void (%"struct.num_params::C"*, i32, i32)*)(%"struct.num_params::C"* %{{.*}}, i32 0, i32 0)
 
-// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@num_params@@$BA@AE"(%"struct.num_params::C"* %this, ...)
+// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@num_params@@$BA@AE"(%"struct.num_params::C"* %this, ...) {{.*}} comdat
 // CHECK: musttail call x86_thiscallcc void (%"struct.num_params::C"*, ...)* %{{.*}}(%"struct.num_params::C"* %{{.*}}, ...)
 // CHECK-NEXT: ret void
 
@@ -45,7 +45,7 @@
 // CHECK: call x86_thiscallcc i32 bitcast (void (%"struct.i64_return::C"*, ...)* @"\01??_9C@i64_return@@$BA@AE" to i32 (%"struct.i64_return::C"*)*)(%"struct.i64_return::C"* %{{.*}})
 // CHECK: call x86_thiscallcc i64 bitcast (void (%"struct.i64_return::C"*, ...)* @"\01??_9C@i64_return@@$BA@AE" to i64 (%"struct.i64_return::C"*)*)(%"struct.i64_return::C"* %{{.*}})
 
-// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@i64_return@@$BA@AE"(%"struct.i64_return::C"* %this, ...)
+// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@i64_return@@$BA@AE"(%"struct.i64_return::C"* %this, ...) {{.*}} comdat
 // CHECK: musttail call x86_thiscallcc void (%"struct.i64_return::C"*, ...)* %{{.*}}(%"struct.i64_return::C"* %{{.*}}, ...)
 // CHECK-NEXT: ret void
 
@@ -67,7 +67,7 @@
 // CHECK: call x86_thiscallcc i32 bitcast (void (%"struct.sret::C"*, ...)* @"\01??_9C@sret@@$BA@AE" to i32 (%"struct.sret::C"*)*)(%"struct.sret::C"* %{{.*}})
 // CHECK: call x86_thiscallcc void bitcast (void (%"struct.sret::C"*, ...)* @"\01??_9C@sret@@$BA@AE" to void (%"struct.sret::C"*, %"struct.sret::Big"*)*)(%"struct.sret::C"* %{{.*}}, %"struct.sret::Big"* sret %{{.*}})
 
-// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@sret@@$BA@AE"(%"struct.sret::C"* %this, ...)
+// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01??_9C@sret@@$BA@AE"(%"struct.sret::C"* %this, ...) {{.*}} comdat
 // CHECK: musttail call x86_thiscallcc void (%"struct.sret::C"*, ...)* %{{.*}}(%"struct.sret::C"* %{{.*}}, ...)
 // CHECK-NEXT: ret void
 
@@ -96,6 +96,6 @@
 // CHECK: call void bitcast (void (%"struct.cdecl_inalloca::C"*, ...)* @"\01??_9C@cdecl_inalloca@@$BA@AE" to void (%"struct.cdecl_inalloca::C"*)*)(%"struct.cdecl_inalloca::C"* %{{.*}})
 // CHECK: call void bitcast (void (%"struct.cdecl_inalloca::C"*, ...)* @"\01??_9C@cdecl_inalloca@@$BA@AE" to void (<{ %"struct.cdecl_inalloca::C"*, %"struct.cdecl_inalloca::Big" }>*)*)(<{ %"struct.cdecl_inalloca::C"*, %"struct.cdecl_inalloca::Big" }>* inalloca %{{.*}})
 
-// CHECK-LABEL: define linkonce_odr void @"\01??_9C@cdecl_inalloca@@$BA@AE"(%"struct.cdecl_inalloca::C"* %this, ...)
+// CHECK-LABEL: define linkonce_odr void @"\01??_9C@cdecl_inalloca@@$BA@AE"(%"struct.cdecl_inalloca::C"* %this, ...) {{.*}} comdat
 // CHECK: musttail call void (%"struct.cdecl_inalloca::C"*, ...)* %{{.*}}(%"struct.cdecl_inalloca::C"* %{{.*}}, ...)
 // CHECK-NEXT: ret void
diff --git a/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp b/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp
index 957980a..d71f40a 100644
--- a/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp
+++ b/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 %s -fno-rtti -triple=i386-pc-win32 -emit-llvm -o %t.ll -fdump-vtable-layouts >%t
 // RUN: FileCheck %s < %t
-// RUN: FileCheck --check-prefix=MANGLING %s < %t.ll
+// RUN: FileCheck --check-prefix=BITCODE %s < %t.ll
 
 namespace test1 {
 struct A {
@@ -29,8 +29,8 @@
   // CHECK-LABEL: VFTable indices for 'test1::X' (1 entry).
   // CHECK-NEXT:   0 | void test1::X::g()
 
-  // MANGLING-DAG: @"\01??_7X@test1@@6BA@1@@"
-  // MANGLING-DAG: @"\01??_7X@test1@@6BB@1@@"
+  // BITCODE-DAG: @"\01??_7X@test1@@6BA@1@@"
+  // BITCODE-DAG: @"\01??_7X@test1@@6BB@1@@"
 
   virtual void g();
 } x;
@@ -71,9 +71,9 @@
   // CHECK-NEXT:   via vfptr at offset 4
   // CHECK-NEXT:   0 | void test2::X::g()
 
-  // MANGLING-DAG: @"\01??_7X@test2@@6BA@1@@"
-  // MANGLING-DAG: @"\01??_7X@test2@@6BB@1@@"
-  // MANGLING-DAG: @"\01??_7X@test2@@6BC@1@@"
+  // BITCODE-DAG: @"\01??_7X@test2@@6BA@1@@"
+  // BITCODE-DAG: @"\01??_7X@test2@@6BB@1@@"
+  // BITCODE-DAG: @"\01??_7X@test2@@6BC@1@@"
 
   virtual void g();
 } x;
@@ -138,3 +138,42 @@
 
 void build_vftable(X *obj) { obj->g(); }
 }
+
+namespace test4 {
+struct A {
+  virtual void foo();
+};
+struct B {
+  virtual int filler();
+  virtual int operator-();
+  virtual int bar();
+};
+struct C : public A, public B {
+  virtual int filler();
+  virtual int operator-();
+  virtual int bar();
+};
+
+// BITCODE-LABEL: define {{.*}}\01?ffun@test4@@YAXAAUC@1@@Z
+void ffun(C &c) {
+  // BITCODE: load
+  // BITCODE: bitcast
+  // BITCODE: bitcast
+  // BITCODE: [[THIS1:%.+]] = bitcast %"struct.test4::C"* {{.*}} to i8*
+  // BITCODE: [[THIS2:%.+]] = getelementptr inbounds i8* [[THIS1]], i32 4
+  // BITCODE-NEXT: call x86_thiscallcc {{.*}}(i8* [[THIS2]])
+  c.bar();
+}
+
+// BITCODE-LABEL: define {{.*}}\01?fop@test4@@YAXAAUC@1@@Z
+void fop(C &c) {
+  // BITCODE: load
+  // BITCODE: bitcast
+  // BITCODE: bitcast
+  // BITCODE: [[THIS1:%.+]] = bitcast %"struct.test4::C"* {{.*}} to i8*
+  // BITCODE: [[THIS2:%.+]] = getelementptr inbounds i8* [[THIS1]], i32 4
+  // BITCODE-NEXT: call x86_thiscallcc {{.*}}(i8* [[THIS2]])
+  -c;
+}
+
+}
diff --git a/test/CodeGenCXX/microsoft-interface.cpp b/test/CodeGenCXX/microsoft-interface.cpp
index c030d1d..a9fffc4 100644
--- a/test/CodeGenCXX/microsoft-interface.cpp
+++ b/test/CodeGenCXX/microsoft-interface.cpp
@@ -29,12 +29,12 @@
 // CHECK-LABEL: define linkonce_odr x86_thiscallcc i32 @_ZN1S4testEv(%struct.S* %this)
 // CHECK:   %{{[.0-9A-Z_a-z]+}} = call x86_thiscallcc i32 @_ZN1I4testEv(%__interface.I* %{{[.0-9A-Z_a-z]+}})
 
-// CHECK-LABEL: define linkonce_odr x86_thiscallcc i32 @_ZN1I4testEv(%__interface.I* %this)
-// CHECK:   ret i32 1
-
 // CHECK-LABEL: define linkonce_odr x86_thiscallcc void @_ZN1SC2Ev(%struct.S* %this)
 // CHECK:   call x86_thiscallcc void @_ZN1IC2Ev(%__interface.I* %{{[.0-9A-Z_a-z]+}})
-// CHECK:   store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1S, i64 0, i64 2), i8*** %{{[.0-9A-Z_a-z]+}}
+// CHECK:   store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1S, i64 0, i64 2) to i32 (...)**), i32 (...)*** %{{[.0-9A-Z_a-z]+}}
 
 // CHECK-LABEL: define linkonce_odr x86_thiscallcc void @_ZN1IC2Ev(%__interface.I* %this)
-// CHECK:   store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1I, i64 0, i64 2), i8*** %{{[.0-9A-Z_a-z]+}}
+// CHECK:   store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1I, i64 0, i64 2) to i32 (...)**), i32 (...)*** %{{[.0-9A-Z_a-z]+}}
+
+// CHECK-LABEL: define linkonce_odr x86_thiscallcc i32 @_ZN1I4testEv(%__interface.I* %this)
+// CHECK:   ret i32 1
diff --git a/test/CodeGenCXX/microsoft-no-rtti-data.cpp b/test/CodeGenCXX/microsoft-no-rtti-data.cpp
index fded4c9..68fdf05 100644
--- a/test/CodeGenCXX/microsoft-no-rtti-data.cpp
+++ b/test/CodeGenCXX/microsoft-no-rtti-data.cpp
@@ -2,7 +2,7 @@
 
 // vftable shouldn't have RTTI data in it.
 // CHECK-NOT: @"\01??_R4S@@6B@"
-// CHECK: @"\01??_7S@@6B@" = linkonce_odr unnamed_addr constant [1 x i8*] [i8* bitcast ({{.*}} @"\01??_GS@@UAEPAXI@Z" to i8*)]
+// CHECK: @"\01??_7S@@6B@" = linkonce_odr unnamed_addr constant [1 x i8*] [i8* bitcast ({{.*}} @"\01??_GS@@UAEPAXI@Z" to i8*)], comdat
 
 struct type_info;
 namespace std { using ::type_info; }
diff --git a/test/CodeGenCXX/microsoft-uuidof.cpp b/test/CodeGenCXX/microsoft-uuidof.cpp
index d57ca83..2ac5f1b 100644
--- a/test/CodeGenCXX/microsoft-uuidof.cpp
+++ b/test/CodeGenCXX/microsoft-uuidof.cpp
@@ -19,6 +19,7 @@
 struct __declspec(uuid("12345678-1234-1234-1234-1234567890aB")) S1 { } s1;
 struct __declspec(uuid("87654321-4321-4321-4321-ba0987654321")) S2 { };
 struct __declspec(uuid("{12345678-1234-1234-1234-1234567890ac}")) Curly;
+struct __declspec(uuid("{12345678-1234-1234-1234-1234567890ac}")) Curly;
 
 #ifdef DEFINE_GUID
 // Make sure we can properly generate code when the UUID has curly braces on it.
@@ -33,7 +34,7 @@
 #endif
 
 // First global use of __uuidof(S1) forces the creation of the global.
-// CHECK: @_GUID_12345678_1234_1234_1234_1234567890ab = linkonce_odr constant { i32, i16, i16, [8 x i8] } { i32 305419896, i16 4660, i16 4660, [8 x i8] c"\124\124Vx\90\AB" }
+// CHECK: @_GUID_12345678_1234_1234_1234_1234567890ab = linkonce_odr constant { i32, i16, i16, [8 x i8] } { i32 305419896, i16 4660, i16 4660, [8 x i8] c"\124\124Vx\90\AB" }, comdat
 // CHECK: @gr = constant %struct._GUID* bitcast ({ i32, i16, i16, [8 x i8] }* @_GUID_12345678_1234_1234_1234_1234567890ab to %struct._GUID*), align 4
 const GUID& gr = __uuidof(S1);
 
@@ -49,7 +50,7 @@
 
 // __uuidof(S2) hasn't been used globally yet, so it's emitted when it's used
 // in a function and is emitted at the end of the globals section.
-// CHECK: @_GUID_87654321_4321_4321_4321_ba0987654321 = linkonce_odr constant { i32, i16, i16, [8 x i8] } { i32 -2023406815, i16 17185, i16 17185, [8 x i8] c"C!\BA\09\87eC!" }
+// CHECK: @_GUID_87654321_4321_4321_4321_ba0987654321 = linkonce_odr constant { i32, i16, i16, [8 x i8] } { i32 -2023406815, i16 17185, i16 17185, [8 x i8] c"C!\BA\09\87eC!" }, comdat
 
 // The static initializer for thing.
 // CHECK-DEFINE-GUID: call void @llvm.memcpy.p0i8.p0i8.i32(i8* bitcast (%struct._GUID* @thing to i8*), i8* bitcast ({ i32, i16, i16, [8 x i8] }* @_GUID_12345678_1234_1234_1234_1234567890ac to i8*), i32 16, i32 4, i1 false)
diff --git a/test/CodeGenCXX/ms-integer-static-data-members-exported.cpp b/test/CodeGenCXX/ms-integer-static-data-members-exported.cpp
index 3f868f3..78bb3a2 100644
--- a/test/CodeGenCXX/ms-integer-static-data-members-exported.cpp
+++ b/test/CodeGenCXX/ms-integer-static-data-members-exported.cpp
@@ -17,6 +17,6 @@
   };
 };
 
-// CHECK: @"\01?x@S@@2FB" = weak_odr dllexport constant i16 42, align 2
-// CHECK: @"\01?y@S@@2W4Enum@@B" = weak_odr dllexport constant i32 2, align 4
+// CHECK: @"\01?x@S@@2FB" = weak_odr dllexport constant i16 42, comdat, align 2
+// CHECK: @"\01?y@S@@2W4Enum@@B" = weak_odr dllexport constant i32 2, comdat, align 4
 // CHECK-NOT: NonExported
diff --git a/test/CodeGenCXX/ms-integer-static-data-members.cpp b/test/CodeGenCXX/ms-integer-static-data-members.cpp
index b02b679..4965f73 100644
--- a/test/CodeGenCXX/ms-integer-static-data-members.cpp
+++ b/test/CodeGenCXX/ms-integer-static-data-members.cpp
@@ -26,7 +26,7 @@
 
 
 // Inline initialization.
-// CHECK-INLINE: @"\01?x@S@@2HB" = linkonce_odr constant i32 5, align 4
+// CHECK-INLINE: @"\01?x@S@@2HB" = linkonce_odr constant i32 5, comdat, align 4
 
 // Out-of-line initialization.
 // CHECK-OUTOFLINE: @"\01?x@S@@2HB" = constant i32 5, align 4
diff --git a/test/CodeGenCXX/ms-novtable.cpp b/test/CodeGenCXX/ms-novtable.cpp
new file mode 100644
index 0000000..8d54878
--- /dev/null
+++ b/test/CodeGenCXX/ms-novtable.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple i386-pc-win32 %s -emit-llvm -fms-extensions -fms-compatibility -fno-rtti -o - | FileCheck %s
+
+// CHECK-NOT: @"\01??_7C@@6B@"
+
+// CHECK-DAG: @"\01??_7A2@@6B@"
+
+// CHECK-DAG: @"\01??_7B2@@6B@"
+
+// CHECK-NOT: @"\01??_7B1@@6B@"
+
+// CHECK-NOT: @"\01??_7A1@@6B@"
+
+struct __declspec(novtable) A1 {
+  virtual void a();
+} a1;
+struct                      A2 {
+  virtual void a();
+};
+struct __declspec(novtable) B1 : virtual A1 {} b1;
+struct                      B2 : virtual A1 {} b2;
+struct __declspec(novtable) C  : virtual A2 {} c;
diff --git a/test/CodeGenCXX/ms-thread_local.cpp b/test/CodeGenCXX/ms-thread_local.cpp
index de72ea9..c29473f 100644
--- a/test/CodeGenCXX/ms-thread_local.cpp
+++ b/test/CodeGenCXX/ms-thread_local.cpp
@@ -6,8 +6,8 @@
 };
 
 // CHECK-DAG: $"\01??$a@X@@3UA@@A" = comdat any
-// CHECK-DAG: @"\01??$a@X@@3UA@@A" = linkonce_odr thread_local global %struct.A zeroinitializer, comdat $"\01??$a@X@@3UA@@A"
-// CHECK-DAG: @"\01??__E?$a@X@@YAXXZ$initializer$" = internal constant void ()* @"\01??__E?$a@X@@YAXXZ", section ".CRT$XDU", comdat $"\01??$a@X@@3UA@@A"
+// CHECK-DAG: @"\01??$a@X@@3UA@@A" = linkonce_odr thread_local global %struct.A zeroinitializer, comdat, align 1
+// CHECK-DAG: @"\01??__E?$a@X@@YAXXZ$initializer$" = internal constant void ()* @"\01??__E?$a@X@@YAXXZ", section ".CRT$XDU", comdat($"\01??$a@X@@3UA@@A")
 template <typename T>
 thread_local A a = A();
 
diff --git a/test/CodeGenCXX/ms_wide_predefined_expr.cpp b/test/CodeGenCXX/ms_wide_predefined_expr.cpp
index 3949d39..03c78d9 100644
--- a/test/CodeGenCXX/ms_wide_predefined_expr.cpp
+++ b/test/CodeGenCXX/ms_wide_predefined_expr.cpp
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 %s -fms-extensions -triple i686-pc-win32 -emit-llvm -o - | FileCheck %s
 
-// CHECK: @"\01??_C@_19DPFBEKIN@?$AAf?$AAu?$AAn?$AAc?$AA?$AA@" = linkonce_odr unnamed_addr constant [5 x i16] [i16 102, i16 117, i16 110, i16 99, i16 0], align 2
+// CHECK: @"\01??_C@_19DPFBEKIN@?$AAf?$AAu?$AAn?$AAc?$AA?$AA@" = linkonce_odr unnamed_addr constant [5 x i16] [i16 102, i16 117, i16 110, i16 99, i16 0], comdat, align 2
 
 void wprint(const wchar_t*);
 
diff --git a/test/CodeGenCXX/new.cpp b/test/CodeGenCXX/new.cpp
index 862161b..30a8c23 100644
--- a/test/CodeGenCXX/new.cpp
+++ b/test/CodeGenCXX/new.cpp
@@ -36,6 +36,10 @@
 void operator delete(void *, const std::nothrow_t &) throw();
 void operator delete[](void *, const std::nothrow_t &) throw();
 
+// Declare some other placemenet operators.
+void *operator new(size_t, void*, bool) throw();
+void *operator new[](size_t, void*, bool) throw();
+
 void t2(int* a) {
   int* b = new (a) int;
 }
@@ -191,20 +195,31 @@
 namespace test15 {
   struct A { A(); ~A(); };
 
-  // CHECK-LABEL:    define void @_ZN6test155test0EPv(
-  // CHECK:      [[P:%.*]] = load i8*
+  // CHECK-LABEL:    define void @_ZN6test156test0aEPv(
+  // CHECK:      [[P:%.*]] = load i8**
+  // CHECK-NOT:  icmp eq i8* [[P]], null
+  // CHECK-NOT:  br i1
+  // CHECK:      [[T0:%.*]] = bitcast i8* [[P]] to [[A:%.*]]*
+  // CHECK-NEXT: call void @_ZN6test151AC1Ev([[A]]* [[T0]])
+  void test0a(void *p) {
+    new (p) A();
+  }
+
+  // CHECK-LABEL:    define void @_ZN6test156test0bEPv(
+  // CHECK:      [[P0:%.*]] = load i8**
+  // CHECK:      [[P:%.*]] = call i8* @_ZnwmPvb(i64 1, i8* [[P0]]
   // CHECK-NEXT: icmp eq i8* [[P]], null
   // CHECK-NEXT: br i1
   // CHECK:      [[T0:%.*]] = bitcast i8* [[P]] to [[A:%.*]]*
   // CHECK-NEXT: call void @_ZN6test151AC1Ev([[A]]* [[T0]])
-  void test0(void *p) {
-    new (p) A();
+  void test0b(void *p) {
+    new (p, true) A();
   }
 
-  // CHECK-LABEL:    define void @_ZN6test155test1EPv(
+  // CHECK-LABEL:    define void @_ZN6test156test1aEPv(
   // CHECK:      [[P:%.*]] = load i8**
-  // CHECK-NEXT: icmp eq i8* [[P]], null
-  // CHECK-NEXT: br i1
+  // CHECK-NOT:  icmp eq i8* [[P]], null
+  // CHECK-NOT:  br i1
   // CHECK:      [[BEGIN:%.*]] = bitcast i8* [[P]] to [[A:%.*]]*
   // CHECK-NEXT: [[END:%.*]] = getelementptr inbounds [[A]]* [[BEGIN]], i64 5
   // CHECK-NEXT: br label
@@ -213,10 +228,28 @@
   // CHECK-NEXT: [[NEXT]] = getelementptr inbounds [[A]]* [[CUR]], i64 1
   // CHECK-NEXT: [[DONE:%.*]] = icmp eq [[A]]* [[NEXT]], [[END]]
   // CHECK-NEXT: br i1 [[DONE]]
-  void test1(void *p) {
+  void test1a(void *p) {
     new (p) A[5];
   }
 
+  // CHECK-LABEL:    define void @_ZN6test156test1bEPv(
+  // CHECK:      [[P0:%.*]] = load i8**
+  // CHECK:      [[P:%.*]] = call i8* @_ZnamPvb(i64 13, i8* [[P0]]
+  // CHECK-NEXT: icmp eq i8* [[P]], null
+  // CHECK-NEXT: br i1
+  // CHECK:      [[AFTER_COOKIE:%.*]] = getelementptr inbounds i8* [[P]], i64 8
+  // CHECK:      [[BEGIN:%.*]] = bitcast i8* [[AFTER_COOKIE]] to [[A:%.*]]*
+  // CHECK-NEXT: [[END:%.*]] = getelementptr inbounds [[A]]* [[BEGIN]], i64 5
+  // CHECK-NEXT: br label
+  // CHECK:      [[CUR:%.*]] = phi [[A]]* [ [[BEGIN]], {{%.*}} ], [ [[NEXT:%.*]], {{%.*}} ]
+  // CHECK-NEXT: call void @_ZN6test151AC1Ev([[A]]* [[CUR]])
+  // CHECK-NEXT: [[NEXT]] = getelementptr inbounds [[A]]* [[CUR]], i64 1
+  // CHECK-NEXT: [[DONE:%.*]] = icmp eq [[A]]* [[NEXT]], [[END]]
+  // CHECK-NEXT: br i1 [[DONE]]
+  void test1b(void *p) {
+    new (p, true) A[5];
+  }
+
   // TODO: it's okay if all these size calculations get dropped.
   // FIXME: maybe we should try to throw on overflow?
   // CHECK-LABEL:    define void @_ZN6test155test2EPvi(
@@ -224,9 +257,7 @@
   // CHECK-NEXT: [[T0:%.*]] = sext i32 [[N]] to i64
   // CHECK-NEXT: [[T1:%.*]] = icmp slt i64 [[T0]], 0
   // CHECK-NEXT: [[T2:%.*]] = select i1 [[T1]], i64 -1, i64 [[T0]]
-  // CHECK-NEXT: [[P:%.*]] = load i8*
-  // CHECK-NEXT: icmp eq i8* [[P]], null
-  // CHECK-NEXT: br i1
+  // CHECK-NEXT: [[P:%.*]] = load i8**
   // CHECK:      [[BEGIN:%.*]] = bitcast i8* [[P]] to [[A:%.*]]*
   // CHECK-NEXT: [[ISEMPTY:%.*]] = icmp eq i64 [[T0]], 0
   // CHECK-NEXT: br i1 [[ISEMPTY]],
diff --git a/test/CodeGenCXX/nrvo-noreturn.cc b/test/CodeGenCXX/nrvo-noreturn.cpp
similarity index 100%
rename from test/CodeGenCXX/nrvo-noreturn.cc
rename to test/CodeGenCXX/nrvo-noreturn.cpp
diff --git a/test/CodeGenCXX/optnone-def-decl.cpp b/test/CodeGenCXX/optnone-def-decl.cpp
new file mode 100644
index 0000000..ab6eb3f
--- /dev/null
+++ b/test/CodeGenCXX/optnone-def-decl.cpp
@@ -0,0 +1,94 @@
+// RUN: %clang_cc1 %s -triple %itanium_abi_triple -fms-extensions -emit-llvm -o - | FileCheck %s
+
+// Test optnone on both function declarations and function definitions.
+// Verify also that we don't generate invalid IR functions with
+// both alwaysinline and noinline. (optnone implies noinline and wins
+// over alwaysinline, in all cases.)
+
+// Test optnone on extern declaration only.
+extern int decl_only(int a) __attribute__((optnone));
+
+// This function should be marked 'optnone'.
+int decl_only(int a) {
+  return a + a + a + a;
+}
+
+// CHECK: define {{.*}} @_Z9decl_onlyi({{.*}}) [[OPTNONE:#[0-9]+]]
+
+// Test optnone on definition but not extern declaration.
+extern int def_only(int a);
+
+__attribute__((optnone))
+int def_only(int a) {
+  return a + a + a + a;
+}
+
+// Function def_only is a optnone function and therefore it should not be
+// inlined inside 'user_of_def_only'.
+int user_of_def_only() {
+  return def_only(5);
+}
+
+// CHECK: define {{.*}} @_Z8def_onlyi({{.*}}) [[OPTNONE]]
+// CHECK: define {{.*}} @_Z16user_of_def_onlyv() [[NORMAL:#[0-9]+]]
+
+// Test optnone on both definition and declaration.
+extern int def_and_decl(int a) __attribute__((optnone));
+
+__attribute__((optnone))
+int def_and_decl(int a) {
+  return a + a + a + a;
+}
+
+// CHECK: define {{.*}} @_Z12def_and_decli({{.*}}) [[OPTNONE]]
+
+// Check that optnone wins over always_inline.
+
+// Test optnone on definition and always_inline on declaration.
+extern int always_inline_function(int a) __attribute__((always_inline));
+
+__attribute__((optnone))
+extern int always_inline_function(int a) {
+  return a + a + a + a;
+}
+// CHECK: define {{.*}} @_Z22always_inline_functioni({{.*}}) [[OPTNONE]]
+
+int user_of_always_inline_function() {
+  return always_inline_function(4);
+}
+
+// CHECK: define {{.*}} @_Z30user_of_always_inline_functionv() [[NORMAL]]
+
+// Test optnone on declaration and always_inline on definition.
+extern int optnone_function(int a) __attribute__((optnone));
+
+__attribute__((always_inline))
+int optnone_function(int a) {
+  return a + a + a + a;
+}
+// CHECK: define {{.*}} @_Z16optnone_functioni({{.*}}) [[OPTNONE]]
+
+int user_of_optnone_function() {
+  return optnone_function(4);
+}
+
+// CHECK: define {{.*}} @_Z24user_of_optnone_functionv() [[NORMAL]]
+
+// Test the combination of optnone with forceinline (optnone wins).
+extern __forceinline int forceinline_optnone_function(int a, int b);
+
+__attribute__((optnone))
+extern int forceinline_optnone_function(int a, int b) {
+    return a + b;
+}
+
+int user_of_forceinline_optnone_function() {
+    return forceinline_optnone_function(4,5);
+}
+
+// CHECK: @_Z36user_of_forceinline_optnone_functionv() [[NORMAL]]
+// CHECK: @_Z28forceinline_optnone_functionii({{.*}}) [[OPTNONE]]
+
+// CHECK: attributes [[OPTNONE]] = { noinline nounwind optnone {{.*}} }
+// CHECK: attributes [[NORMAL]] = { nounwind {{.*}} }
+
diff --git a/test/CodeGenCXX/override-layout.cpp b/test/CodeGenCXX/override-layout.cpp
index 418c4ff..a3c4bb4 100644
--- a/test/CodeGenCXX/override-layout.cpp
+++ b/test/CodeGenCXX/override-layout.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -fdump-record-layouts-simple %s > %t.layouts
-// RUN: %clang_cc1 -fdump-record-layouts-simple %s > %t.before
-// RUN: %clang_cc1 -DPACKED= -DALIGNED16= -fdump-record-layouts-simple -foverride-record-layout=%t.layouts %s > %t.after
+// RUN: %clang_cc1 -w -fdump-record-layouts-simple %s > %t.layouts
+// RUN: %clang_cc1 -w -fdump-record-layouts-simple %s > %t.before
+// RUN: %clang_cc1 -w -DPACKED= -DALIGNED16= -fdump-record-layouts-simple -foverride-record-layout=%t.layouts %s > %t.after
 // RUN: diff -u %t.before %t.after
 // RUN: FileCheck %s < %t.after
 
diff --git a/test/CodeGenCXX/pod-member-memcpys.cpp b/test/CodeGenCXX/pod-member-memcpys.cpp
index a3ee990..3c05847 100644
--- a/test/CodeGenCXX/pod-member-memcpys.cpp
+++ b/test/CodeGenCXX/pod-member-memcpys.cpp
@@ -180,47 +180,50 @@
 #define CALL_CC(T) T callCC##T(const T& b) { return b; }
 
 CALL_CC(PackedMembers)
+// PackedMembers copy-assignment:
+// CHECK-LABEL: define linkonce_odr void @_ZN13PackedMembersC2ERKS_(%struct.PackedMembers* %this, %struct.PackedMembers* dereferenceable({{[0-9]+}}))
+// CHECK: call void @_ZN6NonPODC1ERKS_
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 1{{.*}})
+// CHECK: ret void
+
 CALL_CC(BitfieldMember2)
+// BitfieldMember2 copy-constructor:
+// CHECK-2-LABEL: define linkonce_odr void @_ZN15BitfieldMember2C2ERKS_(%struct.BitfieldMember2* %this, %struct.BitfieldMember2* dereferenceable({{[0-9]+}}))
+// CHECK-2: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4, i1 false)
+// CHECK-2: call void @_ZN6NonPODC1ERKS_
+// CHECK-2: ret void
+
 CALL_CC(BitfieldMember3)
+// BitfieldMember3 copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN15BitfieldMember3C2ERKS_(%struct.BitfieldMember3* %this, %struct.BitfieldMember3* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 8, i32 8, i1 false)
+// CHECK: ret void
+
 CALL_CC(ReferenceMember)
+// ReferenceMember copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN15ReferenceMemberC2ERKS_(%struct.ReferenceMember* %this, %struct.ReferenceMember* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 8{{.*}})
+// CHECK: call void @_ZN6NonPODC1ERKS_
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 8{{.*}})
+// CHECK: ret void
+
 CALL_CC(InnerClassMember)
+// InnerClass copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN16InnerClassMemberC2ERKS_(%struct.InnerClassMember* %this, %struct.InnerClassMember* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 32, i32 4{{.*}})
+// CHECK: call void @_ZN6NonPODC1ERKS_
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
+// CHECK: ret void
+
 CALL_CC(BitfieldMember)
+// BitfieldMember copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN14BitfieldMemberC2ERKS_(%struct.BitfieldMember* %this, %struct.BitfieldMember* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
+// CHECK: call void @_ZN6NonPODC1ERKS_
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 3, i32 1{{.*}})
+// CHECK: ret void
+
 CALL_CC(VolatileMember)
-CALL_CC(ArrayMember)
-CALL_CC(PODLikeMember)
-CALL_CC(PODMember)
-CALL_CC(Basic)
-
-// Basic copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN5BasicC2ERKS_(%struct.Basic* %this, %struct.Basic* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
-// CHECK: call void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
-// CHECK: ret void
-
-// PODMember copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN9PODMemberC2ERKS_(%struct.PODMember* %this, %struct.PODMember* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 32, i32 4{{.*}})
-// CHECK: call void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
-// CHECK: ret void
-
-// PODLikeMember copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN13PODLikeMemberC2ERKS_(%struct.PODLikeMember* %this, %struct.PODLikeMember* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 32, i32 4{{.*}})
-// CHECK: invoke void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
-// CHECK: ret void
-// CHECK: landingpad
-// CHECK: invoke void @_ZN7PODLikeD1Ev
-
-// ArrayMember copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN11ArrayMemberC2ERKS_(%struct.ArrayMember* %this, %struct.ArrayMember* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 64, i32 4{{.*}})
-// CHECK: call void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 64, i32 4{{.*}})
-// CHECK: ret void
-
 // VolatileMember copy-constructor:
 // CHECK-LABEL: define linkonce_odr void @_ZN14VolatileMemberC2ERKS_(%struct.VolatileMember* %this, %struct.VolatileMember* dereferenceable({{[0-9]+}}))
 // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
@@ -230,40 +233,36 @@
 // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
 // CHECK: ret void
 
-// BitfieldMember copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN14BitfieldMemberC2ERKS_(%struct.BitfieldMember* %this, %struct.BitfieldMember* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
+CALL_CC(ArrayMember)
+// ArrayMember copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN11ArrayMemberC2ERKS_(%struct.ArrayMember* %this, %struct.ArrayMember* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 64, i32 4{{.*}})
 // CHECK: call void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 3, i32 1{{.*}})
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 64, i32 4{{.*}})
 // CHECK: ret void
 
-// InnerClass copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN16InnerClassMemberC2ERKS_(%struct.InnerClassMember* %this, %struct.InnerClassMember* dereferenceable({{[0-9]+}}))
+CALL_CC(PODLikeMember)
+// PODLikeMember copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN13PODLikeMemberC2ERKS_(%struct.PODLikeMember* %this, %struct.PODLikeMember* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 32, i32 4{{.*}})
+// CHECK: invoke void @_ZN6NonPODC1ERKS_
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
+// CHECK: ret void
+// CHECK: landingpad
+// CHECK: invoke void @_ZN7PODLikeD1Ev
+
+CALL_CC(PODMember)
+// PODMember copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN9PODMemberC2ERKS_(%struct.PODMember* %this, %struct.PODMember* dereferenceable({{[0-9]+}}))
 // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 32, i32 4{{.*}})
 // CHECK: call void @_ZN6NonPODC1ERKS_
 // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
 // CHECK: ret void
 
-// ReferenceMember copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN15ReferenceMemberC2ERKS_(%struct.ReferenceMember* %this, %struct.ReferenceMember* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 8{{.*}})
+CALL_CC(Basic)
+// Basic copy-constructor:
+// CHECK-LABEL: define linkonce_odr void @_ZN5BasicC2ERKS_(%struct.Basic* %this, %struct.Basic* dereferenceable({{[0-9]+}}))
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
 // CHECK: call void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 8{{.*}})
-// CHECK: ret void
-
-// BitfieldMember3 copy-constructor:
-// CHECK-LABEL: define linkonce_odr void @_ZN15BitfieldMember3C2ERKS_(%struct.BitfieldMember3* %this, %struct.BitfieldMember3* dereferenceable({{[0-9]+}}))
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 8, i32 8, i1 false)
-// CHECK: ret void
-
-// BitfieldMember2 copy-constructor:
-// CHECK-2-LABEL: define linkonce_odr void @_ZN15BitfieldMember2C2ERKS_(%struct.BitfieldMember2* %this, %struct.BitfieldMember2* dereferenceable({{[0-9]+}}))
-// CHECK-2: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4, i1 false)
-// CHECK-2: call void @_ZN6NonPODC1ERKS_
-// CHECK-2: ret void
-
-// PackedMembers copy-assignment:
-// CHECK-LABEL: define linkonce_odr void @_ZN13PackedMembersC2ERKS_(%struct.PackedMembers* %this, %struct.PackedMembers* dereferenceable({{[0-9]+}}))
-// CHECK: call void @_ZN6NonPODC1ERKS_
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 1{{.*}})
+// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64({{.*}}i64 16, i32 4{{.*}})
 // CHECK: ret void
diff --git a/test/CodeGenCXX/pr12251.cpp b/test/CodeGenCXX/pr12251.cpp
index 21dadf5..5b1ef9a 100644
--- a/test/CodeGenCXX/pr12251.cpp
+++ b/test/CodeGenCXX/pr12251.cpp
@@ -136,10 +136,10 @@
 // CHECK: ret
 
 
-// CHECK: [[RANGE_i8_0_2]] = metadata !{i8 0, i8 2}
-// CHECK: [[RANGE_i32_0_32]] = metadata !{i32 0, i32 32}
-// CHECK: [[RANGE_i32_m16_16]] = metadata !{i32 -16, i32 16}
-// CHECK: [[RANGE_i32_m32_32]] = metadata !{i32 -32, i32 32}
-// CHECK: [[RANGE_i32_m1_1]] = metadata !{i32 -1, i32 1}
-// CHECK: [[RANGE_i32_m64_64]] = metadata !{i32 -64, i32 64}
-// CHECK: [[RANGE_i64_0_2pow33]] = metadata !{i64 0, i64 8589934592}
+// CHECK: [[RANGE_i8_0_2]] = !{i8 0, i8 2}
+// CHECK: [[RANGE_i32_0_32]] = !{i32 0, i32 32}
+// CHECK: [[RANGE_i32_m16_16]] = !{i32 -16, i32 16}
+// CHECK: [[RANGE_i32_m32_32]] = !{i32 -32, i32 32}
+// CHECK: [[RANGE_i32_m1_1]] = !{i32 -1, i32 1}
+// CHECK: [[RANGE_i32_m64_64]] = !{i32 -64, i32 64}
+// CHECK: [[RANGE_i64_0_2pow33]] = !{i64 0, i64 8589934592}
diff --git a/test/CodeGenCXX/pr21754.cpp b/test/CodeGenCXX/pr21754.cpp
new file mode 100644
index 0000000..61c1969
--- /dev/null
+++ b/test/CodeGenCXX/pr21754.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y -o - %s 2>&1 | FileCheck %s  --check-prefix=CHECKUND
+// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y -fdefine-sized-deallocation -o - %s 2>&1 | FileCheck %s --check-prefix=CHECKDEF
+// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++1y -fno-sized-deallocation -o - %s 2>&1 | FileCheck %s --check-prefix=CHECKNO
+// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -fsized-deallocation -o - %s 2>&1 | FileCheck %s --check-prefix=CHECKUND
+// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -fsized-deallocation -fdefine-sized-deallocation -o - %s 2>&1 | FileCheck %s --check-prefix=CHECKDEF
+// RUN: %clang -cc1 -emit-llvm -triple x86_64-unknown-unknown -std=c++11 -o - %s 2>&1 | FileCheck %s --check-prefix=CHECKNO
+
+void operator delete(void*, unsigned long) throw() __attribute__((alias("foo")));
+extern "C" void foo(void*, unsigned long) {}
+
+// CHECKUND-DAG: @_ZdlPvm = weak alias void (i8*, i64)* @foo
+// CHECKDEF-DAG: @_ZdlPvm = alias void (i8*, i64)* @foo
+// CHECKNO-DAG: @_ZdlPvm = alias void (i8*, i64)* @foo
diff --git a/test/CodeGenCXX/pr21989.cpp b/test/CodeGenCXX/pr21989.cpp
new file mode 100644
index 0000000..0b9bccb
--- /dev/null
+++ b/test/CodeGenCXX/pr21989.cpp
@@ -0,0 +1,9 @@
+// REQUIRES: asserts
+// RUN: not %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - %s 2>&1 | FileCheck %s
+
+struct {
+  void __attribute__((used)) f() {}
+};
+// CHECK: 2 errors generated.
+
+// Emit the errors, but don't assert.
diff --git a/test/CodeGenCXX/pragma-init_seg.cpp b/test/CodeGenCXX/pragma-init_seg.cpp
index 3f9ff21..cc4d018 100644
--- a/test/CodeGenCXX/pragma-init_seg.cpp
+++ b/test/CodeGenCXX/pragma-init_seg.cpp
@@ -35,24 +35,24 @@
 
 namespace selectany_init {
 int __declspec(selectany) x = f();
-// CHECK: @"\01?x@selectany_init@@3HA" = weak_odr global i32 0, comdat $"\01?x@selectany_init@@3HA", align 4
-// CHECK: @__cxx_init_fn_ptr3 = private constant void ()* @"\01??__Ex@selectany_init@@YAXXZ", section ".asdf", comdat $"\01?x@selectany_init@@3HA"
+// CHECK: @"\01?x@selectany_init@@3HA" = weak_odr global i32 0, comdat, align 4
+// CHECK: @__cxx_init_fn_ptr3 = private constant void ()* @"\01??__Ex@selectany_init@@YAXXZ", section ".asdf", comdat($"\01?x@selectany_init@@3HA")
 }
 
 namespace explicit_template_instantiation {
 template <typename T> struct A { static const int x; };
 template <typename T> const int A<T>::x = f();
 template struct A<int>;
-// CHECK: @"\01?x@?$A@H@explicit_template_instantiation@@2HB" = weak_odr global i32 0, comdat $"\01?x@?$A@H@explicit_template_instantiation@@2HB", align 4
-// CHECK: @__cxx_init_fn_ptr4 = private constant void ()* @"\01??__Ex@?$A@H@explicit_template_instantiation@@2HB@YAXXZ", section ".asdf", comdat $"\01?x@?$A@H@explicit_template_instantiation@@2HB"
+// CHECK: @"\01?x@?$A@H@explicit_template_instantiation@@2HB" = weak_odr global i32 0, comdat, align 4
+// CHECK: @__cxx_init_fn_ptr4 = private constant void ()* @"\01??__Ex@?$A@H@explicit_template_instantiation@@2HB@YAXXZ", section ".asdf", comdat($"\01?x@?$A@H@explicit_template_instantiation@@2HB")
 }
 
 namespace implicit_template_instantiation {
 template <typename T> struct A { static const int x; };
 template <typename T> const int A<T>::x = f();
 int g() { return A<int>::x; }
-// CHECK: @"\01?x@?$A@H@implicit_template_instantiation@@2HB" = linkonce_odr global i32 0, comdat $"\01?x@?$A@H@implicit_template_instantiation@@2HB", align 4
-// CHECK: @__cxx_init_fn_ptr5 = private constant void ()* @"\01??__Ex@?$A@H@implicit_template_instantiation@@2HB@YAXXZ", section ".asdf", comdat $"\01?x@?$A@H@implicit_template_instantiation@@2HB"
+// CHECK: @"\01?x@?$A@H@implicit_template_instantiation@@2HB" = linkonce_odr global i32 0, comdat, align 4
+// CHECK: @__cxx_init_fn_ptr5 = private constant void ()* @"\01??__Ex@?$A@H@implicit_template_instantiation@@2HB@YAXXZ", section ".asdf", comdat($"\01?x@?$A@H@implicit_template_instantiation@@2HB")
 }
 
 // ... and here's where we emitted user level ctors.
diff --git a/test/CodeGenCXX/predefined-expr.cpp b/test/CodeGenCXX/predefined-expr.cpp
index f901467..4c0a886 100644
--- a/test/CodeGenCXX/predefined-expr.cpp
+++ b/test/CodeGenCXX/predefined-expr.cpp
@@ -1,102 +1,102 @@
-// RUN: %clang_cc1 -std=c++11 %s -triple %itanium_abi_triple -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -fblocks %s -triple %itanium_abi_triple -emit-llvm -o - | FileCheck %s
 
-// CHECK: private unnamed_addr constant [15 x i8] c"externFunction\00"
-// CHECK: private unnamed_addr constant [26 x i8] c"void NS::externFunction()\00"
-// CHECK: private unnamed_addr constant [49 x i8] c"void functionTemplateExplicitSpecialization(int)\00"
+// CHECK-DAG: private unnamed_addr constant [15 x i8] c"externFunction\00"
+// CHECK-DAG: private unnamed_addr constant [26 x i8] c"void NS::externFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [49 x i8] c"void functionTemplateExplicitSpecialization(int)\00"
 
-// CHECK: private unnamed_addr constant [95 x i8] c"void SpecializedClassTemplate<char>::memberFunctionTemplate(T, U) const [T = char, U = double]\00"
-// CHECK: private unnamed_addr constant [85 x i8] c"void SpecializedClassTemplate<int>::memberFunctionTemplate(int, U) const [U = float]\00"
-// CHECK: private unnamed_addr constant [57 x i8] c"void NonTypeTemplateParam<42>::size() const [Count = 42]\00"
-// CHECK: private unnamed_addr constant [122 x i8] c"static void ClassWithTemplateTemplateParam<char, NS::ClassTemplate>::staticMember() [T = char, Param = NS::ClassTemplate]\00"
-// CHECK: private unnamed_addr constant [106 x i8] c"void OuterClass<int *>::MiddleClass::InnerClass<float>::memberFunction(T, U) const [T = int *, U = float]\00"
-// CHECK: private unnamed_addr constant [51 x i8] c"void functionTemplateWithCapturedStmt(T) [T = int]\00"
-// CHECK: private unnamed_addr constant [76 x i8] c"auto functionTemplateWithLambda(int)::(anonymous class)::operator()() const\00"
-// CHECK: private unnamed_addr constant [65 x i8] c"void functionTemplateWithUnnamedTemplateParameter(T) [T = float]\00"
+// CHECK-DAG: private unnamed_addr constant [95 x i8] c"void SpecializedClassTemplate<char>::memberFunctionTemplate(T, U) const [T = char, U = double]\00"
+// CHECK-DAG: private unnamed_addr constant [85 x i8] c"void SpecializedClassTemplate<int>::memberFunctionTemplate(int, U) const [U = float]\00"
+// CHECK-DAG: private unnamed_addr constant [57 x i8] c"void NonTypeTemplateParam<42>::size() const [Count = 42]\00"
+// CHECK-DAG: private unnamed_addr constant [122 x i8] c"static void ClassWithTemplateTemplateParam<char, NS::ClassTemplate>::staticMember() [T = char, Param = NS::ClassTemplate]\00"
+// CHECK-DAG: private unnamed_addr constant [106 x i8] c"void OuterClass<int *>::MiddleClass::InnerClass<float>::memberFunction(T, U) const [T = int *, U = float]\00"
+// CHECK-DAG: private unnamed_addr constant [51 x i8] c"void functionTemplateWithCapturedStmt(T) [T = int]\00"
+// CHECK-DAG: private unnamed_addr constant [76 x i8] c"auto functionTemplateWithLambda(int)::(anonymous class)::operator()() const\00"
+// CHECK-DAG: private unnamed_addr constant [65 x i8] c"void functionTemplateWithUnnamedTemplateParameter(T) [T = float]\00"
 
-// CHECK: private unnamed_addr constant [60 x i8] c"void functionTemplateExplicitSpecialization(T) [T = double]\00"
-// CHECK: private unnamed_addr constant [52 x i8] c"T *functionTemplateWithCompoundTypes(T *) [T = int]\00" 
-// CHECK: private unnamed_addr constant [54 x i8] c"T functionTemplateWithTemplateReturnType() [T = char]\00"
-// CHECK: private unnamed_addr constant [57 x i8] c"void functionTemplateWithoutParameterList() [T = double]\00"
-// CHECK: private unnamed_addr constant [62 x i8] c"void functionTemplateWithTwoParams(T, U) [T = int, U = float]\00"
+// CHECK-DAG: private unnamed_addr constant [60 x i8] c"void functionTemplateExplicitSpecialization(T) [T = double]\00"
+// CHECK-DAG: private unnamed_addr constant [52 x i8] c"T *functionTemplateWithCompoundTypes(T *) [T = int]\00" 
+// CHECK-DAG: private unnamed_addr constant [54 x i8] c"T functionTemplateWithTemplateReturnType() [T = char]\00"
+// CHECK-DAG: private unnamed_addr constant [57 x i8] c"void functionTemplateWithoutParameterList() [T = double]\00"
+// CHECK-DAG: private unnamed_addr constant [62 x i8] c"void functionTemplateWithTwoParams(T, U) [T = int, U = float]\00"
 
-// CHECK: private unnamed_addr constant [22 x i8] c"classTemplateFunction\00"
-// CHECK: private unnamed_addr constant [77 x i8] c"void NS::ClassTemplate<NS::Base *>::classTemplateFunction() [T = NS::Base *]\00"
-// CHECK: private unnamed_addr constant [63 x i8] c"void NS::ClassTemplate<int>::classTemplateFunction() [T = int]\00"
+// CHECK-DAG: private unnamed_addr constant [22 x i8] c"classTemplateFunction\00"
+// CHECK-DAG: private unnamed_addr constant [77 x i8] c"void NS::ClassTemplate<NS::Base *>::classTemplateFunction() [T = NS::Base *]\00"
+// CHECK-DAG: private unnamed_addr constant [63 x i8] c"void NS::ClassTemplate<int>::classTemplateFunction() [T = int]\00"
 
-// CHECK: private unnamed_addr constant [18 x i8] c"functionTemplate1\00"
-// CHECK: private unnamed_addr constant [53 x i8] c"void NS::Base::functionTemplate1(T) [T = NS::Base *]\00"
-// CHECK: private unnamed_addr constant [46 x i8] c"void NS::Base::functionTemplate1(T) [T = int]\00"
+// CHECK-DAG: private unnamed_addr constant [18 x i8] c"functionTemplate1\00"
+// CHECK-DAG: private unnamed_addr constant [53 x i8] c"void NS::Base::functionTemplate1(T) [T = NS::Base *]\00"
+// CHECK-DAG: private unnamed_addr constant [46 x i8] c"void NS::Base::functionTemplate1(T) [T = int]\00"
 
-// CHECK: private unnamed_addr constant [23 x i8] c"anonymousUnionFunction\00"
-// CHECK: private unnamed_addr constant [83 x i8] c"void NS::ContainerForAnonymousRecords::(anonymous union)::anonymousUnionFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [23 x i8] c"anonymousUnionFunction\00"
+// CHECK-DAG: private unnamed_addr constant [83 x i8] c"void NS::ContainerForAnonymousRecords::(anonymous union)::anonymousUnionFunction()\00"
 
-// CHECK: private unnamed_addr constant [24 x i8] c"anonymousStructFunction\00"
-// CHECK: private unnamed_addr constant [85 x i8] c"void NS::ContainerForAnonymousRecords::(anonymous struct)::anonymousStructFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [24 x i8] c"anonymousStructFunction\00"
+// CHECK-DAG: private unnamed_addr constant [85 x i8] c"void NS::ContainerForAnonymousRecords::(anonymous struct)::anonymousStructFunction()\00"
 
-// CHECK: private unnamed_addr constant [23 x i8] c"anonymousClassFunction\00"
-// CHECK: private unnamed_addr constant [83 x i8] c"void NS::ContainerForAnonymousRecords::(anonymous class)::anonymousClassFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [23 x i8] c"anonymousClassFunction\00"
+// CHECK-DAG: private unnamed_addr constant [83 x i8] c"void NS::ContainerForAnonymousRecords::(anonymous class)::anonymousClassFunction()\00"
 
-// CHECK: private unnamed_addr constant [12 x i8] c"~Destructor\00"
-// CHECK: private unnamed_addr constant [30 x i8] c"NS::Destructor::~Destructor()\00"
+// CHECK-DAG: private unnamed_addr constant [12 x i8] c"~Destructor\00"
+// CHECK-DAG: private unnamed_addr constant [30 x i8] c"NS::Destructor::~Destructor()\00"
 
-// CHECK: private unnamed_addr constant [12 x i8] c"Constructor\00"
-// CHECK: private unnamed_addr constant [41 x i8] c"NS::Constructor::Constructor(NS::Base *)\00"
-// CHECK: private unnamed_addr constant [34 x i8] c"NS::Constructor::Constructor(int)\00"
-// CHECK: private unnamed_addr constant [31 x i8] c"NS::Constructor::Constructor()\00"
+// CHECK-DAG: private unnamed_addr constant [12 x i8] c"Constructor\00"
+// CHECK-DAG: private unnamed_addr constant [41 x i8] c"NS::Constructor::Constructor(NS::Base *)\00"
+// CHECK-DAG: private unnamed_addr constant [34 x i8] c"NS::Constructor::Constructor(int)\00"
+// CHECK-DAG: private unnamed_addr constant [31 x i8] c"NS::Constructor::Constructor()\00"
 
-// CHECK: private unnamed_addr constant [16 x i8] c"virtualFunction\00"
-// CHECK: private unnamed_addr constant [44 x i8] c"virtual void NS::Derived::virtualFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [16 x i8] c"virtualFunction\00"
+// CHECK-DAG: private unnamed_addr constant [44 x i8] c"virtual void NS::Derived::virtualFunction()\00"
 
-// CHECK: private unnamed_addr constant [21 x i8] c"refQualifiedFunction\00"
-// CHECK: private unnamed_addr constant [41 x i8] c"void NS::Base::refQualifiedFunction() &&\00"
-// CHECK: private unnamed_addr constant [40 x i8] c"void NS::Base::refQualifiedFunction() &\00"
+// CHECK-DAG: private unnamed_addr constant [21 x i8] c"refQualifiedFunction\00"
+// CHECK-DAG: private unnamed_addr constant [41 x i8] c"void NS::Base::refQualifiedFunction() &&\00"
+// CHECK-DAG: private unnamed_addr constant [40 x i8] c"void NS::Base::refQualifiedFunction() &\00"
 
-// CHECK: private unnamed_addr constant [22 x i8] c"constVolatileFunction\00"
-// CHECK: private unnamed_addr constant [54 x i8] c"void NS::Base::constVolatileFunction() const volatile\00"
+// CHECK-DAG: private unnamed_addr constant [22 x i8] c"constVolatileFunction\00"
+// CHECK-DAG: private unnamed_addr constant [54 x i8] c"void NS::Base::constVolatileFunction() const volatile\00"
 
-// CHECK: private unnamed_addr constant [17 x i8] c"volatileFunction\00"
-// CHECK: private unnamed_addr constant [43 x i8] c"void NS::Base::volatileFunction() volatile\00"
+// CHECK-DAG: private unnamed_addr constant [17 x i8] c"volatileFunction\00"
+// CHECK-DAG: private unnamed_addr constant [43 x i8] c"void NS::Base::volatileFunction() volatile\00"
 
-// CHECK: private unnamed_addr constant [14 x i8] c"constFunction\00"
-// CHECK: private unnamed_addr constant [37 x i8] c"void NS::Base::constFunction() const\00"
+// CHECK-DAG: private unnamed_addr constant [14 x i8] c"constFunction\00"
+// CHECK-DAG: private unnamed_addr constant [37 x i8] c"void NS::Base::constFunction() const\00"
 
-// CHECK: private unnamed_addr constant [26 x i8] c"functionReturingTemplate2\00"
-// CHECK: private unnamed_addr constant [64 x i8] c"ClassTemplate<NS::Base *> NS::Base::functionReturingTemplate2()\00"
+// CHECK-DAG: private unnamed_addr constant [26 x i8] c"functionReturingTemplate2\00"
+// CHECK-DAG: private unnamed_addr constant [64 x i8] c"ClassTemplate<NS::Base *> NS::Base::functionReturingTemplate2()\00"
 
-// CHECK: private unnamed_addr constant [26 x i8] c"functionReturingTemplate1\00"
-// CHECK: private unnamed_addr constant [57 x i8] c"ClassTemplate<int> NS::Base::functionReturingTemplate1()\00"
+// CHECK-DAG: private unnamed_addr constant [26 x i8] c"functionReturingTemplate1\00"
+// CHECK-DAG: private unnamed_addr constant [57 x i8] c"ClassTemplate<int> NS::Base::functionReturingTemplate1()\00"
 
-// CHECK: private unnamed_addr constant [23 x i8] c"withTemplateParameter2\00"
-// CHECK: private unnamed_addr constant [65 x i8] c"void NS::Base::withTemplateParameter2(ClassTemplate<NS::Base *>)\00"
+// CHECK-DAG: private unnamed_addr constant [23 x i8] c"withTemplateParameter2\00"
+// CHECK-DAG: private unnamed_addr constant [65 x i8] c"void NS::Base::withTemplateParameter2(ClassTemplate<NS::Base *>)\00"
 
-// CHECK: private unnamed_addr constant [23 x i8] c"withTemplateParameter1\00"
-// CHECK: private unnamed_addr constant [58 x i8] c"void NS::Base::withTemplateParameter1(ClassTemplate<int>)\00"
+// CHECK-DAG: private unnamed_addr constant [23 x i8] c"withTemplateParameter1\00"
+// CHECK-DAG: private unnamed_addr constant [58 x i8] c"void NS::Base::withTemplateParameter1(ClassTemplate<int>)\00"
 
-// CHECK: private unnamed_addr constant [23 x i8] c"functionReturningClass\00"
-// CHECK: private unnamed_addr constant [45 x i8] c"NS::Base *NS::Base::functionReturningClass()\00"
+// CHECK-DAG: private unnamed_addr constant [23 x i8] c"functionReturningClass\00"
+// CHECK-DAG: private unnamed_addr constant [45 x i8] c"NS::Base *NS::Base::functionReturningClass()\00"
 
-// CHECK: private unnamed_addr constant [23 x i8] c"functionWithParameters\00"
-// CHECK: private unnamed_addr constant [64 x i8] c"void NS::Base::functionWithParameters(int, float *, NS::Base *)\00"
+// CHECK-DAG: private unnamed_addr constant [23 x i8] c"functionWithParameters\00"
+// CHECK-DAG: private unnamed_addr constant [64 x i8] c"void NS::Base::functionWithParameters(int, float *, NS::Base *)\00"
 
-// CHECK: private unnamed_addr constant [17 x i8] c"variadicFunction\00"
-// CHECK: private unnamed_addr constant [42 x i8] c"void NS::Base::variadicFunction(int, ...)\00"
+// CHECK-DAG: private unnamed_addr constant [17 x i8] c"variadicFunction\00"
+// CHECK-DAG: private unnamed_addr constant [42 x i8] c"void NS::Base::variadicFunction(int, ...)\00"
 
-// CHECK: private unnamed_addr constant [41 x i8] c"virtual void NS::Base::virtualFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [41 x i8] c"virtual void NS::Base::virtualFunction()\00"
 
-// CHECK: private unnamed_addr constant [15 x i8] c"inlineFunction\00"
-// CHECK: private unnamed_addr constant [32 x i8] c"void NS::Base::inlineFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [15 x i8] c"inlineFunction\00"
+// CHECK-DAG: private unnamed_addr constant [32 x i8] c"void NS::Base::inlineFunction()\00"
 
-// CHECK: private unnamed_addr constant [15 x i8] c"staticFunction\00"
-// CHECK: private unnamed_addr constant [39 x i8] c"static void NS::Base::staticFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [15 x i8] c"staticFunction\00"
+// CHECK-DAG: private unnamed_addr constant [39 x i8] c"static void NS::Base::staticFunction()\00"
 
-// CHECK: private unnamed_addr constant [26 x i8] c"topLevelNamespaceFunction\00"
-// CHECK: private unnamed_addr constant [59 x i8] c"void ClassInTopLevelNamespace::topLevelNamespaceFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [26 x i8] c"topLevelNamespaceFunction\00"
+// CHECK-DAG: private unnamed_addr constant [59 x i8] c"void ClassInTopLevelNamespace::topLevelNamespaceFunction()\00"
 
-// CHECK: private unnamed_addr constant [27 x i8] c"anonymousNamespaceFunction\00"
-// CHECK: private unnamed_addr constant [84 x i8] c"void (anonymous namespace)::ClassInAnonymousNamespace::anonymousNamespaceFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [27 x i8] c"anonymousNamespaceFunction\00"
+// CHECK-DAG: private unnamed_addr constant [84 x i8] c"void (anonymous namespace)::ClassInAnonymousNamespace::anonymousNamespaceFunction()\00"
 
-// CHECK: private unnamed_addr constant [19 x i8] c"localClassFunction\00"
-// CHECK: private unnamed_addr constant [59 x i8] c"void NS::localClass(int)::LocalClass::localClassFunction()\00"
+// CHECK-DAG: private unnamed_addr constant [19 x i8] c"localClassFunction\00"
+// CHECK-DAG: private unnamed_addr constant [59 x i8] c"void NS::localClass(int)::LocalClass::localClassFunction()\00"
 
 
 
@@ -537,3 +537,33 @@
 
   return 0;
 }
+
+// rdar://19065361
+class XXX {
+  XXX();
+  ~XXX();
+};
+
+void XXLog(const char *functionName) { }
+
+typedef void (^notify_handler_t)(int token);
+
+typedef void (^dispatch_block_t)(void);
+
+void notify_register_dispatch(notify_handler_t handler);
+
+void _dispatch_once(dispatch_block_t block);
+
+XXX::XXX()
+{
+   _dispatch_once(^{ notify_register_dispatch( ^(int token) { XXLog(__FUNCTION__); }); 
+   });
+}
+// CHECK: define internal void @___ZN3XXXC2Ev_block_invoke_
+
+XXX::~XXX()
+{
+   _dispatch_once(^{ notify_register_dispatch( ^(int token) { XXLog(__FUNCTION__); }); 
+   });
+}
+// CHECK: define internal void @___ZN3XXXD2Ev_block_invoke_
diff --git a/test/CodeGenCXX/rtti-linkage.cpp b/test/CodeGenCXX/rtti-linkage.cpp
index 3b06d42..b6b72aa 100644
--- a/test/CodeGenCXX/rtti-linkage.cpp
+++ b/test/CodeGenCXX/rtti-linkage.cpp
@@ -33,12 +33,12 @@
 // CHECK-WITH-HIDDEN: @_ZTIPK2T4 = linkonce_odr hidden constant 
 // CHECK-WITH-HIDDEN: @_ZTSZ2t5vE1A = internal constant
 // CHECK-WITH-HIDDEN: @_ZTIZ2t5vE1A = internal constant
+// CHECK-WITH-HIDDEN: @_ZTSZ2t6vE1A = linkonce_odr hidden constant
+// CHECK-WITH-HIDDEN: @_ZTIZ2t6vE1A = linkonce_odr hidden constant
 // CHECK-WITH-HIDDEN: @_ZTSPZ2t7vE1A = linkonce_odr hidden constant
 // CHECK-WITH-HIDDEN: @_ZTSZ2t7vE1A = linkonce_odr hidden constant
 // CHECK-WITH-HIDDEN: @_ZTIZ2t7vE1A = linkonce_odr hidden constant
 // CHECK-WITH-HIDDEN: @_ZTIPZ2t7vE1A = linkonce_odr hidden constant
-// CHECK-WITH-HIDDEN: @_ZTSZ2t6vE1A = linkonce_odr hidden constant
-// CHECK-WITH-HIDDEN: @_ZTIZ2t6vE1A = linkonce_odr hidden constant
 
 // CHECK: _ZTSN12_GLOBAL__N_11DE = internal constant
 // CHECK: _ZTIN12_GLOBAL__N_11DE = internal constant
@@ -64,12 +64,12 @@
 // CHECK: _ZTS1B = constant
 // CHECK: _ZTI1B = constant
 // CHECK: _ZTS1F = linkonce_odr constant
+// CHECK: _ZTSZ2t6vE1A = linkonce_odr constant
+// CHECK: _ZTIZ2t6vE1A = linkonce_odr constant
 // CHECK: _ZTSPZ2t7vE1A = linkonce_odr constant
 // CHECK: _ZTSZ2t7vE1A = linkonce_odr constant
 // CHECK: _ZTIZ2t7vE1A = linkonce_odr constant
 // CHECK: _ZTIPZ2t7vE1A = linkonce_odr constant
-// CHECK: _ZTSZ2t6vE1A = linkonce_odr constant
-// CHECK: _ZTIZ2t6vE1A = linkonce_odr constant
 
 // CHECK: _ZTIN12_GLOBAL__N_11DE to
 
diff --git a/test/CodeGenCXX/runtimecc.cpp b/test/CodeGenCXX/runtimecc.cpp
index 2044883..ad6dc85 100644
--- a/test/CodeGenCXX/runtimecc.cpp
+++ b/test/CodeGenCXX/runtimecc.cpp
@@ -20,33 +20,33 @@
   };
 
   A global;
-// CHECK-LABEL:    define internal arm_aapcscc void @__cxx_global_var_init()
-// CHECK:      call arm_aapcscc [[A]]* @_ZN5test01AC1Ev([[A]]* @_ZN5test06globalE)
-// CHECK-NEXT: call arm_aapcscc i32 @__cxa_atexit(void (i8*)* bitcast ([[A]]* ([[A]]*)* @_ZN5test01AD1Ev to void (i8*)*), i8* bitcast ([[A]]* @_ZN5test06globalE to i8*), i8* @__dso_handle) [[NOUNWIND:#[0-9]+]]
+// CHECK-LABEL:    define internal void @__cxx_global_var_init()
+// CHECK:      call [[A]]* @_ZN5test01AC1Ev([[A]]* @_ZN5test06globalE)
+// CHECK-NEXT: call i32 @__cxa_atexit(void (i8*)* bitcast ([[A]]* ([[A]]*)* @_ZN5test01AD1Ev to void (i8*)*), i8* bitcast ([[A]]* @_ZN5test06globalE to i8*), i8* @__dso_handle) [[NOUNWIND:#[0-9]+]]
 // CHECK-NEXT: ret void
 }
 
-// CHECK: declare arm_aapcscc i32 @__cxa_atexit(void (i8*)*, i8*, i8*) [[NOUNWIND]]
+// CHECK: declare i32 @__cxa_atexit(void (i8*)*, i8*, i8*) [[NOUNWIND]]
 
 namespace test1 {
   void test() {
     throw 0;
   }
 
-// CHECK-LABEL:    define arm_aapcscc void @_ZN5test14testEv()
-// CHECK:      [[T0:%.*]] = call arm_aapcscc i8* @__cxa_allocate_exception(i32 4) [[NOUNWIND]]
+// CHECK-LABEL:    define void @_ZN5test14testEv()
+// CHECK:      [[T0:%.*]] = call i8* @__cxa_allocate_exception(i32 4) [[NOUNWIND]]
 // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to i32*
 // CHECK-NEXT: store i32 0, i32* [[T1]]
-// CHECK-NEXT: call arm_aapcscc void @__cxa_throw(i8* [[T0]], i8* bitcast (i8** @_ZTIi to i8*), i8* null) [[NORETURN:#[0-9]+]]
+// CHECK-NEXT: call void @__cxa_throw(i8* [[T0]], i8* bitcast (i8** @_ZTIi to i8*), i8* null) [[NORETURN:#[0-9]+]]
 // CHECK-NEXT: unreachable
 }
 
-// CHECK: declare arm_aapcscc i8* @__cxa_allocate_exception(i32)
+// CHECK: declare i8* @__cxa_allocate_exception(i32)
 
-// CHECK: declare arm_aapcscc void @__cxa_throw(i8*, i8*, i8*)
+// CHECK: declare void @__cxa_throw(i8*, i8*, i8*)
 
-// CHECK-LABEL: define internal arm_aapcscc void @_GLOBAL__sub_I_runtimecc.cpp()
-// CHECK:   call arm_aapcscc void @__cxx_global_var_init()
+// CHECK-LABEL: define internal void @_GLOBAL__sub_I_runtimecc.cpp()
+// CHECK:   call void @__cxx_global_var_init()
 
 
 // CHECK: attributes [[NOUNWIND]] = { nounwind }
diff --git a/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp b/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
index 29926b9..6b50075 100644
--- a/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
+++ b/test/CodeGenCXX/skip-vtable-pointer-initialization.cpp
@@ -11,7 +11,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test11AD2Ev
-// CHECK-NOT: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test11AE, i64 0, i64 2), i8***
+// CHECK-NOT: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test11AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A() 
 {
 }
@@ -27,7 +27,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test21AD2Ev
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test21AE, i64 0, i64 2), i8***
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test21AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A() {
   f();
 }
@@ -50,7 +50,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test31AD2Ev
-// CHECK-NOT: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test31AE, i64 0, i64 2), i8***
+// CHECK-NOT: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test31AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A() {
   
 }
@@ -76,7 +76,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test41AD2Ev
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test41AE, i64 0, i64 2), i8***
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test41AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A()
 {
 }
@@ -100,7 +100,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test51AD2Ev
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test51AE, i64 0, i64 2), i8***
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test51AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A()
 {
 }
@@ -128,7 +128,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test61AD2Ev
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test61AE, i64 0, i64 2), i8***
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test61AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A()
 {
 }
@@ -154,7 +154,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test71AD2Ev
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test71AE, i64 0, i64 2), i8***
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test71AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A()
 {
 }
@@ -180,7 +180,7 @@
 };
 
 // CHECK-LABEL: define void @_ZN5Test81AD2Ev
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test81AE, i64 0, i64 2), i8***
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTVN5Test81AE, i64 0, i64 2) to i32 (...)**), i32 (...)***
 A::~A()
 {
 }
diff --git a/test/CodeGenCXX/split-stacks.cpp b/test/CodeGenCXX/split-stacks.cpp
index 3e12034..76e1b79 100644
--- a/test/CodeGenCXX/split-stacks.cpp
+++ b/test/CodeGenCXX/split-stacks.cpp
@@ -18,7 +18,7 @@
 
 // CHECK-SEGSTK: define i32 @_Z3foov() [[SS:#[0-9]+]] {
 // CHECK-SEGSTK: define i32 @_Z7nosplitv() [[NSS1:#[0-9]+]] {
-// CHECK-SEGSTK: define linkonce_odr i32 @_Z8tnosplitIiEiv() [[NSS2:#[0-9]+]] {
+// CHECK-SEGSTK: define linkonce_odr i32 @_Z8tnosplitIiEiv() [[NSS2:#[0-9]+]] comdat {
 // CHECK-SEGSTK-NOT: [[NSS1]] = { {{.*}} "split-stack" {{.*}} }
 // CHECK-SEGSTK-NOT: [[NSS2]] = { {{.*}} "split-stack" {{.*}} }
 // CHECK-SEGSTK: [[SS]] = { {{.*}} "split-stack" {{.*}} }
@@ -27,7 +27,7 @@
 
 // CHECK-NOSEGSTK: define i32 @_Z3foov() [[NSS0:#[0-9]+]] {
 // CHECK-NOSEGSTK: define i32 @_Z7nosplitv() [[NSS1:#[0-9]+]] {
-// CHECK-NOSEGSTK: define linkonce_odr i32 @_Z8tnosplitIiEiv() [[NSS2:#[0-9]+]] {
+// CHECK-NOSEGSTK: define linkonce_odr i32 @_Z8tnosplitIiEiv() [[NSS2:#[0-9]+]] comdat {
 // CHECK-NOSEGSTK-NOT: [[NSS1]] = { {{.*}} "split-stack" {{.*}} }
 // CHECK-NOSEGSTK-NOT: [[NSS2]] = { {{.*}} "split-stack" {{.*}} }
 // CHECK-NOSEGSTK-NOT: [[NSS3]] = { {{.*}} "split-stack" {{.*}} }
diff --git a/test/CodeGenCXX/static-data-member.cpp b/test/CodeGenCXX/static-data-member.cpp
index 5ec3755..d41ac8f 100644
--- a/test/CodeGenCXX/static-data-member.cpp
+++ b/test/CodeGenCXX/static-data-member.cpp
@@ -4,8 +4,8 @@
 
 // CHECK: @_ZN5test11A1aE = constant i32 10, align 4
 // CHECK: @_ZN5test212_GLOBAL__N_11AIiE1xE = internal global i32 0, align 4
-// CHECK: @_ZN5test31AIiE1xE = weak_odr global i32 0, comdat $_ZN5test31AIiE1xE, align 4
-// CHECK: @_ZGVN5test31AIiE1xE = weak_odr global i64 0, comdat $_ZN5test31AIiE1xE
+// CHECK: @_ZN5test31AIiE1xE = weak_odr global i32 0, comdat, align 4
+// CHECK: @_ZGVN5test31AIiE1xE = weak_odr global i64 0, comdat($_ZN5test31AIiE1xE)
 // MACHO: @_ZGVN5test31AIiE1xE = weak_odr global i64 0
 // MACHO-NOT: comdat
 
@@ -64,7 +64,7 @@
   template <class T> int A<T>::x = foo();
   template struct A<int>;
 
-  // CHECK-LABEL: define internal void @__cxx_global_var_init1() {{.*}} comdat $_ZN5test31AIiE1xE
+  // CHECK-LABEL: define internal void @__cxx_global_var_init1() {{.*}} comdat($_ZN5test31AIiE1xE)
   // MACHO-LABEL: define internal void @__cxx_global_var_init1()
   // MACHO-NOT: comdat
   // CHECK:      [[GUARDBYTE:%.*]] = load i8* bitcast (i64* @_ZGVN5test31AIiE1xE to i8*)
diff --git a/test/CodeGenCXX/static-init.cpp b/test/CodeGenCXX/static-init.cpp
index a9debe3..acac84d 100644
--- a/test/CodeGenCXX/static-init.cpp
+++ b/test/CodeGenCXX/static-init.cpp
@@ -5,12 +5,10 @@
 // CHECK: @base_req_uchar = global [4 x i8] c"bar\00", align 1
 
 // CHECK: @_ZZN5test31BC1EvE1u = internal global { i8, [3 x i8] } { i8 97, [3 x i8] undef }, align 4
-// CHECK: @_ZZN5test1L6getvarEiE3var = internal constant [4 x i32] [i32 1, i32 0, i32 2, i32 4], align 16
 
-// CHECK: @_ZZ2h2vE1i = linkonce_odr global i32 0
-// CHECK-NOT: comdat
-// CHECK: @_ZGVZ2h2vE1i = linkonce_odr global i64 0
-// CHECK-NOT: comdat
+// CHECK: @_ZZ2h2vE1i = linkonce_odr global i32 0, comdat, align
+// CHECK: @_ZGVZ2h2vE1i = linkonce_odr global i64 0, comdat{{$}}
+// CHECK: @_ZZN5test1L6getvarEiE3var = internal constant [4 x i32] [i32 1, i32 0, i32 2, i32 4], align 16
 
 struct A {
   A();
@@ -37,8 +35,7 @@
   static const int i = a();
 }
 
-// CHECK: define linkonce_odr void @_Z2h2v()
-// CHECK-NOT: comdat
+// CHECK: define linkonce_odr void @_Z2h2v() {{.*}} comdat {
 inline void h2() {
   static int i = a();
 }
diff --git a/test/CodeGenCXX/static-local-in-local-class.cpp b/test/CodeGenCXX/static-local-in-local-class.cpp
index 729b937..9c13ff1 100644
--- a/test/CodeGenCXX/static-local-in-local-class.cpp
+++ b/test/CodeGenCXX/static-local-in-local-class.cpp
@@ -1,11 +1,11 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fblocks -emit-llvm -o - %s -std=c++1y | FileCheck %s
 
-// CHECK: @"_ZZNK3$_2clEvE1x" = internal global i32 42
-// CHECK: @_ZZ18static_local_labelPvE1q = linkonce_odr global i8* blockaddress(@_Z18static_local_labelPv, %{{.*}})
-// CHECK: @_ZZZL20block_deduced_returnvEUb_E1n = internal global i32 42
-// CHECK: @_ZZL14deduced_returnvE1n = internal global i32 42
 // CHECK: @"_ZZZNK17pr18020_constexpr3$_1clEvENKUlvE_clEvE2l2" =
 // CHECK: internal global i32* @"_ZZNK17pr18020_constexpr3$_1clEvE2l1"
+// CHECK: @_ZZL14deduced_returnvE1n = internal global i32 42
+// CHECK: @_ZZZL20block_deduced_returnvEUb_E1n = internal global i32 42
+// CHECK: @_ZZ18static_local_labelPvE1q = linkonce_odr global i8* blockaddress(@_Z18static_local_labelPv, %{{.*}})
+// CHECK: @"_ZZNK3$_2clEvE1x" = internal global i32 42
 
 namespace pr6769 {
 struct X {
diff --git a/test/CodeGenCXX/static-member-variable-explicit-specialization.cpp b/test/CodeGenCXX/static-member-variable-explicit-specialization.cpp
index 430fa2b..20b409c 100644
--- a/test/CodeGenCXX/static-member-variable-explicit-specialization.cpp
+++ b/test/CodeGenCXX/static-member-variable-explicit-specialization.cpp
@@ -76,37 +76,37 @@
 }
 int *use_internal_a = &Internal<int>::a;
 
-// ALL: define internal void @[[unordered1]]
+// ALL: define internal void @[[unordered1]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_ZN1AIsE1aE
 // ALL: ret
 
-// ALL: define internal void @[[unordered2]]
+// ALL: define internal void @[[unordered2]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_Z1xIsE
 // ALL: ret
 
-// ALL: define internal void @[[unordered3]]
+// ALL: define internal void @[[unordered3]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_ZN2ns1aIiE1iE
 // ALL: ret
 
-// ALL: define internal void @[[unordered4]]
+// ALL: define internal void @[[unordered4]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_ZN2ns1b1iIiEE
 // ALL: ret
 
-// ALL: define internal void @[[unordered5]]
+// ALL: define internal void @[[unordered5]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_ZN1AIvE1aE
 // ALL: ret
 
-// ALL: define internal void @[[unordered6]]
+// ALL: define internal void @[[unordered6]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_Z1xIcE
 // ALL: ret
 
-// ALL: define internal void @[[unordered7]]
+// ALL: define internal void @[[unordered7]](
 // ALL: call i32 @foo()
 // ALL: store {{.*}} @_ZN12_GLOBAL__N_18InternalIiE1aE
 // ALL: ret
diff --git a/test/CodeGenCXX/template-anonymous-types.cpp b/test/CodeGenCXX/template-anonymous-types.cpp
index f4d6549..63685ef 100644
--- a/test/CodeGenCXX/template-anonymous-types.cpp
+++ b/test/CodeGenCXX/template-anonymous-types.cpp
@@ -24,14 +24,13 @@
   // CHECK-LABEL: define linkonce_odr i32 @_Z1fIN1SUt0_EEiT_(i32 %t)
   (void)f(S::BAR);
 
-  // Now check for the class template instantiations. Annoyingly, they are in
-  // reverse order.
+  // Now check for the class template instantiations.
   //
   // BAR's instantiation of X:
-  // CHECK-LABEL: define linkonce_odr i32 @_ZN1XIN1SUt0_EE1fEv(%struct.X* %this)
-  // CHECK-LABEL: define linkonce_odr void @_ZN1XIN1SUt0_EEC2ES1_(%struct.X* %this, i32 %t) unnamed_addr
+  // CHECK-LABEL: define linkonce_odr i32 @_ZN1XIN1SUt_EE1fEv(%struct.X* %this)
+  // CHECK-LABEL: define linkonce_odr void @_ZN1XIN1SUt_EEC2ES1_(%struct.X* %this, i32 %t) unnamed_addr
   //
   // FOO's instantiation of X:
-  // CHECK-LABEL: define linkonce_odr i32 @_ZN1XIN1SUt_EE1fEv(%struct.X.0* %this)
-  // CHECK-LABEL: define linkonce_odr void @_ZN1XIN1SUt_EEC2ES1_(%struct.X.0* %this, i32 %t) unnamed_addr
+  // CHECK-LABEL: define linkonce_odr i32 @_ZN1XIN1SUt0_EE1fEv(%struct.X.0* %this)
+  // CHECK-LABEL: define linkonce_odr void @_ZN1XIN1SUt0_EEC2ES1_(%struct.X.0* %this, i32 %t) unnamed_addr
 }
diff --git a/test/CodeGenCXX/temporaries.cpp b/test/CodeGenCXX/temporaries.cpp
index 7f5c7af..7985039 100644
--- a/test/CodeGenCXX/temporaries.cpp
+++ b/test/CodeGenCXX/temporaries.cpp
@@ -3,7 +3,7 @@
 namespace PR16263 {
   const unsigned int n = 1234;
   extern const int &r = (const int&)n;
-  // CHECK: @_ZGRN7PR162631rE_ = private constant i32 1234,
+  // CHECK: @_ZGRN7PR162631rE_ = internal constant i32 1234,
   // CHECK: @_ZN7PR162631rE = constant i32* @_ZGRN7PR162631rE_,
 
   extern const int &s = reinterpret_cast<const int&>(n);
@@ -14,16 +14,16 @@
   struct B { int n; };
   struct C : A, B {};
   extern const A &&a = (A&&)(A&&)(C&&)(C{});
-  // CHECK: @_ZGRN7PR162631aE_ = private global {{.*}} zeroinitializer,
+  // CHECK: @_ZGRN7PR162631aE_ = internal global {{.*}} zeroinitializer,
   // CHECK: @_ZN7PR162631aE = constant {{.*}} bitcast ({{.*}}* @_ZGRN7PR162631aE_ to
 
   extern const int &&t = ((B&&)C{}).n;
-  // CHECK: @_ZGRN7PR162631tE_ = private global {{.*}} zeroinitializer,
+  // CHECK: @_ZGRN7PR162631tE_ = internal global {{.*}} zeroinitializer,
   // CHECK: @_ZN7PR162631tE = constant i32* {{.*}}* @_ZGRN7PR162631tE_ {{.*}} 4
 
   struct D { double d; C c; };
   extern const int &&u = (123, static_cast<B&&>(0, ((D&&)D{}).*&D::c).n);
-  // CHECK: @_ZGRN7PR162631uE_ = private global {{.*}} zeroinitializer
+  // CHECK: @_ZGRN7PR162631uE_ = internal global {{.*}} zeroinitializer
   // CHECK: @_ZN7PR162631uE = constant i32* {{.*}} @_ZGRN7PR162631uE_ {{.*}} 12
 }
 
@@ -33,13 +33,20 @@
   struct C : B {};
 
   A &&a = dynamic_cast<A&&>(A{});
-  // CHECK: @_ZGRN7PR202271aE_ = private global
+  // CHECK: @_ZGRN7PR202271aE_ = internal global
 
   B &&b = dynamic_cast<C&&>(dynamic_cast<B&&>(C{}));
-  // CHECK: @_ZGRN7PR202271bE_ = private global
+  // CHECK: @_ZGRN7PR202271bE_ = internal global
 
   B &&c = static_cast<C&&>(static_cast<B&&>(C{}));
-  // CHECK: @_ZGRN7PR202271cE_ = private global
+  // CHECK: @_ZGRN7PR202271cE_ = internal global
+}
+
+namespace BraceInit {
+  typedef const int &CIR;
+  CIR x = CIR{3};
+  // CHECK: @_ZGRN9BraceInit1xE_ = internal constant i32 3
+  // CHECK: @_ZN9BraceInit1xE = constant i32* @_ZGRN9BraceInit1xE_
 }
 
 struct A {
diff --git a/test/CodeGenCXX/thunks.cpp b/test/CodeGenCXX/thunks.cpp
index 89e4db3..891667e 100644
--- a/test/CodeGenCXX/thunks.cpp
+++ b/test/CodeGenCXX/thunks.cpp
@@ -363,12 +363,12 @@
 
 /**** The following has to go at the end of the file ****/
 
+// This is from Test5:
+// CHECK-LABEL: define internal void @_ZThn8_N6Test4B12_GLOBAL__N_11C1fEv(
+// CHECK-LABEL: define linkonce_odr void @_ZTv0_n24_N5Test51B1fEv
+
 // This is from Test10:
 // CHECK-LABEL: define linkonce_odr void @_ZN6Test101C3fooEv
 // CHECK-LABEL: define linkonce_odr void @_ZThn8_N6Test101C3fooEv
 
-// This is from Test5:
-// CHECK-LABEL: define linkonce_odr void @_ZTv0_n24_N5Test51B1fEv
-// CHECK-LABEL: define internal void @_ZThn8_N6Test4B12_GLOBAL__N_11C1fEv(
-
 // CHECK: attributes [[NUW]] = { nounwind uwtable{{.*}} }
diff --git a/test/CodeGenCXX/virtual-base-destructor-call.cpp b/test/CodeGenCXX/virtual-base-destructor-call.cpp
index 3d79071..29f1f5c 100644
--- a/test/CodeGenCXX/virtual-base-destructor-call.cpp
+++ b/test/CodeGenCXX/virtual-base-destructor-call.cpp
@@ -22,11 +22,6 @@
 //  CHECK: call {{.*}} @_ZN14basic_iostreamIcED2Ev
 //  CHECK: call {{.*}} @_ZN9basic_iosD2Ev
 
-// basic_iostream's base dtor calls its non-virtual base dtor.
-//  CHECK: define linkonce_odr {{.*}} @_ZN14basic_iostreamIcED2Ev(%struct.basic_iostream* {{.*}}%this, i8** %vtt) unnamed_addr
-//  CHECK: call {{.*}} @_ZN13basic_istreamIcED2Ev
-//  CHECK: }
-
 // basic_istream's complete dtor calls the base dtor,
 // then its virtual base's base dtor.
 //  CHECK: define linkonce_odr {{.*}} @_ZN13basic_istreamIcED1Ev(%struct.basic_istream* {{.*}}%this) unnamed_addr
@@ -49,3 +44,8 @@
 //  CHECK: define linkonce_odr {{.*}} @_ZN13basic_istreamIcED2Ev(%struct.basic_istream* {{.*}}%this, i8** %vtt) unnamed_addr
 //  CHECK-NOT: call
 //  CHECK: }
+
+// basic_iostream's base dtor calls its non-virtual base dtor.
+//  CHECK: define linkonce_odr {{.*}} @_ZN14basic_iostreamIcED2Ev(%struct.basic_iostream* {{.*}}%this, i8** %vtt) unnamed_addr
+//  CHECK: call {{.*}} @_ZN13basic_istreamIcED2Ev
+//  CHECK: }
diff --git a/test/CodeGenCXX/virtual-operator-call.cpp b/test/CodeGenCXX/virtual-operator-call.cpp
index 72d49c2..727c8e1 100644
--- a/test/CodeGenCXX/virtual-operator-call.cpp
+++ b/test/CodeGenCXX/virtual-operator-call.cpp
@@ -1,10 +1,13 @@
 // RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s
 
 struct A {
-  virtual int operator-() = 0;
+  virtual int operator-();
 };
 
-void f(A *a) {
+void f(A a, A *ap) {
+  // CHECK: call i32 @_ZN1AngEv(%struct.A* %a)
+  -a;
+
   // CHECK: call i32 %
-  -*a;
+  -*ap;
 }
diff --git a/test/CodeGenCXX/visibility.cpp b/test/CodeGenCXX/visibility.cpp
index 1c4d5bb..7239cbe 100644
--- a/test/CodeGenCXX/visibility.cpp
+++ b/test/CodeGenCXX/visibility.cpp
@@ -135,17 +135,22 @@
   // CHECK-HIDDEN: _ZTVN6test271CIiE1DE = unnamed_addr constant
 }
 
-// CHECK: @_ZZN6Test193fooIiEEvvE1a = linkonce_odr global
-// CHECK: @_ZGVZN6Test193fooIiEEvvE1a = linkonce_odr global i64
-// CHECK-HIDDEN: @_ZZN6Test193fooIiEEvvE1a = linkonce_odr hidden global
-// CHECK-HIDDEN: @_ZGVZN6Test193fooIiEEvvE1a = linkonce_odr hidden global i64
-// CHECK: @_ZZN6test681fC1EvE4test = linkonce_odr global
-// CHECK: @_ZGVZN6test681fC1EvE4test = linkonce_odr global
-// CHECK-HIDDEN: @_ZZN6test681fC1EvE4test = linkonce_odr hidden global
-// CHECK-HIDDEN: @_ZGVZN6test681fC1EvE4test = linkonce_odr hidden global
+// CHECK: @_ZTVN5Test63fooE = linkonce_odr hidden unnamed_addr constant
+
 // CHECK-HIDDEN: @_ZTVN6Test161AIcEE = external unnamed_addr constant
 // CHECK-HIDDEN: @_ZTTN6Test161AIcEE = external unnamed_addr constant
-// CHECK: @_ZTVN5Test63fooE = linkonce_odr hidden unnamed_addr constant 
+
+// CHECK: @_ZZN6test681fC1EvE4test = linkonce_odr global
+// CHECK-HIDDEN: @_ZZN6test681fC1EvE4test = linkonce_odr hidden global
+
+// CHECK: @_ZGVZN6test681fC1EvE4test = linkonce_odr global
+// CHECK-HIDDEN: @_ZGVZN6test681fC1EvE4test = linkonce_odr hidden global
+
+// CHECK: @_ZZN6Test193fooIiEEvvE1a = linkonce_odr global
+// CHECK-HIDDEN: @_ZZN6Test193fooIiEEvvE1a = linkonce_odr hidden global
+
+// CHECK: @_ZGVZN6Test193fooIiEEvvE1a = linkonce_odr global i64
+// CHECK-HIDDEN: @_ZGVZN6Test193fooIiEEvvE1a = linkonce_odr hidden global i64
 
 namespace Test1 {
   // CHECK-LABEL: define hidden void @_ZN5Test11fEv
@@ -235,7 +240,7 @@
   class B : public A {};
   B b; // top of file
 
-  // CHECK-LABEL: define linkonce_odr hidden void @_ZN5Test74ArefILZNS_1aEEE3fooEv()
+  // CHECK-LABEL: define linkonce_odr hidden void @_ZN5Test74ArefIL_ZNS_1aEEE3fooEv()
   void test() {
     Aref<a>::foo();
   }
diff --git a/test/CodeGenCXX/vla-lambda-capturing.cpp b/test/CodeGenCXX/vla-lambda-capturing.cpp
index 4ad183d..1341b14 100644
--- a/test/CodeGenCXX/vla-lambda-capturing.cpp
+++ b/test/CodeGenCXX/vla-lambda-capturing.cpp
@@ -70,17 +70,17 @@
 
 // CHECK-LABEL: @main
 int main() {
-  // CHECK:       call void [[G]]([[INTPTR_T]] 1)
+  // CHECK:       call void [[G]]([[INTPTR_T]] [[INTPTR_T_ATTR:(signext )?]]1)
   g((intptr_t)1);
-  // CHECK:       call void [[F_INT:@.+]]([[INTPTR_T]] 1, [[INTPTR_T]] 2)
+  // CHECK:       call void [[F_INT:@.+]]([[INTPTR_T]] [[INTPTR_T_ATTR]]1, [[INTPTR_T]] [[INTPTR_T_ATTR]]2)
   f((intptr_t)1, (intptr_t)2);
-  // CHECK:       call void [[B_INT:@.+]]([[INTPTR_T]] 12, [[INTPTR_T]] 13)
+  // CHECK:       call void [[B_INT:@.+]]([[INTPTR_T]] [[INTPTR_T_ATTR]]12, [[INTPTR_T]] [[INTPTR_T_ATTR]]13)
   b((intptr_t)12, (intptr_t)13);
   // CHECK:       ret i32 0
   return 0;
 }
 
-// CHECK: void [[F_INT]]([[INTPTR_T]]
+// CHECK: define linkonce_odr void [[F_INT]]([[INTPTR_T]]
 // CHECK: [[SIZE:%.+]] = add
 // CHECK: call i{{.+}}* @llvm.stacksave()
 // CHECK: [[BUFFER_ADDR:%.+]] = alloca [[INTPTR_T]], [[INTPTR_T]] [[SIZE]]
@@ -111,6 +111,15 @@
 // CHECK: call void @llvm.stackrestore(
 // CHECK: ret void
 
+// CHECK: define linkonce_odr void [[F_INT_LAMBDA]]([[CAP_TYPE2]]*
+// CHECK: [[THIS:%.+]] = load [[CAP_TYPE2]]**
+// CHECK: [[SIZE_REF:%.+]] = getelementptr inbounds [[CAP_TYPE2]]* [[THIS]], i{{.+}} 0, i{{.+}} 0
+// CHECK: [[SIZE:%.+]] = load [[INTPTR_T]]* [[SIZE_REF]]
+// CHECK: call i{{.+}}* @llvm.stacksave()
+// CHECK: alloca [[INTPTR_T]], [[INTPTR_T]] [[SIZE]]
+// CHECK: call void @llvm.stackrestore(
+// CHECK: ret void
+
 // CHECK: define {{.*}} void [[B_INT_LAMBDA]]([[CAP_TYPE3]]*
 // CHECK: [[SIZE2_REF:%.+]] = getelementptr inbounds [[CAP_TYPE3]]* [[THIS:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 1
 // CHECK: [[SIZE2:%.+]] = load i{{[0-9]+}}* [[SIZE2_REF]]
@@ -159,13 +168,4 @@
 // CHECK: [[MUL:%.+]] = mul {{.*}} i{{[0-9]+}} [[SIZE2]], [[SIZE1]]
 // CHECK: mul {{.*}} i{{[0-9]+}} {{[0-9]+}}, [[MUL]]
 // CHECK: ret void
-
-// CHECK: void [[F_INT_LAMBDA]]([[CAP_TYPE2]]*
-// CHECK: [[THIS:%.+]] = load [[CAP_TYPE2]]**
-// CHECK: [[SIZE_REF:%.+]] = getelementptr inbounds [[CAP_TYPE2]]* [[THIS]], i{{.+}} 0, i{{.+}} 0
-// CHECK: [[SIZE:%.+]] = load [[INTPTR_T]]* [[SIZE_REF]]
-// CHECK: call i{{.+}}* @llvm.stacksave()
-// CHECK: alloca [[INTPTR_T]], [[INTPTR_T]] [[SIZE]]
-// CHECK: call void @llvm.stackrestore(
-// CHECK: ret void
 #endif
diff --git a/test/CodeGenCXX/vlt_to_reference.cpp b/test/CodeGenCXX/vlt_to_reference.cpp
new file mode 100644
index 0000000..49d7f1a
--- /dev/null
+++ b/test/CodeGenCXX/vlt_to_reference.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+// CHECK-LABEL: @main
+
+struct dyn_array { 
+    int size;
+    int data[];
+};
+
+int foo(dyn_array **&d) {
+  return (*d)->data[1];
+}
+
+int main()
+{
+    dyn_array **d;
+    return foo(d);
+
+    // CHECK: call {{.+}} @{{.+}}foo{{.+}}(
+    // CHECK: ret i{{[0-9]+}}
+}
+
diff --git a/test/CodeGenCXX/vtable-holder-self-reference.cpp b/test/CodeGenCXX/vtable-holder-self-reference.cpp
new file mode 100644
index 0000000..05e6d71
--- /dev/null
+++ b/test/CodeGenCXX/vtable-holder-self-reference.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -emit-llvm -gdwarf-2 -x c++ -o - %s | FileCheck %s
+//
+// PR21941: crasher for self-referencing DW_TAG_structure_type node.  If we get
+// rid of self-referenceing structure_types (PR21902), then it should be safe
+// to just kill this test.
+//
+// CHECK: ![[SELF:[0-9]+]] = distinct !{!"0x13\00B\00{{[^"]*}}", {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, ![[SELF]], {{[^}]+}}} ; [ DW_TAG_structure_type ] [B]
+
+void foo() {
+  struct V {
+    int vi;
+  };
+  struct B : virtual V {};
+  B b;
+}
diff --git a/test/CodeGenCXX/vtable-linkage.cpp b/test/CodeGenCXX/vtable-linkage.cpp
index 9c08b30..5cbd389 100644
--- a/test/CodeGenCXX/vtable-linkage.cpp
+++ b/test/CodeGenCXX/vtable-linkage.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o %t
+// RUN: %clang_cc1 %s -triple=x86_64-pc-linux -emit-llvm -o %t
 // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -disable-llvm-optzns -O3 -emit-llvm -o %t.opt
 // RUN: FileCheck --check-prefix=CHECK %s < %t
 // RUN: FileCheck --check-prefix=CHECK-OPT %s < %t.opt
@@ -89,10 +89,10 @@
 
 // C has no key function, so its vtable should have weak_odr linkage
 // and hidden visibility (rdar://problem/7523229).
-// CHECK-DAG: @_ZTV1C = linkonce_odr unnamed_addr constant
-// CHECK-DAG: @_ZTS1C = linkonce_odr constant
-// CHECK-DAG: @_ZTI1C = linkonce_odr constant
-// CHECK-DAG: @_ZTT1C = linkonce_odr unnamed_addr constant
+// CHECK-DAG: @_ZTV1C = linkonce_odr unnamed_addr constant {{.*}}, comdat,
+// CHECK-DAG: @_ZTS1C = linkonce_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTI1C = linkonce_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTT1C = linkonce_odr unnamed_addr constant {{.*}}, comdat{{$}}
 
 // D has a key function that is defined in this translation unit so its vtable is
 // defined in the translation unit.
@@ -110,28 +110,28 @@
 // E<short> is an explicit template instantiation with a key function
 // defined in this translation unit, so its vtable should have
 // weak_odr linkage.
-// CHECK-DAG: @_ZTV1EIsE = weak_odr unnamed_addr constant
-// CHECK-DAG: @_ZTS1EIsE = weak_odr constant
-// CHECK-DAG: @_ZTI1EIsE = weak_odr constant
+// CHECK-DAG: @_ZTV1EIsE = weak_odr unnamed_addr constant {{.*}}, comdat,
+// CHECK-DAG: @_ZTS1EIsE = weak_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTI1EIsE = weak_odr constant {{.*}}, comdat{{$}}
 
 // F<short> is an explicit template instantiation without a key
 // function, so its vtable should have weak_odr linkage
-// CHECK-DAG: @_ZTV1FIsE = weak_odr unnamed_addr constant
-// CHECK-DAG: @_ZTS1FIsE = weak_odr constant
-// CHECK-DAG: @_ZTI1FIsE = weak_odr constant
+// CHECK-DAG: @_ZTV1FIsE = weak_odr unnamed_addr constant {{.*}}, comdat,
+// CHECK-DAG: @_ZTS1FIsE = weak_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTI1FIsE = weak_odr constant {{.*}}, comdat{{$}}
 
 // E<long> is an implicit template instantiation with a key function
 // defined in this translation unit, so its vtable should have
 // linkonce_odr linkage.
-// CHECK-DAG: @_ZTV1EIlE = linkonce_odr unnamed_addr constant
-// CHECK-DAG: @_ZTS1EIlE = linkonce_odr constant
-// CHECK-DAG: @_ZTI1EIlE = linkonce_odr constant
+// CHECK-DAG: @_ZTV1EIlE = linkonce_odr unnamed_addr constant {{.*}}, comdat,
+// CHECK-DAG: @_ZTS1EIlE = linkonce_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTI1EIlE = linkonce_odr constant {{.*}}, comdat{{$}}
 
 // F<long> is an implicit template instantiation with no key function,
 // so its vtable should have linkonce_odr linkage.
-// CHECK-DAG: @_ZTV1FIlE = linkonce_odr unnamed_addr constant
-// CHECK-DAG: @_ZTS1FIlE = linkonce_odr constant
-// CHECK-DAG: @_ZTI1FIlE = linkonce_odr constant
+// CHECK-DAG: @_ZTV1FIlE = linkonce_odr unnamed_addr constant {{.*}}, comdat,
+// CHECK-DAG: @_ZTS1FIlE = linkonce_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTI1FIlE = linkonce_odr constant {{.*}}, comdat{{$}}
 
 // F<int> is an explicit template instantiation declaration without a
 // key function, so its vtable should have external linkage.
@@ -158,11 +158,11 @@
 
 // F<char> is an explicit specialization without a key function, so
 // its vtable should have linkonce_odr linkage.
-// CHECK-DAG: @_ZTV1FIcE = linkonce_odr unnamed_addr constant
-// CHECK-DAG: @_ZTS1FIcE = linkonce_odr constant
-// CHECK-DAG: @_ZTI1FIcE = linkonce_odr constant
+// CHECK-DAG: @_ZTV1FIcE = linkonce_odr unnamed_addr constant {{.*}}, comdat,
+// CHECK-DAG: @_ZTS1FIcE = linkonce_odr constant {{.*}}, comdat{{$}}
+// CHECK-DAG: @_ZTI1FIcE = linkonce_odr constant {{.*}}, comdat{{$}}
 
-// CHECK-DAG: @_ZTV1GIiE = linkonce_odr unnamed_addr constant
+// CHECK-DAG: @_ZTV1GIiE = linkonce_odr unnamed_addr constant {{.*}}, comdat,
 template <typename T>
 class G {
 public:
@@ -178,7 +178,7 @@
 
 // H<int> has a key function without a body but it's a template instantiation
 // so its VTable must be emitted.
-// CHECK-DAG: @_ZTV1HIiE = linkonce_odr unnamed_addr constant
+// CHECK-DAG: @_ZTV1HIiE = linkonce_odr unnamed_addr constant {{.*}}, comdat,
 template <typename T>
 class H {
 public:
diff --git a/test/CodeGenCXX/vtable-pointer-initialization.cpp b/test/CodeGenCXX/vtable-pointer-initialization.cpp
index 85e08d8..efdaa6d 100644
--- a/test/CodeGenCXX/vtable-pointer-initialization.cpp
+++ b/test/CodeGenCXX/vtable-pointer-initialization.cpp
@@ -21,13 +21,13 @@
 
 // CHECK-LABEL: define void @_ZN1AC2Ev(%struct.A* %this) unnamed_addr
 // CHECK: call void @_ZN4BaseC2Ev(
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1A, i64 0, i64 2)
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1A, i64 0, i64 2) to i32 (...)**)
 // CHECK: call void @_ZN5FieldC1Ev(
 // CHECK: ret void
 A::A() { }
 
 // CHECK-LABEL: define void @_ZN1AD2Ev(%struct.A* %this) unnamed_addr
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1A, i64 0, i64 2)
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1A, i64 0, i64 2) to i32 (...)**)
 // CHECK: call void @_ZN5FieldD1Ev(
 // CHECK: call void @_ZN4BaseD2Ev(
 // CHECK: ret void
@@ -45,13 +45,16 @@
 // CHECK: call void @_ZN1BC2Ev(
 
 // CHECK-LABEL: define linkonce_odr void @_ZN1BD1Ev(%struct.B* %this) unnamed_addr
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1B, i64 0, i64 2)
-// CHECK: call void @_ZN5FieldD1Ev(
-// CHECK: call void @_ZN4BaseD2Ev(
-// CHECK: ret void
+// CHECK: call void @_ZN1BD2Ev(
 
 // CHECK-LABEL: define linkonce_odr void @_ZN1BC2Ev(%struct.B* %this) unnamed_addr
 // CHECK: call void @_ZN4BaseC2Ev(
-// CHECK: store i8** getelementptr inbounds ([3 x i8*]* @_ZTV1B, i64 0, i64 2)
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1B, i64 0, i64 2) to i32 (...)**)
 // CHECK: call void @_ZN5FieldC1Ev
 // CHECK: ret void
+
+// CHECK-LABEL: define linkonce_odr void @_ZN1BD2Ev(%struct.B* %this) unnamed_addr
+// CHECK: store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @_ZTV1B, i64 0, i64 2) to i32 (...)**)
+// CHECK: call void @_ZN5FieldD1Ev(
+// CHECK: call void @_ZN4BaseD2Ev(
+// CHECK: ret void
diff --git a/test/CodeGenCXX/vtt-layout.cpp b/test/CodeGenCXX/vtt-layout.cpp
index abc2477..d855da7 100644
--- a/test/CodeGenCXX/vtt-layout.cpp
+++ b/test/CodeGenCXX/vtt-layout.cpp
@@ -81,6 +81,6 @@
 // CHECK: @_ZTTN5Test11BE = unnamed_addr constant [1 x i8*] [i8* bitcast (i8** getelementptr inbounds ([4 x i8*]* @_ZTVN5Test11BE, i64 0, i64 3) to i8*)]
 // CHECK: @_ZTVN5Test51AE = unnamed_addr constant [4 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTIN5Test51AE to i8*), i8* bitcast (void ()* @__cxa_pure_virtual to i8*), i8* bitcast (void (%"struct.Test5::A"*)* @_ZN5Test51A6anchorEv to i8*)]
 // CHECK: @_ZTVN5Test61AE = unnamed_addr constant [4 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTIN5Test61AE to i8*), i8* bitcast (void ()* @__cxa_deleted_virtual to i8*), i8* bitcast (void (%"struct.Test6::A"*)* @_ZN5Test61A6anchorEv to i8*)]
-// CHECK: @_ZTTN5Test41DE = linkonce_odr unnamed_addr constant [19 x i8*] [i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE0_NS_2C1E, i64 0, i64 4) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE0_NS_2C1E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE0_NS_2C1E, i64 0, i64 10) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 12) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 15) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 18) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 17) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 20) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 13) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 13) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 1, i64 0) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test41DE40_NS_2V1E, i64 0, i64 3) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test41DE40_NS_2V1E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE72_NS_2V2E, i64 0, i64 4) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE72_NS_2V2E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE72_NS_2V2E, i64 0, i64 10) to i8*)] 
-// CHECK: @_ZTTN5Test31DE = linkonce_odr unnamed_addr constant [13 x i8*] [i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 5) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE0_NS_2C1E, i64 0, i64 3) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE0_NS_2C1E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 10) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 13) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 15) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 11) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 11) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 1, i64 0) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE64_NS_2V2E, i64 0, i64 3) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE64_NS_2V2E, i64 0, i64 6) to i8*)] 
 // CHECK: @_ZTTN5Test21CE = linkonce_odr unnamed_addr constant [2 x i8*] [i8* bitcast (i8** getelementptr inbounds ([5 x i8*]* @_ZTVN5Test21CE, i64 0, i64 4) to i8*), i8* bitcast (i8** getelementptr inbounds ([5 x i8*]* @_ZTVN5Test21CE, i64 0, i64 4) to i8*)] 
+// CHECK: @_ZTTN5Test31DE = linkonce_odr unnamed_addr constant [13 x i8*] [i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 5) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE0_NS_2C1E, i64 0, i64 3) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE0_NS_2C1E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 10) to i8*), i8* bitcast (i8** getelementptr inbounds ([14 x i8*]* @_ZTCN5Test31DE16_NS_2C2E, i64 0, i64 13) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 15) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 11) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 0, i64 11) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTVN5Test31DE, i64 1, i64 0) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE64_NS_2V2E, i64 0, i64 3) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test31DE64_NS_2V2E, i64 0, i64 6) to i8*)] 
+// CHECK: @_ZTTN5Test41DE = linkonce_odr unnamed_addr constant [19 x i8*] [i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE0_NS_2C1E, i64 0, i64 4) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE0_NS_2C1E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE0_NS_2C1E, i64 0, i64 10) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 12) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 15) to i8*), i8* bitcast (i8** getelementptr inbounds ([19 x i8*]* @_ZTCN5Test41DE16_NS_2C2E, i64 0, i64 18) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 17) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 20) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 13) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 0, i64 13) to i8*), i8* bitcast (i8** getelementptr inbounds ([25 x i8*]* @_ZTVN5Test41DE, i64 1, i64 0) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test41DE40_NS_2V1E, i64 0, i64 3) to i8*), i8* bitcast (i8** getelementptr inbounds ([7 x i8*]* @_ZTCN5Test41DE40_NS_2V1E, i64 0, i64 6) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE72_NS_2V2E, i64 0, i64 4) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE72_NS_2V2E, i64 0, i64 7) to i8*), i8* bitcast (i8** getelementptr inbounds ([11 x i8*]* @_ZTCN5Test41DE72_NS_2V2E, i64 0, i64 10) to i8*)] 
diff --git a/test/CodeGenObjC/2010-02-09-DbgSelf.m b/test/CodeGenObjC/2010-02-09-DbgSelf.m
index e939ede..d70b3d6 100644
--- a/test/CodeGenObjC/2010-02-09-DbgSelf.m
+++ b/test/CodeGenObjC/2010-02-09-DbgSelf.m
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 -x objective-c -emit-llvm -g < %s | FileCheck %s
 // Test to check that "self" argument is assigned a location.
-// CHECK: call void @llvm.dbg.declare(metadata !{%0** %{{[^}]+}}}, metadata [[SELF:![0-9]*]], metadata !{{.*}})
+// CHECK: call void @llvm.dbg.declare(metadata %0** %{{[^,]+}}, metadata [[SELF:![0-9]*]], metadata !{{.*}})
 // CHECK: [[SELF]] = {{.*}} ; [ DW_TAG_arg_variable ] [self]
 
 @interface Foo 
diff --git a/test/CodeGenObjC/arc-linetable-autorelease.m b/test/CodeGenObjC/arc-linetable-autorelease.m
index fa10915..ab20f3e 100644
--- a/test/CodeGenObjC/arc-linetable-autorelease.m
+++ b/test/CodeGenObjC/arc-linetable-autorelease.m
@@ -32,8 +32,8 @@
   // CHECK: call void @objc_storeStrong{{.*}} !dbg ![[ARC:[0-9]+]]
   // CHECK: call {{.*}} @objc_autoreleaseReturnValue{{.*}} !dbg ![[ARC]]
   // CHECK: ret {{.*}} !dbg ![[ARC]]
-  // CHECK: ![[RET]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   return path;
-  // CHECK: ![[ARC]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[ARC]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 @end
diff --git a/test/CodeGenObjC/arc-linetable.m b/test/CodeGenObjC/arc-linetable.m
index 2d56ab3..cd746d1 100644
--- a/test/CodeGenObjC/arc-linetable.m
+++ b/test/CodeGenObjC/arc-linetable.m
@@ -4,8 +4,8 @@
 
 // CHECK: define {{.*}}testNoSideEffect
 // CHECK: call void @objc_storeStrong{{.*}}
-// CHECK: call void @objc_storeStrong{{.*}} !dbg ![[ARC1:[0-9]+]]
-// CHECK: ret {{.*}} !dbg ![[RET1:[0-9]+]]
+// CHECK: call void @objc_storeStrong{{.*}} !dbg ![[RET1:[0-9]+]]
+// CHECK: ret {{.*}} !dbg ![[RET1]]
 
 // CHECK: define {{.*}}testNoCleanup
 // CHECK: ret {{.*}} !dbg ![[RET2:[0-9]+]]
@@ -21,8 +21,8 @@
 
 // CHECK: define {{.*}}testVoid
 // CHECK: call void @objc_storeStrong{{.*}}
-// CHECK: call void @objc_storeStrong{{.*}} !dbg ![[ARC5:[0-9]+]]
-// CHECK: ret {{.*}} !dbg ![[RET5:[0-9]+]]
+// CHECK: call void @objc_storeStrong{{.*}} !dbg ![[RET5:[0-9]+]]
+// CHECK: ret {{.*}} !dbg ![[RET5]]
 
 // CHECK: define {{.*}}testVoidNoReturn
 // CHECK: @objc_msgSend{{.*}} !dbg ![[MSG6:[0-9]+]]
@@ -57,52 +57,50 @@
 // CHECK: ![[TESTNOSIDEEFFECT:.*]] = {{.*}}[ DW_TAG_subprogram ] [line [[@LINE+1]]] [local] [def] [-[AppDelegate testNoSideEffect:]]
 - (int)testNoSideEffect:(NSString *)foo {
   int x = 1;
-  // CHECK: ![[ARC1]] = metadata !{i32 [[@LINE+1]], i32 0, metadata ![[TESTNOSIDEEFFECT]], null}
   return 1; // Return expression
-  // CHECK: ![[RET1]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET1]] = !MDLocation(line: [[@LINE+1]], scope: ![[TESTNOSIDEEFFECT]])
 }           // Cleanup + Ret
 
 - (int)testNoCleanup {
-  // CHECK: ![[RET2]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET2]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   return 1;
 }
 
 - (int)testSideEffect:(NSString *)foo {
-  // CHECK: ![[MSG3]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[MSG3]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   return [self testNoSideEffect :foo];
-  // CHECK: ![[RET3]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET3]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 
 - (int)testMultiline:(NSString *)foo {
-  // CHECK: ![[MSG4]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[MSG4]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   int r = [self testSideEffect :foo];
-  // CHECK: ![[EXP4]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[EXP4]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   return r;
-  // CHECK: ![[RET4]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET4]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 
 - (void)testVoid:(NSString *)foo {
-  // CHECK: ![[ARC5]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
   return;
-  // CHECK: ![[RET5]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET5]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 
 - (void)testVoidNoReturn:(NSString *)foo {
-  // CHECK: ![[MSG6]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[MSG6]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   [self testVoid :foo];
-  // CHECK: ![[RET6]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET6]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
 }
 
 - (int)testNoCleanupSideEffect {
-  // CHECK: ![[MSG7]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[MSG7]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   [self testVoid :@"foo"];
-  // CHECK: ![[RET7]] = metadata !{i32 [[@LINE+1]], i32 0, metadata !{{.*}}, null}
+  // CHECK: ![[RET7]] = !MDLocation(line: [[@LINE+1]], scope: !{{.*}})
   return 1;
 }
 
 - (void)testCleanupVoid:(BOOL)skip withDelegate: (AppDelegate *) delegate {
   static BOOL skip_all;
-  // CHECK: ![[SKIP1]] = metadata !{i32 [[@LINE+1]], i32 0,
+  // CHECK: ![[SKIP1]] = !MDLocation(line: [[@LINE+1]], scope:
   if (!skip_all) {
     if (!skip) {
       return;
@@ -112,8 +110,8 @@
       [delegate testVoid :s];
     }
   }
-  // CHECK: ![[RET8]] = metadata !{i32 [[@LINE+2]], i32 0,
-  // CHECK: ![[ARC8]] = metadata !{i32 [[@LINE+1]], i32 0,
+  // CHECK: ![[RET8]] = !MDLocation(line: [[@LINE+2]], scope:
+  // CHECK: ![[ARC8]] = !MDLocation(line: [[@LINE+1]], scope:
 }
 
 
diff --git a/test/CodeGenObjC/arc-precise-lifetime.m b/test/CodeGenObjC/arc-precise-lifetime.m
index ddbd704..dede949 100644
--- a/test/CodeGenObjC/arc-precise-lifetime.m
+++ b/test/CodeGenObjC/arc-precise-lifetime.m
@@ -110,7 +110,7 @@
   // CHECK-NEXT: [[EIGHT:%.*]] = bitcast [[TEST1]]* [[SIX]] to i8*
   // CHECK-NEXT: [[CALL1:%.*]] = call i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* [[EIGHT]], i8* [[SEVEN]])
   // CHECK-NEXT: store i8* [[CALL1]], i8**
-  // CHECK-NEXT: [[NINE:%.*]] = load [[TEST1]]** 
+  // CHECK-NEXT: [[NINE:%.*]] = load [[TEST1]]**
   // CHECK-NEXT: [[TEN:%.*]] = bitcast [[TEST1]]* [[NINE]] to i8*
   // CHECK-NEXT: call void @objc_release(i8* [[TEN]])
   // CHECK-NEXT: ret void
diff --git a/test/CodeGenObjC/arm-atomic-scalar-setter-getter.m b/test/CodeGenObjC/arm-atomic-scalar-setter-getter.m
index 535cbbb..6eb5890 100644
--- a/test/CodeGenObjC/arm-atomic-scalar-setter-getter.m
+++ b/test/CodeGenObjC/arm-atomic-scalar-setter-getter.m
@@ -8,6 +8,6 @@
 @implementation I
 @synthesize LONG_PROP;
 @end
-// CHECK-ARM: call arm_aapcscc  void @objc_copyStruct(i8* %{{.*}}, i8* %{{.*}}, i32 8, i1 zeroext true, i1 zeroext false)
-// CHECK-ARM: call arm_aapcscc  void @objc_copyStruct(i8* %{{.*}}, i8* %{{.*}}, i32 8, i1 zeroext true, i1 zeroext false)
+// CHECK-ARM: call void @objc_copyStruct(i8* %{{.*}}, i8* %{{.*}}, i32 8, i1 zeroext true, i1 zeroext false)
+// CHECK-ARM: call void @objc_copyStruct(i8* %{{.*}}, i8* %{{.*}}, i32 8, i1 zeroext true, i1 zeroext false)
 
diff --git a/test/CodeGenObjC/debug-info-block-captured-self.m b/test/CodeGenObjC/debug-info-block-captured-self.m
index 87ef9a3..f0ca1af 100644
--- a/test/CodeGenObjC/debug-info-block-captured-self.m
+++ b/test/CodeGenObjC/debug-info-block-captured-self.m
@@ -55,15 +55,15 @@
 // CHECK-NEXT:   %[[MEM2:.*]] = alloca i8*, align 8
 // CHECK:        store i8* [[BLOCK_DESC:%.*]], i8** %[[MEM1]], align 8
 // CHECK:        %[[TMP0:.*]] = load i8** %[[MEM1]]
-// CHECK:        call void @llvm.dbg.value(metadata !{i8* %[[TMP0]]}, i64 0, metadata ![[BDMD:[0-9]+]], metadata !{{.*}})
-// CHECK:        call void @llvm.dbg.declare(metadata !{i8* [[BLOCK_DESC]]}, metadata ![[BDMD:[0-9]+]], metadata !{{.*}})
+// CHECK:        call void @llvm.dbg.value(metadata i8* %[[TMP0]], i64 0, metadata ![[BDMD:[0-9]+]], metadata !{{.*}})
+// CHECK:        call void @llvm.dbg.declare(metadata i8* [[BLOCK_DESC]], metadata ![[BDMD:[0-9]+]], metadata !{{.*}})
 // CHECK:        %[[TMP1:.*]] = bitcast
 // CHECK-NEXT:   store
-// CHECK:        call void @llvm.dbg.declare(metadata !{<{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>** {{.*}}}, metadata ![[SELF:.*]], metadata !{{.*}})
+// CHECK:        call void @llvm.dbg.declare(metadata <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>** {{[^,]*}}, metadata ![[SELF:.*]], metadata !{{.*}})
 // make sure we are still in the same function
 // CHECK: define {{.*}}__copy_helper_block_
 // Metadata
-// CHECK:        ![[MAIN:.*]] = metadata !{metadata !"0x13\00Main\0023\00{{.*}}", {{.*}} ; [ DW_TAG_structure_type ] [Main] [line 23,
+// CHECK:        ![[MAIN:.*]] = !{!"0x13\00Main\0023\00{{.*}}", {{.*}} ; [ DW_TAG_structure_type ] [Main] [line 23,
 // CHECK:        ![[PMAIN:.*]] = {{.*}}![[MAIN]]} ; [ DW_TAG_pointer_type ]{{.*}}from Main
-// CHECK:        ![[BDMD]] = metadata {{.*}}.block_descriptor
+// CHECK:        ![[BDMD]] = {{.*}}.block_descriptor
 // CHECK:        ![[SELF]] = {{.*}}![[PMAIN]]{{.*}}[ DW_TAG_auto_variable ] [self] [line 40]
diff --git a/test/CodeGenObjC/debug-info-block-type.m b/test/CodeGenObjC/debug-info-block-type.m
index e50163e..ef92bf3 100644
--- a/test/CodeGenObjC/debug-info-block-type.m
+++ b/test/CodeGenObjC/debug-info-block-type.m
@@ -5,14 +5,14 @@
 // CHECK: ![[ID:[0-9]+]] = {{.*}} [ DW_TAG_typedef ] [id]
 
 typedef BOOL (^SomeKindOfPredicate)(id obj);
-// CHECK: metadata ![[PTR:[0-9]+]]} ; [ DW_TAG_member ] [__FuncPtr]
-// CHECK: ![[PTR]] = {{.*}}, metadata ![[FNTYPE:[0-9]+]]} ; [ DW_TAG_pointer_type ]
-// CHECK: ![[FNTYPE]] = {{.*}} metadata ![[ARGS:[0-9]+]]{{.*}} ; [ DW_TAG_subroutine_type ]
-// CHECK: ![[ARGS]] = metadata !{metadata ![[BOOL]], metadata ![[ID]]}
+// CHECK: ![[PTR:[0-9]+]]} ; [ DW_TAG_member ] [__FuncPtr]
+// CHECK: ![[PTR]] = {{.*}}, ![[FNTYPE:[0-9]+]]} ; [ DW_TAG_pointer_type ]
+// CHECK: ![[FNTYPE]] = {{.*}} ![[ARGS:[0-9]+]]{{.*}} ; [ DW_TAG_subroutine_type ]
+// CHECK: ![[ARGS]] = !{![[BOOL]], ![[ID]]}
 
 int main()
 {
   SomeKindOfPredicate p = ^BOOL(id obj) { return obj != nil; };
-  // CHECK: metadata ![[PTR]]} ; [ DW_TAG_member ] [__FuncPtr] [line [[@LINE-1]], size 64, align 64, offset 128]
+  // CHECK: ![[PTR]]} ; [ DW_TAG_member ] [__FuncPtr] [line [[@LINE-1]], size 64, align 64, offset 128]
   return p(nil);
 }
diff --git a/test/CodeGenObjC/debug-info-blocks.m b/test/CodeGenObjC/debug-info-blocks.m
index aaa28d2..f5f4437 100644
--- a/test/CodeGenObjC/debug-info-blocks.m
+++ b/test/CodeGenObjC/debug-info-blocks.m
@@ -7,8 +7,8 @@
 // CHECK: define {{.*}}_block_invoke
 // CHECK: %[[BLOCK:.*]] = bitcast i8* %.block_descriptor to <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>*, !dbg
 // CHECK-NEXT: store <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>* %[[BLOCK]], <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>** %[[ALLOCA:.*]], align
-// CHECK-NEXT: call void @llvm.dbg.declare(metadata !{<{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>** %[[ALLOCA]]}, metadata ![[SELF:[0-9]+]], metadata !{{.*}})
-// CHECK-NEXT: call void @llvm.dbg.declare(metadata !{%1** %d}, metadata ![[D:[0-9]+]], metadata !{{.*}})
+// CHECK-NEXT: call void @llvm.dbg.declare(metadata <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, %0* }>** %[[ALLOCA]], metadata ![[SELF:[0-9]+]], metadata !{{.*}})
+// CHECK-NEXT: call void @llvm.dbg.declare(metadata %1** %d, metadata ![[D:[0-9]+]], metadata !{{.*}})
 
 // rdar://problem/14386148
 // Test that we don't emit bogus line numbers for the helper functions.
@@ -22,10 +22,10 @@
 // CHECK-NOT: ret
 // CHECK: load {{.*}}, !dbg ![[DESTROY_LINE:[0-9]+]]
 
-// CHECK-DAG: [[DBG_LINE]] = metadata !{i32 0, i32 0, metadata ![[COPY_SP:[0-9]+]], null}
-// CHECK-DAG: [[COPY_LINE]] = metadata !{i32 0, i32 0, metadata ![[COPY_SP:[0-9]+]], null}
+// CHECK-DAG: [[DBG_LINE]] = !MDLocation(line: 0, scope: ![[COPY_SP:[0-9]+]])
+// CHECK-DAG: [[COPY_LINE]] = !MDLocation(line: 0, scope: ![[COPY_SP:[0-9]+]])
 // CHECK-DAG: [[COPY_SP]] = {{.*}}[ DW_TAG_subprogram ]{{.*}}[__copy_helper_block_]
-// CHECK-DAG: [[DESTROY_LINE]] = metadata !{i32 0, i32 0, metadata ![[DESTROY_SP:[0-9]+]], null}
+// CHECK-DAG: [[DESTROY_LINE]] = !MDLocation(line: 0, scope: ![[DESTROY_SP:[0-9]+]])
 // CHECK-DAG: [[DESTROY_SP]] = {{.*}}[ DW_TAG_subprogram ]{{.*}}[__destroy_helper_block_]
 typedef unsigned int NSUInteger;
 
diff --git a/test/CodeGenObjC/debug-info-getter-name.m b/test/CodeGenObjC/debug-info-getter-name.m
index cf38116..9e1e55f 100644
--- a/test/CodeGenObjC/debug-info-getter-name.m
+++ b/test/CodeGenObjC/debug-info-getter-name.m
@@ -1,7 +1,7 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-apple-darwin10 -fexceptions -fobjc-exceptions -g %s -o - | FileCheck %s
 
-// CHECK: metadata !{metadata !"0x2e\00-[InstanceVariablesEverywhereButTheInterface someString]\00{{.*}}", {{.*}} ; [ DW_TAG_subprogram ]
+// CHECK:  !"0x2e\00-[InstanceVariablesEverywhereButTheInterface someString]\00{{.*}}", {{.*}} ; [ DW_TAG_subprogram ]
 
 //rdar: //8498026
 
diff --git a/test/CodeGenObjC/debug-info-id-with-protocol.m b/test/CodeGenObjC/debug-info-id-with-protocol.m
index b14c30a..9233f6c 100644
--- a/test/CodeGenObjC/debug-info-id-with-protocol.m
+++ b/test/CodeGenObjC/debug-info-id-with-protocol.m
@@ -36,7 +36,7 @@
     }
 }
 // Verify that the debug type for both variables is 'id'.
-// CHECK: metadata !{metadata !"0x101\00bad_carrier\00{{[0-9]+}}\000", metadata !{{[0-9]+}}, null, metadata ![[IDTYPE:[0-9]+]]} ; [ DW_TAG_arg_variable ] [bad_carrier] [line 0]
+// CHECK:  !"0x101\00bad_carrier\00{{[0-9]+}}\000", !{{[0-9]+}}, null, ![[IDTYPE:[0-9]+]]} ; [ DW_TAG_arg_variable ] [bad_carrier] [line 0]
 //
-// CHECK: metadata !{metadata !"0x101\00good_carrier\00{{[0-9]+}}\000", metadata !{{[0-9]+}}, null, metadata ![[IDTYPE]]} ; [ DW_TAG_arg_variable ] [good_carrier] [line 0]
-// CHECK !{{.*}}[[IDTYPE]] = metadata !{metadata !"0x16\00id\00{{[0-9]+}}\000\000\000\000", null, metadata !{{[0-9]+}}, metadata !{{[0-9]+}}} ; [ DW_TAG_typedef ] [id]
+// CHECK:  !"0x101\00good_carrier\00{{[0-9]+}}\000", !{{[0-9]+}}, null, ![[IDTYPE]]} ; [ DW_TAG_arg_variable ] [good_carrier] [line 0]
+// CHECK !{{.*}}[[IDTYPE]] = !{!"0x16\00id\00{{[0-9]+}}\000\000\000\000", null, !{{[0-9]+}}, !{{[0-9]+}}} ; [ DW_TAG_typedef ] [id]
diff --git a/test/CodeGenObjC/debug-info-instancetype.m b/test/CodeGenObjC/debug-info-instancetype.m
index 4a7c581..07fd5ca 100644
--- a/test/CodeGenObjC/debug-info-instancetype.m
+++ b/test/CodeGenObjC/debug-info-instancetype.m
@@ -13,11 +13,11 @@
 
 @implementation Foo
 +(instancetype)defaultFoo {return 0;}
-// CHECK: ![[FOO:[0-9]+]] = metadata {{.*}}; [ DW_TAG_structure_type ] [Foo]
-// CHECK: metadata !{metadata !"0x2e\00+[Foo defaultFoo]\00+[Foo defaultFoo]\00\00[[@LINE-2]]\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[TYPE:[0-9]+]]
-// CHECK: ![[TYPE]] = {{.*}} metadata ![[RESULT:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
-// CHECK: ![[RESULT]] = metadata {{.*}}{metadata ![[FOOPTR:[0-9]+]],
-// CHECK: ![[FOOPTR]] = {{.*}}, metadata ![[FOO]]}{{.*}}[ DW_TAG_pointer_type ] {{.*}} [from Foo]
+// CHECK: ![[FOO:[0-9]+]] = {{.*}}; [ DW_TAG_structure_type ] [Foo]
+// CHECK:  !"0x2e\00+[Foo defaultFoo]\00+[Foo defaultFoo]\00\00[[@LINE-2]]\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[TYPE:[0-9]+]]
+// CHECK: ![[TYPE]] = {{.*}} ![[RESULT:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: ![[RESULT]] = {{.*}}{![[FOOPTR:[0-9]+]],
+// CHECK: ![[FOOPTR]] = {{.*}}, ![[FOO]]}{{.*}}[ DW_TAG_pointer_type ] {{.*}} [from Foo]
 @end
 
 
diff --git a/test/CodeGenObjC/debug-info-lifetime-crash.m b/test/CodeGenObjC/debug-info-lifetime-crash.m
index 43e196e..e2e5d7e 100644
--- a/test/CodeGenObjC/debug-info-lifetime-crash.m
+++ b/test/CodeGenObjC/debug-info-lifetime-crash.m
@@ -13,10 +13,10 @@
 {
   // The debug type for these two will be identical, because we do not
   // actually emit the ownership qualifier.
-  // CHECK-DAG: metadata !{metadata !"0x100\00weakSelf\00[[@LINE+1]]\000"{{, [^,]+, [^,]+}}, metadata ![[SELFTY:[0-9]+]]} ; [ DW_TAG_auto_variable ] [weakSelf]
+  // CHECK-DAG:  !"0x100\00weakSelf\00[[@LINE+1]]\000"{{, [^,]+, [^,]+}}, ![[SELFTY:[0-9]+]]} ; [ DW_TAG_auto_variable ] [weakSelf]
   __attribute__((objc_ownership(weak))) __typeof(self) weakSelf = self;
   Block = [^{
-  // CHECK-DAG: metadata !{metadata !"0x100\00strongSelf\00[[@LINE+1]]\000"{{, [^,]+, [^,]+}}, metadata ![[SELFTY]]} ; [ DW_TAG_auto_variable ] [strongSelf]
+  // CHECK-DAG:  !"0x100\00strongSelf\00[[@LINE+1]]\000"{{, [^,]+, [^,]+}}, ![[SELFTY]]} ; [ DW_TAG_auto_variable ] [strongSelf]
       __attribute__((objc_ownership(strong))) __typeof(self) strongSelf = weakSelf;
     } copy];
 }
diff --git a/test/CodeGenObjC/debug-info-nested-blocks.m b/test/CodeGenObjC/debug-info-nested-blocks.m
index 029348c..5c5958c 100644
--- a/test/CodeGenObjC/debug-info-nested-blocks.m
+++ b/test/CodeGenObjC/debug-info-nested-blocks.m
@@ -23,4 +23,4 @@
 //
 // CHECK: define {{.*}}void @__bar_block_invoke_3(i8* %.block_descriptor)
 // CHECK: %[[BLOCKADDR:.*]] = alloca <{{.*}}>*, align
-// CHECK: call void @llvm.dbg.declare(metadata !{{.*}}%[[BLOCKADDR]]
+// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%[[BLOCKADDR]]
diff --git a/test/CodeGenObjC/debug-info-property-accessors.m b/test/CodeGenObjC/debug-info-property-accessors.m
index 4510dcf..0c7f03e 100644
--- a/test/CodeGenObjC/debug-info-property-accessors.m
+++ b/test/CodeGenObjC/debug-info-property-accessors.m
@@ -5,7 +5,7 @@
 // Ensure we emit the names of explicit/renamed accessors even if they
 // are defined later in the implementation section.
 //
-// CHECK: metadata !{metadata !"0x4200\00blah\00{{[0-9]+}}\00isBlah\00{{.*}}", {{.*}}} ; [ DW_TAG_APPLE_property ] [blah]
+// CHECK:  !"0x4200\00blah\00{{[0-9]+}}\00isBlah\00{{.*}}", {{.*}}} ; [ DW_TAG_APPLE_property ] [blah]
 
 @class NSString;
 extern void NSLog(NSString *format, ...);
diff --git a/test/CodeGenObjC/debug-info-property3.m b/test/CodeGenObjC/debug-info-property3.m
index f09f821..a6d8daf 100644
--- a/test/CodeGenObjC/debug-info-property3.m
+++ b/test/CodeGenObjC/debug-info-property3.m
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 -S -emit-llvm -g %s -o - | FileCheck %s
 
-// CHECK: metadata !{metadata !"0x4200\00p1\005\00\00\002316", {{.*}}} ; [ DW_TAG_APPLE_property ]
+// CHECK:  !"0x4200\00p1\005\00\00\002316", {{.*}}} ; [ DW_TAG_APPLE_property ]
 @interface I1
 @property int p1;
 @end
diff --git a/test/CodeGenObjC/debug-info-self.m b/test/CodeGenObjC/debug-info-self.m
index c02ca57..a6e9daf 100644
--- a/test/CodeGenObjC/debug-info-self.m
+++ b/test/CodeGenObjC/debug-info-self.m
@@ -14,6 +14,6 @@
 }
 @end
 
-// CHECK: metadata !{metadata !"0x101\00self\0016777216\001088", metadata ![[CTOR:.*]], null, metadata !{{.*}}} ; [ DW_TAG_arg_variable ] [self] [line 0]
-// CHECK: metadata !{metadata !"0x101\00_cmd\0033554432\0064", metadata ![[CTOR]], null, metadata !{{.*}}} ; [ DW_TAG_arg_variable ] [_cmd] [line 0]
-// CHECK: metadata !{metadata !"0x101\00myarg\0050331659\000", metadata ![[CTOR]], metadata !{{.*}}, metadata !{{.*}}} ; [ DW_TAG_arg_variable ] [myarg] [line 11]
+// CHECK:  !"0x101\00self\0016777216\001088", ![[CTOR:.*]], null, !{{.*}}} ; [ DW_TAG_arg_variable ] [self] [line 0]
+// CHECK:  !"0x101\00_cmd\0033554432\0064", ![[CTOR]], null, !{{.*}}} ; [ DW_TAG_arg_variable ] [_cmd] [line 0]
+// CHECK:  !"0x101\00myarg\0050331659\000", ![[CTOR]], !{{.*}}, !{{.*}}} ; [ DW_TAG_arg_variable ] [myarg] [line 11]
diff --git a/test/CodeGenObjC/debug-info-static-var.m b/test/CodeGenObjC/debug-info-static-var.m
index 45f9d82..6828983 100644
--- a/test/CodeGenObjC/debug-info-static-var.m
+++ b/test/CodeGenObjC/debug-info-static-var.m
@@ -2,7 +2,7 @@
 // Radar 8801045
 // Do not emit AT_MIPS_linkage_name for static variable i
 
-// CHECK: metadata !{metadata !"0x34\00i\00i\00\00{{.*}}"
+// CHECK:  !"0x34\00i\00i\00\00{{.*}}"
 
 @interface A {
 }
diff --git a/test/CodeGenObjC/debug-info-synthesis.m b/test/CodeGenObjC/debug-info-synthesis.m
index 1bf7576..55867b4 100644
--- a/test/CodeGenObjC/debug-info-synthesis.m
+++ b/test/CodeGenObjC/debug-info-synthesis.m
@@ -31,4 +31,4 @@
 }
 
 // CHECK: ![[FILE:.*]] = {{.*}}[ DW_TAG_file_type ] [{{.*}}/foo.h]
-// CHECK: metadata ![[FILE]], {{.*}} ; [ DW_TAG_subprogram ] [line 8] [local] [def] [-[Foo dict]]
+// CHECK: ![[FILE]], {{.*}} ; [ DW_TAG_subprogram ] [line 8] [local] [def] [-[Foo dict]]
diff --git a/test/CodeGenObjC/debug-info-variadic-method.m b/test/CodeGenObjC/debug-info-variadic-method.m
index a4e759d..e895953 100644
--- a/test/CodeGenObjC/debug-info-variadic-method.m
+++ b/test/CodeGenObjC/debug-info-variadic-method.m
@@ -10,7 +10,7 @@
 @implementation Foo
 - (void) Bar: (int) n, ...
 {
-  // CHECK: metadata ![[NUM:[^,]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
-  // CHECK: ![[NUM]] = {{metadata !{null, metadata ![^,]*, metadata ![^,]*, metadata ![^,]*, null}}}    
+  // CHECK: ![[NUM:[^,]*]], null, null, null} ; [ DW_TAG_subroutine_type ]
+  // CHECK: ![[NUM]] = {{!{null, ![^,]*, ![^,]*, ![^,]*, null}}}    
 }
 @end
diff --git a/test/CodeGenObjC/debug-property-synth.m b/test/CodeGenObjC/debug-property-synth.m
index 68fb956..1465724 100644
--- a/test/CodeGenObjC/debug-property-synth.m
+++ b/test/CodeGenObjC/debug-property-synth.m
@@ -20,8 +20,8 @@
 //
 // CHECK: [ DW_TAG_subprogram ] [line [[@LINE+4]]] [local] [def] [-[I p1]]
 // CHECK: [ DW_TAG_subprogram ] [line [[@LINE+3]]] [local] [def] [-[I setP1:]]
-// CHECK: ![[DBG1]] = metadata !{i32 [[@LINE+2]],
-// CHECK: ![[DBG2]] = metadata !{i32 [[@LINE+1]],
+// CHECK: ![[DBG1]] = !MDLocation(line: [[@LINE+2]],
+// CHECK: ![[DBG2]] = !MDLocation(line: [[@LINE+1]],
 @property int p1;
 @end
 
diff --git a/test/CodeGenObjC/encode-test-5.m b/test/CodeGenObjC/encode-test-5.m
index a27ffb7..c7f030c 100644
--- a/test/CodeGenObjC/encode-test-5.m
+++ b/test/CodeGenObjC/encode-test-5.m
@@ -1,16 +1,21 @@
-// RUN: %clang_cc1 -triple=x86_64-apple-darwin9 -emit-llvm -o %t %s
+// RUN: %clang_cc1 -x objective-c -triple=x86_64-apple-darwin9 -emit-llvm -o - < %s | FileCheck %s
 
-// RUN: grep ji.00 %t | count 1
+// CHECK-DAG: @[[complex_int:.*]] = private unnamed_addr constant [3 x i8] c"ji\00", align 1
+// CHECK-DAG: @a = global i8* getelementptr inbounds ([3 x i8]* @[[complex_int]], i32 0, i32 0), align 8
 char *a = @encode(_Complex int);
 
-// RUN: grep jf.00 %t | count 1
+// CHECK-DAG: @[[complex_float:.*]] = private unnamed_addr constant [3 x i8] c"jf\00", align 1
+// CHECK-DAG: @b = global i8* getelementptr inbounds ([3 x i8]* @[[complex_float]], i32 0, i32 0), align 8
 char *b = @encode(_Complex float);
 
-// RUN: grep jd.00 %t | count 1
+// CHECK-DAG: @[[complex_double:.*]] = private unnamed_addr constant [3 x i8] c"jd\00", align 1
+// CHECK-DAG: @c = global i8* getelementptr inbounds ([3 x i8]* @[[complex_double]], i32 0, i32 0), align 8
 char *c = @encode(_Complex double);
 
-// RUN: grep "t.00" %t | count 1
+// CHECK-DAG: @[[int_128:.*]] = private unnamed_addr constant [2 x i8] c"t\00", align 1
+// CHECK-DAG: @e = global i8* getelementptr inbounds ([2 x i8]* @[[int_128]], i32 0, i32 0), align 8
 char *e = @encode(__int128_t);
 
-// RUN: grep "T.00" %t | count 1
+// CHECK-DAG: @[[uint_128:.*]] = private unnamed_addr constant [2 x i8] c"T\00", align 1
+// CHECK-DAG: @f = global i8* getelementptr inbounds ([2 x i8]* @[[uint_128]], i32 0, i32 0), align 8
 char *f = @encode(__uint128_t);
diff --git a/test/CodeGenObjC/image-info.m b/test/CodeGenObjC/image-info.m
index 49f5d90..43fb125 100644
--- a/test/CodeGenObjC/image-info.m
+++ b/test/CodeGenObjC/image-info.m
@@ -5,13 +5,13 @@
 // RUN: FileCheck --check-prefix CHECK-NONFRAGILE < %t %s
 
 // CHECK-FRAGILE:      !llvm.module.flags = !{{{.*}}}
-// CHECK-FRAGILE:      !{{[0-9]+}} = metadata !{i32 1, metadata !"Objective-C Version", i32 1}
-// CHECK-FRAGILE-NEXT: !{{[0-9]+}} = metadata !{i32 1, metadata !"Objective-C Image Info Version", i32 0}
-// CHECK-FRAGILE-NEXT: !{{[0-9]+}} = metadata !{i32 1, metadata !"Objective-C Image Info Section", metadata !"__OBJC, __image_info,regular"}
-// CHECK-FRAGILE-NEXT: !{{[0-9]+}} = metadata !{i32 4, metadata !"Objective-C Garbage Collection", i32 0}
+// CHECK-FRAGILE:      !{{[0-9]+}} = !{i32 1, !"Objective-C Version", i32 1}
+// CHECK-FRAGILE-NEXT: !{{[0-9]+}} = !{i32 1, !"Objective-C Image Info Version", i32 0}
+// CHECK-FRAGILE-NEXT: !{{[0-9]+}} = !{i32 1, !"Objective-C Image Info Section", !"__OBJC, __image_info,regular"}
+// CHECK-FRAGILE-NEXT: !{{[0-9]+}} = !{i32 4, !"Objective-C Garbage Collection", i32 0}
 
 // CHECK-NONFRAGILE:      !llvm.module.flags = !{{{.*}}}
-// CHECK-NONFRAGILE:      !{{[0-9]+}} = metadata !{i32 1, metadata !"Objective-C Version", i32 2}
-// CHECK-NONFRAGILE-NEXT: !{{[0-9]+}} = metadata !{i32 1, metadata !"Objective-C Image Info Version", i32 0}
-// CHECK-NONFRAGILE-NEXT: !{{[0-9]+}} = metadata !{i32 1, metadata !"Objective-C Image Info Section", metadata !"__DATA, __objc_imageinfo, regular, no_dead_strip"}
-// CHECK-NONFRAGILE-NEXT: !{{[0-9]+}} = metadata !{i32 4, metadata !"Objective-C Garbage Collection", i32 0}
+// CHECK-NONFRAGILE:      !{{[0-9]+}} = !{i32 1, !"Objective-C Version", i32 2}
+// CHECK-NONFRAGILE-NEXT: !{{[0-9]+}} = !{i32 1, !"Objective-C Image Info Version", i32 0}
+// CHECK-NONFRAGILE-NEXT: !{{[0-9]+}} = !{i32 1, !"Objective-C Image Info Section", !"__DATA, __objc_imageinfo, regular, no_dead_strip"}
+// CHECK-NONFRAGILE-NEXT: !{{[0-9]+}} = !{i32 4, !"Objective-C Garbage Collection", i32 0}
diff --git a/test/CodeGenObjC/objc-fixed-enum.m b/test/CodeGenObjC/objc-fixed-enum.m
index 9a028ea..eff317c 100644
--- a/test/CodeGenObjC/objc-fixed-enum.m
+++ b/test/CodeGenObjC/objc-fixed-enum.m
@@ -34,13 +34,13 @@
 
 int main() {
   Enum0 e0 = Enum0One;
-  // CHECK: call void @llvm.dbg.declare(metadata !{{.*}}, metadata ![[ENUM0:[0-9]+]], metadata !{{.*}})
+  // CHECK: call void @llvm.dbg.declare(metadata {{.*}}, metadata ![[ENUM0:[0-9]+]], metadata !{{.*}})
   Enum1 e1 = Enum1One;
-  // CHECK: call void @llvm.dbg.declare(metadata !{{.*}}, metadata ![[ENUM1:[0-9]+]], metadata !{{.*}})
+  // CHECK: call void @llvm.dbg.declare(metadata {{.*}}, metadata ![[ENUM1:[0-9]+]], metadata !{{.*}})
   Enum2 e2 = Enum2One;
-  // CHECK: call void @llvm.dbg.declare(metadata !{{.*}}, metadata ![[ENUM2:[0-9]+]], metadata !{{.*}})
+  // CHECK: call void @llvm.dbg.declare(metadata {{.*}}, metadata ![[ENUM2:[0-9]+]], metadata !{{.*}})
   Enum3 e3 = Enum3One;
-  // CHECK: call void @llvm.dbg.declare(metadata !{{.*}}, metadata ![[ENUM3:[0-9]+]], metadata !{{.*}})
+  // CHECK: call void @llvm.dbg.declare(metadata {{.*}}, metadata ![[ENUM3:[0-9]+]], metadata !{{.*}})
 
   // -Werror and the following line ensures that these enums are not
   // -treated as C++11 strongly typed enums.
@@ -51,14 +51,14 @@
 // CHECK: ![[ENUMERATOR3:[0-9]+]] = {{.*}}; [ DW_TAG_typedef ] [NSInteger] [line 6{{.*}}] [from long int]
 // CHECK: ![[ENUMERATOR2:[0-9]+]] = {{.*}}; [ DW_TAG_enumeration_type ] [line 22{{.*}}] [from NSInteger]
 
-// CHECK: ![[ENUM0]] = metadata !{metadata !"0x100\00e0\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[TYPE0:[0-9]+]]} ; [ DW_TAG_auto_variable ]
-// CHECK: ![[TYPE0]] = metadata !{metadata !"0x16\00Enum0\00{{.*}}", {{.*}}, metadata ![[ENUMERATOR0]]} ; [ DW_TAG_typedef ] [Enum0]
+// CHECK: ![[ENUM0]] = !{!"0x100\00e0\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[TYPE0:[0-9]+]]} ; [ DW_TAG_auto_variable ]
+// CHECK: ![[TYPE0]] = !{!"0x16\00Enum0\00{{.*}}", {{.*}}, ![[ENUMERATOR0]]} ; [ DW_TAG_typedef ] [Enum0]
 
-// CHECK: ![[ENUM1]] = metadata !{metadata !"0x100\00e1\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[TYPE1:[0-9]+]]} ; [ DW_TAG_auto_variable ]
-// CHECK: ![[TYPE1]] = metadata !{metadata !"0x16\00Enum1\00{{.*}}", {{.*}}, metadata ![[ENUMERATOR1]]} ; [ DW_TAG_typedef ] [Enum1]
+// CHECK: ![[ENUM1]] = !{!"0x100\00e1\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[TYPE1:[0-9]+]]} ; [ DW_TAG_auto_variable ]
+// CHECK: ![[TYPE1]] = !{!"0x16\00Enum1\00{{.*}}", {{.*}}, ![[ENUMERATOR1]]} ; [ DW_TAG_typedef ] [Enum1]
 
-// CHECK: ![[ENUM2]] = metadata !{metadata !"0x100\00e2\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[TYPE2:[0-9]+]]} ; [ DW_TAG_auto_variable ]
-// CHECK: ![[TYPE2]] = metadata !{metadata !"0x16\00Enum2\00{{.*}}", {{.*}}, metadata ![[ENUMERATOR2]]} ; [ DW_TAG_typedef ] [Enum2]
+// CHECK: ![[ENUM2]] = !{!"0x100\00e2\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[TYPE2:[0-9]+]]} ; [ DW_TAG_auto_variable ]
+// CHECK: ![[TYPE2]] = !{!"0x16\00Enum2\00{{.*}}", {{.*}}, ![[ENUMERATOR2]]} ; [ DW_TAG_typedef ] [Enum2]
 
-// CHECK: ![[ENUM3]] = metadata !{metadata !"0x100\00e3\00{{[^,]*}}"{{, [^,]+, [^,]+}}, metadata ![[TYPE3:[0-9]+]]} ; [ DW_TAG_auto_variable ]
-// CHECK: ![[TYPE3]] = metadata !{metadata !"0x16\00Enum3\00{{.*}}", {{.*}}, metadata ![[ENUMERATOR3]]} ; [ DW_TAG_typedef ] [Enum3]
+// CHECK: ![[ENUM3]] = !{!"0x100\00e3\00{{[^,]*}}"{{, [^,]+, [^,]+}}, ![[TYPE3:[0-9]+]]} ; [ DW_TAG_auto_variable ]
+// CHECK: ![[TYPE3]] = !{!"0x16\00Enum3\00{{.*}}", {{.*}}, ![[ENUMERATOR3]]} ; [ DW_TAG_typedef ] [Enum3]
diff --git a/test/CodeGenObjC/optimized-setter-ios-device.m b/test/CodeGenObjC/optimized-setter-ios-device.m
index 6fa322a..ae8f34c 100644
--- a/test/CodeGenObjC/optimized-setter-ios-device.m
+++ b/test/CodeGenObjC/optimized-setter-ios-device.m
@@ -26,8 +26,8 @@
 @synthesize atomicPropertyCopy;
 @end
 
-// CHECK: call arm_aapcscc void @objc_setProperty_nonatomic
-// CHECK: call arm_aapcscc void @objc_setProperty_nonatomic_copy
-// CHECK: call arm_aapcscc void @objc_setProperty_atomic
-// CHECK: call arm_aapcscc void @objc_setProperty_atomic_copy
+// CHECK: call void @objc_setProperty_nonatomic
+// CHECK: call void @objc_setProperty_nonatomic_copy
+// CHECK: call void @objc_setProperty_atomic
+// CHECK: call void @objc_setProperty_atomic_copy
 
diff --git a/test/CodeGenObjCXX/arc-cxx11-init-list.mm b/test/CodeGenObjCXX/arc-cxx11-init-list.mm
index 7356b6e..da214dc 100644
--- a/test/CodeGenObjCXX/arc-cxx11-init-list.mm
+++ b/test/CodeGenObjCXX/arc-cxx11-init-list.mm
@@ -1,5 +1,4 @@
-// RUN: %clang_cc1 -triple armv7-ios5.0 -std=c++11 -fobjc-arc -Os -emit-llvm -o - %s \
-// RUN:     | FileCheck %s
+// RUN: %clang_cc1 -triple armv7-ios5.0 -std=c++11 -fobjc-arc -Os -emit-llvm -o - %s | FileCheck %s
 
 typedef __SIZE_TYPE__ size_t;
 
@@ -21,17 +20,17 @@
 
 extern "C" void single() { function({ [I new] }); }
 
-// CHECK: [[INSTANCE:%.*]] = {{.*}} call {{.*}} i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
-// CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[INSTANCE]] to %0*
-// CHECK-NEXT: store %0* [[CAST]], %0** [[ARRAY:%.*]],
-// CHECK: call {{.*}} void @objc_release(i8* {{.*}})
+// CHECK: [[INSTANCE:%.*]] = {{.*}} call i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
+// CHECK-NEXT: [[CAST:%.*]] = bitcast [{{[0-9]+}} x %0*]* %{{.*}} to i8**
+// CHECK-NEXT: store i8* [[INSTANCE]], i8** [[CAST]],
+// CHECK: call void @objc_release(i8* {{.*}})
 
 extern "C" void multiple() { function({ [I new], [I new] }); }
 
-// CHECK: [[INSTANCE:%.*]] = {{.*}} call {{.*}} i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
-// CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[INSTANCE]] to %0*
-// CHECK-NEXT: store %0* [[CAST]], %0** [[ARRAY:%.*]],
-// CHECK: call {{.*}} void @objc_release(i8* {{.*}})
+// CHECK: [[INSTANCE:%.*]] = {{.*}} call i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
+// CHECK-NEXT: [[CAST:%.*]] = bitcast [{{[0-9]+}} x %0*]* %{{.*}} to i8**
+// CHECK-NEXT: store i8* [[INSTANCE]], i8** [[CAST]],
+// CHECK: call void @objc_release(i8* {{.*}})
 // CHECK-NEXT: icmp eq
 
 void external();
@@ -41,17 +40,16 @@
   external();
 }
 
-// CHECK: [[INSTANCE:%.*]] = {{.*}} call {{.*}} i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
-// CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[INSTANCE:%.*]] to {{.*}}*
-// CHECK-NEXT: store {{.*}}* [[CAST]], {{.*}}** {{.*}}
-// CHECK: {{.*}} call {{.*}} void @_Z8externalv()
-// CHECK: {{.*}} call {{.*}} void @objc_release(i8* {{.*}})
+// CHECK: [[INSTANCE:%.*]] = {{.*}} call i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
+// CHECK-NEXT: [[CAST:%.*]] = bitcast [1 x %0*]* %{{.*}} to i8**
+// CHECK-NEXT: store i8* [[INSTANCE]], i8** [[CAST]],
+// CHECK: {{.*}} call void @_Z8externalv()
+// CHECK: {{.*}} call void @objc_release(i8* {{.*}})
 
 std::initializer_list<I *> il = { [I new] };
 
-// CHECK: [[POOL:%.*]] = {{.*}} call {{.*}} i8* @objc_autoreleasePoolPush()
-// CHECK: [[INSTANCE:%.*]] = {{.*}} call {{.*}} i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
-// CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[INSTANCE]] to %0*
-// CHECK-NEXT: store %0* [[CAST]], %0** getelementptr inbounds ([1 x %0*]* @_ZGR2il_, i32 0, i32 0)
-// CHECK: {{.*}} call {{.*}} void @objc_autoreleasePoolPop(i8* [[POOL]])
+// CHECK: [[POOL:%.*]] = {{.*}} call i8* @objc_autoreleasePoolPush()
+// CHECK: [[INSTANCE:%.*]] = {{.*}} call i8* bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i8* (i8*, i8*)*)(i8* {{.*}}, i8* {{.*}})
+// CHECK-NEXT: store i8* [[INSTANCE]], i8** bitcast ([1 x %0*]* @_ZGR2il_ to i8**)
+// CHECK: {{.*}} call void @objc_autoreleasePoolPop(i8* [[POOL]])
 
diff --git a/test/CodeGenObjCXX/arc-cxx11-member-init.mm b/test/CodeGenObjCXX/arc-cxx11-member-init.mm
index 5129f9f..b09bbb8 100644
--- a/test/CodeGenObjCXX/arc-cxx11-member-init.mm
+++ b/test/CodeGenObjCXX/arc-cxx11-member-init.mm
@@ -22,7 +22,7 @@
 }
 @end
 
-// CHECK: [[mClipData:%.*]] = getelementptr inbounds %class.XClipboardDataSet* 
+// CHECK: [[mClipData:%.*]] = getelementptr inbounds %class.XClipboardDataSet*
 // CHECK: [[ZERO:%.*]] = load %struct._class_t** @"OBJC_CLASSLIST_REFERENCES_$_"
 // CHECK: [[ONE:%.*]] = load i8** @OBJC_SELECTOR_REFERENCES_
 // CHECK: [[TWO:%.*]] = bitcast %struct._class_t* [[ZERO]] to i8*
diff --git a/test/CodeGenObjCXX/arc-pseudo-destructors.mm b/test/CodeGenObjCXX/arc-pseudo-destructors.mm
index 0a69487..d21844a 100644
--- a/test/CodeGenObjCXX/arc-pseudo-destructors.mm
+++ b/test/CodeGenObjCXX/arc-pseudo-destructors.mm
@@ -3,7 +3,7 @@
 // CHECK-LABEL: define void @_Z28test_objc_object_pseudo_dtorPU8__strongP11objc_objectPU6__weakS0_
 void test_objc_object_pseudo_dtor(__strong id *ptr, __weak id *wptr) {
   // CHECK: load i8***
-  // CHECK-NEXT: load i8** 
+  // CHECK-NEXT: load i8**
   // CHECK-NEXT: call void @objc_release
   ptr->~id();
 
@@ -11,7 +11,7 @@
   wptr->~id();
 
   // CHECK: load i8***
-  // CHECK-NEXT: load i8** 
+  // CHECK-NEXT: load i8**
   // CHECK-NEXT: call void @objc_release
   (*ptr).~id();
 
diff --git a/test/CodeGenObjCXX/arc-special-member-functions.mm b/test/CodeGenObjCXX/arc-special-member-functions.mm
index 8b002d5..32c00a6 100644
--- a/test/CodeGenObjCXX/arc-special-member-functions.mm
+++ b/test/CodeGenObjCXX/arc-special-member-functions.mm
@@ -104,27 +104,27 @@
 // CHECK-NEXT: call void @objc_release(i8* [[T7]])
 // CHECK-NEXT: ret
 
-// Implicitly-generated copy constructor for ObjCBlockMember
-// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCBlockMemberC2ERKS_
-// CHECK: call i8* @objc_retainBlock
-// CHECK: ret
-
-// Implicitly-generated destructor for ObjCBlockMember
-// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCBlockMemberD2Ev
-// CHECK: call void @objc_storeStrong(i8*
-// CHECK: ret
-
-// Implicitly-generated default constructor for ObjCBlockMember
-// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCBlockMemberC2Ev
-// CHECK: store {{.*}} null,
+// Implicitly-generated default constructor for ObjCMember
+// CHECK-LABEL: define linkonce_odr void @_ZN10ObjCMemberC2Ev
+// CHECK-NOT: objc_release
+// CHECK: store i8* null
 // CHECK-NEXT: ret void
 
-// Implicitly-generated copy constructor for ObjCArrayMember
-// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCArrayMemberC2ERKS_
-// CHECK: br i1
+// Implicitly-generated destructor for ObjCMember
+// CHECK-LABEL: define linkonce_odr void @_ZN10ObjCMemberD2Ev
+// CHECK: call void @objc_storeStrong
+// CHECK: ret void
+
+// Implicitly-generated copy constructor for ObjCMember
+// CHECK-LABEL: define linkonce_odr void @_ZN10ObjCMemberC2ERKS_
+// CHECK-NOT: objc_release
 // CHECK: call i8* @objc_retain
 // CHECK-NEXT: store i8*
-// CHECK-NEXT: br label
+// CHECK-NEXT: ret void
+
+// Implicitly-generated default constructor for ObjCArrayMember
+// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCArrayMemberC2Ev
+// CHECK: call void @llvm.memset.p0i8.i64
 // CHECK: ret
 
 // Implicitly-generated destructor for ObjCArrayMember
@@ -136,29 +136,29 @@
 // CHECK-NEXT: [[CUR]] = getelementptr inbounds i8** [[PAST]], i64 -1
 // CHECK-NEXT: call void @objc_storeStrong(i8** [[CUR]], i8* null)
 // CHECK-NEXT: [[T1:%.*]] = icmp eq i8** [[CUR]], [[BEGIN]]
-// CHECK-NEXT: br i1 [[T1]], 
+// CHECK-NEXT: br i1 [[T1]],
 // CHECK:      ret void
 
-// Implicitly-generated default constructor for ObjCArrayMember
-// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCArrayMemberC2Ev
-// CHECK: call void @llvm.memset.p0i8.i64
-// CHECK: ret
-
-// Implicitly-generated copy constructor for ObjCMember
-// CHECK-LABEL: define linkonce_odr void @_ZN10ObjCMemberC2ERKS_
-// CHECK-NOT: objc_release
+// Implicitly-generated copy constructor for ObjCArrayMember
+// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCArrayMemberC2ERKS_
+// CHECK: br i1
 // CHECK: call i8* @objc_retain
 // CHECK-NEXT: store i8*
+// CHECK-NEXT: br label
+// CHECK: ret
+
+// Implicitly-generated default constructor for ObjCBlockMember
+// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCBlockMemberC2Ev
+// CHECK: store {{.*}} null,
 // CHECK-NEXT: ret void
 
-// Implicitly-generated destructor for ObjCMember
-// CHECK-LABEL: define linkonce_odr void @_ZN10ObjCMemberD2Ev
-// CHECK: call void @objc_storeStrong
-// CHECK: ret void
+// Implicitly-generated destructor for ObjCBlockMember
+// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCBlockMemberD2Ev
+// CHECK: call void @objc_storeStrong(i8*
+// CHECK: ret
 
-// Implicitly-generated default constructor for ObjCMember
-// CHECK-LABEL: define linkonce_odr void @_ZN10ObjCMemberC2Ev
-// CHECK-NOT: objc_release
-// CHECK: store i8* null
-// CHECK-NEXT: ret void
+// Implicitly-generated copy constructor for ObjCBlockMember
+// CHECK-LABEL: define linkonce_odr void @_ZN15ObjCBlockMemberC2ERKS_
+// CHECK: call i8* @objc_retainBlock
+// CHECK: ret
 
diff --git a/test/CodeGenObjCXX/debug-info-cyclic.mm b/test/CodeGenObjCXX/debug-info-cyclic.mm
new file mode 100644
index 0000000..8fd83a5
--- /dev/null
+++ b/test/CodeGenObjCXX/debug-info-cyclic.mm
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -g -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: ![[B:.*]] = {{.*}}, null, null, ![[BMEMBERS:.*]], null, null, null} ; [ DW_TAG_structure_type ] [B] [line [[@LINE+1]], size 8, align 8, offset 0] [def] [from ]
+struct B {
+  B(struct A *);
+// CHECK: ![[BMEMBERS]] = !{![[BB:.*]]}
+// CHECK: ![[BB]] = {{.*}} ![[B]], ![[TY:[0-9]+]], {{.*}}} ; [ DW_TAG_subprogram ] [line [[@LINE-2]]] [B]
+// CHECK: ![[TY]] = {{.*}} ![[ARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
+// CHECK: ![[ARGS]] = !{null, ![[THIS:[0-9]+]],
+// CHECK: ![[THIS]] = {{.*}}[[B]]} ; [ DW_TAG_pointer_type ] [
+};
+
+struct C {
+ B b;
+ C(struct A *);
+ virtual ~C();
+};
+
+C::C(struct A *a)
+  : b(a) {
+}
diff --git a/test/CodeGenObjCXX/debug-info-line.mm b/test/CodeGenObjCXX/debug-info-line.mm
new file mode 100644
index 0000000..4c934f1
--- /dev/null
+++ b/test/CodeGenObjCXX/debug-info-line.mm
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -gline-tables-only -fblocks -emit-llvm %s -o - | FileCheck %s
+
+void fn();
+
+struct foo {
+  ~foo();
+};
+
+void f1() {
+  ^{
+    foo f;
+    fn();
+    // CHECK: cleanup, !dbg [[DBG_F1:![0-9]*]]
+#line 100
+  }();
+}
+
+// CHECK-LABEL: define internal i8* @"\01-[TNSObject init]"
+@implementation TNSObject
+- (id)init
+{
+  foo f;
+  fn();
+  // CHECK: cleanup, !dbg [[DBG_TNSO:![0-9]*]]
+#line 200
+}
+@end
+
+// CHECK: [[DBG_F1]] = !MDLocation(line: 100,
+// CHECK: [[DBG_TNSO]] = !MDLocation(line: 200,
diff --git a/test/CodeGenObjCXX/destroy.mm b/test/CodeGenObjCXX/destroy.mm
index c53ac39..5d797d3 100644
--- a/test/CodeGenObjCXX/destroy.mm
+++ b/test/CodeGenObjCXX/destroy.mm
@@ -43,8 +43,8 @@
 // CHECK: call void @_ZN8tderivedIiEC1Ev
 // CHECK: call void @_ZN8tderivedIiED1Ev
 
-// CHECK-LABEL: define linkonce_odr void @_ZN8tderivedIiED2Ev
+// CHECK-LABEL: define linkonce_odr void @_ZN7derivedD2Ev
 // CHECK: call void @objc_storeStrong(i8** {{.*}}, i8* null)
 
-// CHECK-LABEL: define linkonce_odr void @_ZN7derivedD2Ev
+// CHECK-LABEL: define linkonce_odr void @_ZN8tderivedIiED2Ev
 // CHECK: call void @objc_storeStrong(i8** {{.*}}, i8* null)
diff --git a/test/CodeGenObjCXX/lambda-expressions.mm b/test/CodeGenObjCXX/lambda-expressions.mm
index 9129ff0..4b1995d 100644
--- a/test/CodeGenObjCXX/lambda-expressions.mm
+++ b/test/CodeGenObjCXX/lambda-expressions.mm
@@ -60,6 +60,8 @@
 }
 @end
 
+// ARC-LABEL: define linkonce_odr i32 ()* @_ZZNK13StaticMembersIfE1fMUlvE_clEvENKUlvE_cvU13block_pointerFivEEv
+
 // Check lines for BlockInLambda test below
 // ARC-LABEL: define internal i32 @___ZZN13BlockInLambda1X1fEvENKUlvE_clEv_block_invoke
 // ARC: [[Y:%.*]] = getelementptr inbounds %"struct.BlockInLambda::X"* {{.*}}, i32 0, i32 1
@@ -73,7 +75,6 @@
 template<typename T>
 fptr StaticMembers<T>::f = [] { auto f = []{return 5;}; return fptr(f); }();
 template fptr StaticMembers<float>::f;
-// ARC-LABEL: define linkonce_odr i32 ()* @_ZZNK13StaticMembersIfE1fMUlvE_clEvENKUlvE_cvU13block_pointerFivEEv
 
 namespace BlockInLambda {
   struct X {
diff --git a/test/CodeGenObjCXX/mangle-blocks.mm b/test/CodeGenObjCXX/mangle-blocks.mm
index 1f3f163..283996d 100644
--- a/test/CodeGenObjCXX/mangle-blocks.mm
+++ b/test/CodeGenObjCXX/mangle-blocks.mm
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -emit-llvm -fblocks -o - -triple x86_64-apple-darwin10 -fobjc-runtime=macosx-fragile-10.5 %s | FileCheck %s
 
 // CHECK: @_ZZZN26externally_visible_statics1S3fooEiEd_Ub0_E1k = linkonce_odr global i32 0
-// CHECK: @_ZZ26externally_visible_statics1S1xMUb0_E1j = linkonce_odr global i32 0
 // CHECK: @_ZZZN26externally_visible_statics10inlinefuncEvEUb0_E1i = linkonce_odr global i32 0
+// CHECK: @_ZZ26externally_visible_statics1S1xMUb0_E1j = linkonce_odr global i32 0
 
 int f();
 
diff --git a/test/CodeGenObjCXX/nested-ehlocation.mm b/test/CodeGenObjCXX/nested-ehlocation.mm
new file mode 100644
index 0000000..de3e359
--- /dev/null
+++ b/test/CodeGenObjCXX/nested-ehlocation.mm
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1  -triple x86_64-apple-macosx -emit-llvm -g -stdlib=libc++ -fblocks -fexceptions -x objective-c++ -o - %s | FileCheck %s
+
+// Verify that all invoke instructions have a debug location.
+// Literally: There are no unwind lines that don't end with ", (!dbg 123)".
+// CHECK-NOT: {{to label %.* unwind label [^,]+$}}
+
+void block(void (^)(void));
+extern void foo();
+struct A {
+  ~A(void) { foo(); }
+  void bar() const {}
+};
+void baz(void const *const) {}
+struct B : A {};
+void test() {
+  A a;
+  B b;
+  block(^(void) {
+    baz(&b);
+    block(^() {
+      a.bar();
+    });
+  });
+}
diff --git a/test/CodeGenObjCXX/subst-sel.mm b/test/CodeGenObjCXX/subst-sel.mm
new file mode 100644
index 0000000..f4a2b84
--- /dev/null
+++ b/test/CodeGenObjCXX/subst-sel.mm
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
+
+// CHECK: @_Z4bad1P8NSObjectP13objc_selectorP11objc_objectS4_
+void bad1(struct NSObject *, SEL, id, id) {}
diff --git a/test/CodeGenOpenCL/address-spaces-conversions.cl b/test/CodeGenOpenCL/address-spaces-conversions.cl
new file mode 100644
index 0000000..bc80f47
--- /dev/null
+++ b/test/CodeGenOpenCL/address-spaces-conversions.cl
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 %s -triple x86_64-unknown-linux-gnu -O0 -ffake-address-space-map -cl-std=CL2.0 -emit-llvm -o - | FileCheck %s
+
+// test that we generate address space casts everywhere we need conversions of
+// pointers to different address spaces
+
+void test(global int *arg_glob, generic int *arg_gen) {
+  int var_priv;
+  arg_gen = arg_glob; // implicit cast global -> generic
+  // CHECK: %{{[0-9]+}} = addrspacecast i32 addrspace(1)* %{{[0-9]+}} to i32 addrspace(4)*
+  arg_gen = &var_priv; // implicit cast with obtaining adr, private -> generic
+  // CHECK: %{{[0-9]+}} = addrspacecast i32* %var_priv to i32 addrspace(4)*
+  arg_glob = (global int *)arg_gen; // explicit cast
+  // CHECK: %{{[0-9]+}} = addrspacecast i32 addrspace(4)* %{{[0-9]+}} to i32 addrspace(1)*
+  global int *var_glob =
+      (global int *)arg_glob; // explicit cast in the same address space
+  // CHECK-NOT: %{{[0-9]+}} = addrspacecast i32 addrspace(1)* %{{[0-9]+}} to i32 addrspace(1)*
+  var_priv = arg_gen - arg_glob; // arithmetic operation
+  // CHECK: %{{.*}} = ptrtoint i32 addrspace(4)* %{{.*}} to i64
+  // CHECK: %{{.*}} = ptrtoint i32 addrspace(1)* %{{.*}} to i64
+  var_priv = arg_gen > arg_glob; // comparison
+  // CHECK: %{{[0-9]+}} = addrspacecast i32 addrspace(1)* %{{[0-9]+}} to i32 addrspace(4)*
+}
diff --git a/test/CodeGenOpenCL/amdgpu-num-gpr-attr.cl b/test/CodeGenOpenCL/amdgpu-num-gpr-attr.cl
new file mode 100644
index 0000000..35bdcea
--- /dev/null
+++ b/test/CodeGenOpenCL/amdgpu-num-gpr-attr.cl
@@ -0,0 +1,48 @@
+// RUN: %clang_cc1 -triple amdgcn-- -target-cpu tahiti -O0 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O0 -emit-llvm -verify -o - %s | FileCheck -check-prefix=X86 %s
+
+// Make sure this is silently accepted on other targets.
+
+__attribute__((amdgpu_num_vgpr(64))) // expected-no-diagnostics
+kernel void test_num_vgpr64() {
+// CHECK: define void @test_num_vgpr64() [[ATTR_VGPR64:#[0-9]+]]
+}
+
+__attribute__((amdgpu_num_sgpr(32))) // expected-no-diagnostics
+kernel void test_num_sgpr32() {
+// CHECK: define void @test_num_sgpr32() [[ATTR_SGPR32:#[0-9]+]]
+}
+
+__attribute__((amdgpu_num_vgpr(64), amdgpu_num_sgpr(32))) // expected-no-diagnostics
+kernel void test_num_vgpr64_sgpr32() {
+// CHECK: define void @test_num_vgpr64_sgpr32() [[ATTR_VGPR64_SGPR32:#[0-9]+]]
+
+}
+
+__attribute__((amdgpu_num_sgpr(20), amdgpu_num_vgpr(40))) // expected-no-diagnostics
+kernel void test_num_sgpr20_vgpr40() {
+// CHECK: define void @test_num_sgpr20_vgpr40() [[ATTR_SGPR20_VGPR40:#[0-9]+]]
+}
+
+__attribute__((amdgpu_num_vgpr(0))) // expected-no-diagnostics
+kernel void test_num_vgpr0() {
+}
+
+__attribute__((amdgpu_num_sgpr(0))) // expected-no-diagnostics
+kernel void test_num_sgpr0() {
+}
+
+__attribute__((amdgpu_num_vgpr(0), amdgpu_num_sgpr(0))) // expected-no-diagnostics
+kernel void test_num_vgpr0_sgpr0() {
+}
+
+
+// X86-NOT: "amdgpu_num_vgpr"
+// X86-NOT: "amdgpu_num_sgpr"
+
+// CHECK-DAG-NOT: "amdgpu_num_vgpr"="0"
+// CHECK-DAG-NOT: "amdgpu_num_sgpr"="0"
+// CHECK-DAG: attributes [[ATTR_VGPR64]] = { nounwind "amdgpu_num_vgpr"="64"
+// CHECK-DAG: attributes [[ATTR_SGPR32]] = { nounwind "amdgpu_num_sgpr"="32"
+// CHECK-DAG: attributes [[ATTR_VGPR64_SGPR32]] = { nounwind "amdgpu_num_sgpr"="32" "amdgpu_num_vgpr"="64"
+// CHECK-DAG: attributes [[ATTR_SGPR20_VGPR40]] = { nounwind "amdgpu_num_sgpr"="20" "amdgpu_num_vgpr"="40"
diff --git a/test/CodeGenOpenCL/builtins-r600.cl b/test/CodeGenOpenCL/builtins-r600.cl
index 129531f..3e416b0 100644
--- a/test/CodeGenOpenCL/builtins-r600.cl
+++ b/test/CodeGenOpenCL/builtins-r600.cl
@@ -1,5 +1,6 @@
 // REQUIRES: r600-registered-target
 // RUN: %clang_cc1 -triple r600-unknown-unknown -S -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck %s
 
 #pragma OPENCL EXTENSION cl_khr_fp64 : enable
 
@@ -126,3 +127,17 @@
 {
   *out = __builtin_amdgpu_ldexp(a, b);
 }
+
+// CHECK-LABEL: @test_class_f32
+// CHECK: call i1 @llvm.AMDGPU.class.f32
+void test_class_f32(global float* out, float a, int b)
+{
+  *out = __builtin_amdgpu_classf(a, b);
+}
+
+// CHECK-LABEL: @test_class_f64
+// CHECK: call i1 @llvm.AMDGPU.class.f64
+void test_class_f64(global double* out, double a, int b)
+{
+  *out = __builtin_amdgpu_class(a, b);
+}
diff --git a/test/CodeGenOpenCL/cl-strict-aliasing.cl b/test/CodeGenOpenCL/cl-strict-aliasing.cl
new file mode 100644
index 0000000..b403f7c
--- /dev/null
+++ b/test/CodeGenOpenCL/cl-strict-aliasing.cl
@@ -0,0 +1 @@
+// RUN: %clang_cc1 -x cl -emit-llvm -cl-strict-aliasing < %s
diff --git a/test/CodeGenOpenCL/const-str-array-decay.cl b/test/CodeGenOpenCL/const-str-array-decay.cl
new file mode 100644
index 0000000..dbbe089
--- /dev/null
+++ b/test/CodeGenOpenCL/const-str-array-decay.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - -ffake-address-space-map | FileCheck %s
+
+int test_func(constant char* foo);
+
+kernel void str_array_decy() {
+  test_func("Test string literal");
+}
+
+// CHECK: i8 addrspace(3)* getelementptr inbounds ([20 x i8] addrspace(3)*
+// CHECK-NOT: addrspacecast
+
diff --git a/test/CodeGenOpenCL/fpmath.cl b/test/CodeGenOpenCL/fpmath.cl
index 704fcd7..ef4da84 100644
--- a/test/CodeGenOpenCL/fpmath.cl
+++ b/test/CodeGenOpenCL/fpmath.cl
@@ -22,4 +22,4 @@
   return a / b;
 }
 
-// CHECK: ![[MD]] = metadata !{float 2.500000e+00}
+// CHECK: ![[MD]] = !{float 2.500000e+00}
diff --git a/test/CodeGenOpenCL/kernel-arg-info.cl b/test/CodeGenOpenCL/kernel-arg-info.cl
index 89da3fd..4bc191e 100644
--- a/test/CodeGenOpenCL/kernel-arg-info.cl
+++ b/test/CodeGenOpenCL/kernel-arg-info.cl
@@ -1,49 +1,55 @@
-// RUN: %clang_cc1 %s -cl-kernel-arg-info -emit-llvm -o - -triple spir-unknown-unknown | FileCheck %s
+// RUN: %clang_cc1 %s -cl-kernel-arg-info -emit-llvm -o - -triple spir-unknown-unknown | FileCheck %s -check-prefix ARGINFO
+// RUN: %clang_cc1 %s -emit-llvm -o - -triple spir-unknown-unknown | FileCheck %s -check-prefix NO-ARGINFO
 
 kernel void foo(__global int * restrict X, const int Y, 
                 volatile int anotherArg, __constant float * restrict Z) {
   *X = Y + anotherArg;
 }
 
-// CHECK: metadata !{metadata !"kernel_arg_addr_space", i32 1, i32 0, i32 0, i32 2}
-// CHECK: metadata !{metadata !"kernel_arg_access_qual", metadata !"none", metadata !"none", metadata !"none", metadata !"none"}
-// CHECK: metadata !{metadata !"kernel_arg_type", metadata !"int*", metadata !"int", metadata !"int", metadata !"float*"}
-// CHECK: metadata !{metadata !"kernel_arg_base_type", metadata !"int*", metadata !"int", metadata !"int", metadata !"float*"}
-// CHECK: metadata !{metadata !"kernel_arg_type_qual", metadata !"restrict", metadata !"const", metadata !"volatile", metadata !"restrict const"}
-// CHECK: metadata !{metadata !"kernel_arg_name", metadata !"X", metadata !"Y", metadata !"anotherArg", metadata !"Z"}
+// CHECK:  !{!"kernel_arg_addr_space", i32 1, i32 0, i32 0, i32 2}
+// CHECK:  !{!"kernel_arg_access_qual", !"none", !"none", !"none", !"none"}
+// CHECK:  !{!"kernel_arg_type", !"int*", !"int", !"int", !"float*"}
+// CHECK:  !{!"kernel_arg_base_type", !"int*", !"int", !"int", !"float*"}
+// CHECK:  !{!"kernel_arg_type_qual", !"restrict", !"const", !"volatile", !"restrict const"}
+// ARGINFO: !{!"kernel_arg_name", !"X", !"Y", !"anotherArg", !"Z"}
+// NO-ARGINFO-NOT: !{!"kernel_arg_name", !"X", !"Y", !"anotherArg", !"Z"}
 
 kernel void foo2(read_only image1d_t img1, image2d_t img2, write_only image2d_array_t img3) {
 }
-// CHECK: metadata !{metadata !"kernel_arg_addr_space", i32 1, i32 1, i32 1}
-// CHECK: metadata !{metadata !"kernel_arg_access_qual", metadata !"read_only", metadata !"read_only", metadata !"write_only"}
-// CHECK: metadata !{metadata !"kernel_arg_type", metadata !"image1d_t", metadata !"image2d_t", metadata !"image2d_array_t"}
-// CHECK: metadata !{metadata !"kernel_arg_base_type", metadata !"image1d_t", metadata !"image2d_t", metadata !"image2d_array_t"}
-// CHECK: metadata !{metadata !"kernel_arg_type_qual", metadata !"", metadata !"", metadata !""}
-// CHECK: metadata !{metadata !"kernel_arg_name", metadata !"img1", metadata !"img2", metadata !"img3"}
+// CHECK:  !{!"kernel_arg_addr_space", i32 1, i32 1, i32 1}
+// CHECK:  !{!"kernel_arg_access_qual", !"read_only", !"read_only", !"write_only"}
+// CHECK:  !{!"kernel_arg_type", !"image1d_t", !"image2d_t", !"image2d_array_t"}
+// CHECK:  !{!"kernel_arg_base_type", !"image1d_t", !"image2d_t", !"image2d_array_t"}
+// CHECK:  !{!"kernel_arg_type_qual", !"", !"", !""}
+// ARGINFO: !{!"kernel_arg_name", !"img1", !"img2", !"img3"}
+// NO-ARGINFO-NOT: !{!"kernel_arg_name", !"img1", !"img2", !"img3"}
 
 kernel void foo3(__global half * X) {
 }
-// CHECK: metadata !{metadata !"kernel_arg_addr_space", i32 1}
-// CHECK: metadata !{metadata !"kernel_arg_access_qual", metadata !"none"}
-// CHECK: metadata !{metadata !"kernel_arg_type", metadata !"half*"}
-// CHECK: metadata !{metadata !"kernel_arg_base_type", metadata !"half*"}
-// CHECK: metadata !{metadata !"kernel_arg_type_qual", metadata !""}
-// CHECK: metadata !{metadata !"kernel_arg_name", metadata !"X"}
+// CHECK:  !{!"kernel_arg_addr_space", i32 1}
+// CHECK:  !{!"kernel_arg_access_qual", !"none"}
+// CHECK:  !{!"kernel_arg_type", !"half*"}
+// CHECK:  !{!"kernel_arg_base_type", !"half*"}
+// CHECK:  !{!"kernel_arg_type_qual", !""}
+// ARGINFO: !{!"kernel_arg_name", !"X"}
+// NO-ARGINFO-NOT: !{!"kernel_arg_name", !"X"}
 
 typedef unsigned int myunsignedint;
 kernel void foo4(__global unsigned int * X, __global myunsignedint * Y) {
 }
-// CHECK: metadata !{metadata !"kernel_arg_addr_space", i32 1, i32 1}
-// CHECK: metadata !{metadata !"kernel_arg_access_qual", metadata !"none", metadata !"none"}
-// CHECK: metadata !{metadata !"kernel_arg_type", metadata !"uint*", metadata !"myunsignedint*"}
-// CHECK: metadata !{metadata !"kernel_arg_base_type", metadata !"uint*", metadata !"uint*"}
-// CHECK: metadata !{metadata !"kernel_arg_type_qual", metadata !"", metadata !""}
-// CHECK: metadata !{metadata !"kernel_arg_name", metadata !"X", metadata !"Y"}
+// CHECK:  !{!"kernel_arg_addr_space", i32 1, i32 1}
+// CHECK:  !{!"kernel_arg_access_qual", !"none", !"none"}
+// CHECK:  !{!"kernel_arg_type", !"uint*", !"myunsignedint*"}
+// CHECK:  !{!"kernel_arg_base_type", !"uint*", !"uint*"}
+// CHECK:  !{!"kernel_arg_type_qual", !"", !""}
+// ARGINFO: !{!"kernel_arg_name", !"X", !"Y"}
+// NO-ARGINFO-NOT: !{!"kernel_arg_name", !"X", !"Y"}
 
 typedef image1d_t myImage;
 kernel void foo5(read_only myImage img1, write_only image1d_t img2) {
 }
-// CHECK: metadata !{metadata !"kernel_arg_access_qual", metadata !"read_only", metadata !"write_only"}
-// CHECK: metadata !{metadata !"kernel_arg_type", metadata !"myImage", metadata !"image1d_t"}
-// CHECK: metadata !{metadata !"kernel_arg_base_type", metadata !"image1d_t", metadata !"image1d_t"}
-// CHECK: metadata !{metadata !"kernel_arg_name", metadata !"img1", metadata !"img2"}
+// CHECK:  !{!"kernel_arg_access_qual", !"read_only", !"write_only"}
+// CHECK:  !{!"kernel_arg_type", !"myImage", !"image1d_t"}
+// CHECK:  !{!"kernel_arg_base_type", !"image1d_t", !"image1d_t"}
+// ARGINFO: !{!"kernel_arg_name", !"img1", !"img2"}
+// NO-ARGINFO-NOT: !{!"kernel_arg_name", !"img1", !"img2"}
diff --git a/test/CodeGenOpenCL/kernel-attributes.cl b/test/CodeGenOpenCL/kernel-attributes.cl
index 0825ffc..8f22d61 100644
--- a/test/CodeGenOpenCL/kernel-attributes.cl
+++ b/test/CodeGenOpenCL/kernel-attributes.cl
@@ -8,9 +8,9 @@
 
 // CHECK: opencl.kernels = !{[[MDNODE0:![0-9]+]], [[MDNODE3:![0-9]+]]}
 
-// CHECK: [[MDNODE0]] = metadata !{void (i32)* @kernel1, metadata [[MDNODE1:![0-9]+]], metadata [[MDNODE2:![0-9]+]]}
-// CHECK: [[MDNODE1]] = metadata !{metadata !"vec_type_hint", i32 undef, i32 1}
-// CHECK: [[MDNODE2]] = metadata !{metadata !"reqd_work_group_size", i32 1, i32 2, i32 4}
-// CHECK: [[MDNODE3]] = metadata !{void (i32)* @kernel2, metadata [[MDNODE4:![0-9]+]], metadata [[MDNODE5:![0-9]+]]}
-// CHECK: [[MDNODE4]] = metadata !{metadata !"vec_type_hint", <4 x i32> undef, i32 0}
-// CHECK: [[MDNODE5]] = metadata !{metadata !"work_group_size_hint", i32 8, i32 16, i32 32}
+// CHECK: [[MDNODE0]] = !{void (i32)* @kernel1, {{.*}} [[MDNODE1:![0-9]+]], [[MDNODE2:![0-9]+]]}
+// CHECK: [[MDNODE1]] = !{!"vec_type_hint", i32 undef, i32 1}
+// CHECK: [[MDNODE2]] = !{!"reqd_work_group_size", i32 1, i32 2, i32 4}
+// CHECK: [[MDNODE3]] = !{void (i32)* @kernel2, {{.*}} [[MDNODE4:![0-9]+]], [[MDNODE5:![0-9]+]]}
+// CHECK: [[MDNODE4]] = !{!"vec_type_hint", <4 x i32> undef, i32 0}
+// CHECK: [[MDNODE5]] = !{!"work_group_size_hint", i32 8, i32 16, i32 32}
diff --git a/test/CodeGenOpenCL/kernel-metadata.cl b/test/CodeGenOpenCL/kernel-metadata.cl
index 3e10a11..ef3758f 100644
--- a/test/CodeGenOpenCL/kernel-metadata.cl
+++ b/test/CodeGenOpenCL/kernel-metadata.cl
@@ -7,4 +7,9 @@
 }
 
 // CHECK: !opencl.kernels = !{!0}
-// CHECK: !0 = metadata !{void ()* @kernel_function}
+// CHECK: !0 = !{void ()* @kernel_function, !1, !2, !3, !4, !5}
+// CHECK: !1 = !{!"kernel_arg_addr_space"}
+// CHECK: !2 = !{!"kernel_arg_access_qual"}
+// CHECK: !3 = !{!"kernel_arg_type"}
+// CHECK: !4 = !{!"kernel_arg_base_type"}
+// CHECK: !5 = !{!"kernel_arg_type_qual"}
diff --git a/test/CodeGenOpenCL/opencl_types.cl b/test/CodeGenOpenCL/opencl_types.cl
index ed2bf6d..71d1189 100644
--- a/test/CodeGenOpenCL/opencl_types.cl
+++ b/test/CodeGenOpenCL/opencl_types.cl
@@ -35,3 +35,6 @@
   fnc4smp(glb_smp);
 // CHECK: call void @fnc4smp(i32
 }
+
+void __attribute__((overloadable)) bad1(image1d_t *b, image2d_t *c, image2d_t *d) {}
+// CHECK-LABEL: @{{_Z4bad1P11ocl_image1dP11ocl_image2dS2_|"\\01\?bad1@@YAXPE?APAUocl_image1d@@PE?APAUocl_image2d@@1@Z"}}
diff --git a/test/CodeGenOpenCL/ptx-calls.cl b/test/CodeGenOpenCL/ptx-calls.cl
index 00f2a0e..bde00bc 100644
--- a/test/CodeGenOpenCL/ptx-calls.cl
+++ b/test/CodeGenOpenCL/ptx-calls.cl
@@ -9,5 +9,5 @@
 }
 // CHECK-LABEL: define void @kernel_function()
 // CHECK: call void @device_function()
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @kernel_function, metadata !"kernel", i32 1}
+// CHECK: !{{[0-9]+}} = !{void ()* @kernel_function, !"kernel", i32 1}
 
diff --git a/test/CodeGenOpenCL/ptx-kernels.cl b/test/CodeGenOpenCL/ptx-kernels.cl
index 49d207f..fc6de4f 100644
--- a/test/CodeGenOpenCL/ptx-kernels.cl
+++ b/test/CodeGenOpenCL/ptx-kernels.cl
@@ -8,4 +8,4 @@
 }
 // CHECK-LABEL: define void @kernel_function()
 
-// CHECK: !{{[0-9]+}} = metadata !{void ()* @kernel_function, metadata !"kernel", i32 1}
+// CHECK: !{{[0-9]+}} = !{void ()* @kernel_function, !"kernel", i32 1}
diff --git a/test/CodeGenOpenCL/relaxed-fpmath.cl b/test/CodeGenOpenCL/relaxed-fpmath.cl
new file mode 100644
index 0000000..4222ea9
--- /dev/null
+++ b/test/CodeGenOpenCL/relaxed-fpmath.cl
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s -check-prefix=NORMAL
+// RUN: %clang_cc1 %s -emit-llvm -cl-fast-relaxed-math -o - | FileCheck %s -check-prefix=FAST
+// RUN: %clang_cc1 %s -emit-llvm -cl-finite-math-only -o - | FileCheck %s -check-prefix=FINITE
+// RUN: %clang_cc1 %s -emit-llvm -cl-unsafe-math-optimizations -o - | FileCheck %s -check-prefix=UNSAFE
+// RUN: %clang_cc1 %s -emit-llvm -cl-no-signed-zeros -o - | FileCheck %s -check-prefix=NOSZ
+
+typedef __attribute__(( ext_vector_type(4) )) float float4;
+
+float spscalardiv(float a, float b) {
+  // CHECK: @spscalardiv(
+
+  // NORMAL: fdiv float    
+  // FAST: fdiv fast float
+  // FINITE: fdiv nnan ninf float
+  // UNSAFE: fdiv nnan float
+  // NOSZ: fdiv nsz float
+  return a / b;
+}
+// CHECK: attributes
+
+// NORMAL: "no-infs-fp-math"="false"
+// NORMAL: "no-nans-fp-math"="false"
+// NORMAL: "unsafe-fp-math"="false"
+
+// FAST: "no-infs-fp-math"="true"
+// FAST: "no-nans-fp-math"="true"
+// FAST: "unsafe-fp-math"="true"
+
+// FINITE: "no-infs-fp-math"="true"
+// FINITE: "no-nans-fp-math"="true"
+// FINITE: "unsafe-fp-math"="false"
+
+// UNSAFE: "no-infs-fp-math"="false"
+// UNSAFE: "no-nans-fp-math"="true"
+// UNSAFE: "unsafe-fp-math"="true"
+
diff --git a/test/CodeGenOpenCL/shifts.cl b/test/CodeGenOpenCL/shifts.cl
index 015a777..ab64051 100644
--- a/test/CodeGenOpenCL/shifts.cl
+++ b/test/CodeGenOpenCL/shifts.cl
@@ -1,57 +1,73 @@
-// RUN: %clang_cc1 -x cl -O1 -emit-llvm  %s -o - -triple x86_64-linux-gnu | FileCheck %s
-// OpenCL essentially reduces all shift amounts to the last word-size bits before evaluating.
-// Test this both for variables and constants evaluated in the front-end.
+// RUN: %clang_cc1 -x cl -O1 -emit-llvm  %s -o - -triple x86_64-linux-gnu | FileCheck %s -check-prefix=OPT
+// RUN: %clang_cc1 -x cl -O0 -emit-llvm  %s -o - -triple x86_64-linux-gnu | FileCheck %s -check-prefix=NOOPT
 
+// OpenCL essentially reduces all shift amounts to the last word-size
+// bits before evaluating. Test this both for variables and constants
+// evaluated in the front-end.
 
-//CHECK: @positiveShift32
+// OPT: @gtest1 = constant i64 2147483648
+__constant const unsigned long gtest1 = 1UL << 31;
+
+// NOOPT: @negativeShift32
+int negativeShift32(int a,int b) {
+  // NOOPT: %array0 = alloca [256 x i8]
+  char array0[((int)1)<<40];
+  // NOOPT: %array1 = alloca [256 x i8]
+  char array1[((int)1)<<(-24)];
+
+  // NOOPT: ret i32 65536
+  return ((int)1)<<(-16);
+}
+
+//OPT: @positiveShift32
 int positiveShift32(int a,int b) {
-  //CHECK: [[M32:%.+]] = and i32 %b, 31
-  //CHECK-NEXT: [[C32:%.+]] = shl i32 %a, [[M32]]
+  //OPT: [[M32:%.+]] = and i32 %b, 31
+  //OPT-NEXT: [[C32:%.+]] = shl i32 %a, [[M32]]
   int c = a<<b;
   int d = ((int)1)<<33;
-  //CHECK-NEXT: [[E32:%.+]] = add nsw i32 [[C32]], 2
+  //OPT-NEXT: [[E32:%.+]] = add nsw i32 [[C32]], 2
   int e = c + d;
-  //CHECK-NEXT: ret i32 [[E32]]
+  //OPT-NEXT: ret i32 [[E32]]
   return e;
 }
 
-//CHECK: @positiveShift64
+//OPT: @positiveShift64
 long positiveShift64(long a,long b) {
-  //CHECK: [[M64:%.+]] = and i64 %b, 63
-  //CHECK-NEXT: [[C64:%.+]] = ashr i64 %a, [[M64]]
+  //OPT: [[M64:%.+]] = and i64 %b, 63
+  //OPT-NEXT: [[C64:%.+]] = ashr i64 %a, [[M64]]
   long c = a>>b;
   long d = ((long)8)>>65;
-  //CHECK-NEXT: [[E64:%.+]] = add nsw i64 [[C64]], 4
+  //OPT-NEXT: [[E64:%.+]] = add nsw i64 [[C64]], 4
   long e = c + d;
-  //CHECK-NEXT: ret i64 [[E64]]
+  //OPT-NEXT: ret i64 [[E64]]
   return e;
 }
 
 typedef __attribute__((ext_vector_type(4))) int int4;
 
-//CHECK: @vectorVectorTest
+//OPT: @vectorVectorTest
 int4 vectorVectorTest(int4 a,int4 b) {
-  //CHECK: [[VM:%.+]] = and <4 x i32> %b, <i32 31, i32 31, i32 31, i32 31>
-  //CHECK-NEXT: [[VC:%.+]] = shl <4 x i32> %a, [[VM]]
+  //OPT: [[VM:%.+]] = and <4 x i32> %b, <i32 31, i32 31, i32 31, i32 31>
+  //OPT-NEXT: [[VC:%.+]] = shl <4 x i32> %a, [[VM]]
   int4 c = a << b;
-  //CHECK-NEXT: [[VF:%.+]] = add <4 x i32> [[VC]], <i32 2, i32 4, i32 16, i32 8>
+  //OPT-NEXT: [[VF:%.+]] = add <4 x i32> [[VC]], <i32 2, i32 4, i32 16, i32 8>
   int4 d = {1, 1, 1, 1};
   int4 e = {33, 34, -28, -29};
   int4 f = c + (d << e);
-  //CHECK-NEXT: ret <4 x i32> [[VF]]
+  //OPT-NEXT: ret <4 x i32> [[VF]]
   return f;
 }
 
-//CHECK: @vectorScalarTest
+//OPT: @vectorScalarTest
 int4 vectorScalarTest(int4 a,int b) {
-  //CHECK: [[SP0:%.+]] = insertelement <4 x i32> undef, i32 %b, i32 0
-  //CHECK: [[SP1:%.+]] = shufflevector <4 x i32> [[SP0]], <4 x i32> undef, <4 x i32> zeroinitializer
-  //CHECK: [[VSM:%.+]] = and <4 x i32> [[SP1]], <i32 31, i32 31, i32 31, i32 31>
-  //CHECK-NEXT: [[VSC:%.+]] = shl <4 x i32> %a, [[VSM]]
+  //OPT: [[SP0:%.+]] = insertelement <4 x i32> undef, i32 %b, i32 0
+  //OPT: [[SP1:%.+]] = shufflevector <4 x i32> [[SP0]], <4 x i32> undef, <4 x i32> zeroinitializer
+  //OPT: [[VSM:%.+]] = and <4 x i32> [[SP1]], <i32 31, i32 31, i32 31, i32 31>
+  //OPT-NEXT: [[VSC:%.+]] = shl <4 x i32> %a, [[VSM]]
   int4 c = a << b;
-  //CHECK-NEXT: [[VSF:%.+]] = add <4 x i32> [[VSC]], <i32 4, i32 4, i32 4, i32 4>
+  //OPT-NEXT: [[VSF:%.+]] = add <4 x i32> [[VSC]], <i32 4, i32 4, i32 4, i32 4>
   int4 d = {1, 1, 1, 1};
   int4 f = c + (d << 34);
-  //CHECK-NEXT: ret <4 x i32> [[VSF]]
+  //OPT-NEXT: ret <4 x i32> [[VSF]]
   return f;
 }
diff --git a/test/CodeGenOpenCL/spir-calling-conv.cl b/test/CodeGenOpenCL/spir-calling-conv.cl
new file mode 100644
index 0000000..8fa39fd
--- /dev/null
+++ b/test/CodeGenOpenCL/spir-calling-conv.cl
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -triple "spir-unknown-unknown" -emit-llvm -o - | FileCheck %s
+
+int get_dummy_id(int D);
+
+kernel void bar(global int *A);
+
+kernel void foo(global int *A)
+// CHECK: define spir_kernel void @foo(i32 addrspace(1)* %A)
+{
+  int id = get_dummy_id(0);
+  // CHECK: %{{[a-z0-9_]+}} = tail call spir_func i32 @get_dummy_id(i32 0)
+  A[id] = id;
+  bar(A);
+  // CHECK: tail call spir_kernel void @bar(i32 addrspace(1)* %A)
+}
+
+// CHECK: declare spir_func i32 @get_dummy_id(i32)
+// CHECK: declare spir_kernel void @bar(i32 addrspace(1)*)
diff --git a/test/CoverageMapping/Inputs/code.h b/test/CoverageMapping/Inputs/code.h
index cd3cfb5..609f54a 100644
--- a/test/CoverageMapping/Inputs/code.h
+++ b/test/CoverageMapping/Inputs/code.h
@@ -1,3 +1,5 @@
+// Some code for the middle of a program
+
 x = x;
 if (x == 0) {
   x = 1;
diff --git a/test/CoverageMapping/Inputs/ends_a_scope b/test/CoverageMapping/Inputs/ends_a_scope
new file mode 100644
index 0000000..f6ce61d
--- /dev/null
+++ b/test/CoverageMapping/Inputs/ends_a_scope
@@ -0,0 +1,5 @@
+// This file closes a scope
+
+}
+
+if (true) x = x;
diff --git a/test/CoverageMapping/Inputs/md.def b/test/CoverageMapping/Inputs/md.def
new file mode 100644
index 0000000..fa0fb6b
--- /dev/null
+++ b/test/CoverageMapping/Inputs/md.def
@@ -0,0 +1,5 @@
+
+HANDLE_MD(Val1)
+HANDLE_MD(Val2)
+
+#undef HANDLE_MD
diff --git a/test/CoverageMapping/Inputs/starts_a_scope b/test/CoverageMapping/Inputs/starts_a_scope
new file mode 100644
index 0000000..57c3087
--- /dev/null
+++ b/test/CoverageMapping/Inputs/starts_a_scope
@@ -0,0 +1,4 @@
+// This file opens a new scope
+
+x = x;
+for (int i = 0; i < 2; ++i) {
diff --git a/test/CoverageMapping/break.c b/test/CoverageMapping/break.c
index f5a0af5..99439c8 100644
--- a/test/CoverageMapping/break.c
+++ b/test/CoverageMapping/break.c
@@ -1,29 +1,31 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name break.c %s | FileCheck %s
 
-int main() {         // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+28]]:2 = #0 (HasCodeBefore = 0)
-  int cnt = 0;       // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = #0 (HasCodeBefore = 0)
-  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+3]]:4 = #1 (HasCodeBefore = 0)
+int main() {         // CHECK: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
+  int cnt = 0;       // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = #0
+  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+3]]:4 = #1
     break;
-    ++cnt;           // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = 0 (HasCodeBefore = 0)
-  }                  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = #0 (HasCodeBefore = 0)
-  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+6]]:4 = #2 (HasCodeBefore = 0)
+    ++cnt;           // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+1]]:4 = 0
+  }                  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = #0
+  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+6]]:4 = #2
     {
       break;
-      ++cnt;         // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE+2]]:10 = 0 (HasCodeBefore = 0)
+      ++cnt;         // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE+3]]:4 = 0
     }
     ++cnt;
-  }                  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = ((#0 + #3) - #4) (HasCodeBefore = 0)
-  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+6]]:4 = #3 (HasCodeBefore = 0)
-    if(cnt == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+3]]:6 = #4 (HasCodeBefore = 0)
+  }                  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = ((#0 + #3) - #4)
+  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+7]]:4 = #3
+                     // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:16 = #3
+    if(cnt == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+3]]:6 = #4
       break;
-      ++cnt;         // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:12 = 0 (HasCodeBefore = 0)
+      ++cnt;         // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE+1]]:6 = 0
     }
-    ++cnt;           // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = (#3 - #4) (HasCodeBefore = 0)
-  }                  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = (#0 + #6) (HasCodeBefore = 0)
-  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+7]]:4 = #5 (HasCodeBefore = 0)
-    if(cnt == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+5]]:10 = #6 (HasCodeBefore = 0)
+    ++cnt;           // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+1]]:4 = (#3 - #4)
+  }                  // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:18 = (#0 + #6)
+  while(cnt < 100) { // CHECK-NEXT: File 0, [[@LINE]]:20 -> [[@LINE+8]]:4 = #5
+                     // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:16 = #5
+    if(cnt == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+2]]:6 = #6
       ++cnt;
-    } else {         // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = (#5 - #6) (HasCodeBefore = 0)
+    } else {         // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = (#5 - #6)
       break;
     }
     ++cnt;
diff --git a/test/CoverageMapping/builtinmacro.c b/test/CoverageMapping/builtinmacro.c
index a023abc..80b2672 100644
--- a/test/CoverageMapping/builtinmacro.c
+++ b/test/CoverageMapping/builtinmacro.c
@@ -3,7 +3,7 @@
 // Test the coverage mapping generation for built-in macroes.
 
 // CHECK: filename
-const char *filename (const char *name) { // CHECK-NEXT: File 0, [[@LINE]]:41 -> [[@LINE+3]]:2 = #0 (HasCodeBefore = 0)
+const char *filename (const char *name) { // CHECK-NEXT: File 0, [[@LINE]]:41 -> [[@LINE+3]]:2 = #0
   static const char this_file[] = __FILE__;
   return this_file;
 }
diff --git a/test/CoverageMapping/casts.c b/test/CoverageMapping/casts.c
index 94c13dc..95289f6 100644
--- a/test/CoverageMapping/casts.c
+++ b/test/CoverageMapping/casts.c
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name casts.c %s | FileCheck %s
 
-int main() {                                                   // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+4]]:2 = #0 (HasCodeBefore = 0)
-                                                               // CHECK-NEXT: File 0, [[@LINE+1]]:41 -> [[@LINE+1]]:54 = #1 (HasCodeBefore = 0)
-  int window_size = (sizeof(int) <= 2 ? (unsigned)512 : 1024); // CHECK-NEXT: File 0, [[@LINE]]:57 -> [[@LINE]]:61 = (#0 - #1) (HasCodeBefore = 0)
+int main() {                                                   // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+4]]:2 = #0
+                                                               // CHECK-NEXT: File 0, [[@LINE+1]]:41 -> [[@LINE+1]]:54 = #1
+  int window_size = (sizeof(int) <= 2 ? (unsigned)512 : 1024); // CHECK-NEXT: File 0, [[@LINE]]:57 -> [[@LINE]]:61 = (#0 - #1)
   return 0;
 }
 
diff --git a/test/CoverageMapping/classtemplate.cpp b/test/CoverageMapping/classtemplate.cpp
index 6062266..2e0b507 100644
--- a/test/CoverageMapping/classtemplate.cpp
+++ b/test/CoverageMapping/classtemplate.cpp
@@ -13,25 +13,25 @@
   double bases[BaseCount];
 
                                         // CHECK-CONSTRUCTOR: _ZN4TestIjEC
-  Test() { }                            // CHECK-CONSTRUCTOR: File 0, [[@LINE]]:10 -> [[@LINE]]:13 = #0 (HasCodeBefore = 0)
+  Test() { }                            // CHECK-CONSTRUCTOR: File 0, [[@LINE]]:10 -> [[@LINE]]:13 = #0
 
   // FIXME: It would be nice to emit no-coverage for get, but trying to do this
   // runs afoul of cases like Test3::unmangleable below.
                                         // FIXME-GETTER: _ZNK4TestIjE3get
-  double get(TT position) const {       // FIXME-GETTER: File 0, [[@LINE]]:33 -> [[@LINE+2]]:4 = 0 (HasCodeBefore = 0)
+  double get(TT position) const {       // FIXME-GETTER: File 0, [[@LINE]]:33 -> [[@LINE+2]]:4 = 0
     return bases[position];
   }
                                         // CHECK-SETTER: _ZN4TestIjE3set
-  void set(TT position, double value) { // CHECK-SETTER: File 0, [[@LINE]]:39 -> [[@LINE+2]]:4 = #0 (HasCodeBefore = 0)
+  void set(TT position, double value) { // CHECK-SETTER: File 0, [[@LINE]]:39 -> [[@LINE+2]]:4 = #0
     bases[position] = value;
   }
 };
 
 class Test2 {
                                         // CHECK-CONSTRUCTOR: _ZN5Test2C
-  Test2() { }                           // CHECK-CONSTRUCTOR: File 0, [[@LINE]]:11 -> [[@LINE]]:14 = 0 (HasCodeBefore = 0)
+  Test2() { }                           // CHECK-CONSTRUCTOR: File 0, [[@LINE]]:11 -> [[@LINE]]:14 = 0
                                         // CHECK-GETTER: _ZNK5Test23get
-  double get(unsigned position) const { // CHECK-GETTER: File 0, [[@LINE]]:39 -> [[@LINE+2]]:4 = 0 (HasCodeBefore = 0)
+  double get(unsigned position) const { // CHECK-GETTER: File 0, [[@LINE]]:39 -> [[@LINE+2]]:4 = 0
     return 0.0;
   }
 };
diff --git a/test/CoverageMapping/continue.c b/test/CoverageMapping/continue.c
index b56b164..c86651e 100644
--- a/test/CoverageMapping/continue.c
+++ b/test/CoverageMapping/continue.c
@@ -1,24 +1,24 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name continue.c %s | FileCheck %s
 
-int main() {                    // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+21]]:2 = #0 (HasCodeBefore = 0)
-  int j = 0;                    // CHECK-NEXT: File 0, [[@LINE+2]]:18 -> [[@LINE+2]]:24 = (#0 + #1) (HasCodeBefore = 0)
-                                // CHECK-NEXT: File 0, [[@LINE+1]]:26 -> [[@LINE+1]]:29 = #1 (HasCodeBefore = 0)
-  for(int i = 0; i < 20; ++i) { // CHECK-NEXT: File 0, [[@LINE]]:31 -> [[@LINE+17]]:4 = #1 (HasCodeBefore = 0)
-    if(i < 10) {                // CHECK-NEXT: File 0, [[@LINE]]:16 -> [[@LINE+13]]:6 = #2 (HasCodeBefore = 0)
-      if(i < 5) {               // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+3]]:8 = #3 (HasCodeBefore = 0)
+int main() {                    // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+21]]:2 = #0
+  int j = 0;                    // CHECK-NEXT: File 0, [[@LINE+2]]:18 -> [[@LINE+2]]:24 = (#0 + #1)
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:26 -> [[@LINE+1]]:29 = #1
+  for(int i = 0; i < 20; ++i) { // CHECK-NEXT: File 0, [[@LINE]]:31 -> [[@LINE+17]]:4 = #1
+    if(i < 10) {                // CHECK: File 0, [[@LINE]]:16 -> [[@LINE+13]]:6 = #2
+      if(i < 5) {               // CHECK: File 0, [[@LINE]]:17 -> [[@LINE+3]]:8 = #3
         continue;
-        j = 1;                   // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = 0 (HasCodeBefore = 0)
-      } else {                   // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+7]]:13 = (#2 - #3) (HasCodeBefore = 0)
+        j = 1;                   // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE+1]]:8 = 0
+      } else {                   // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:8 = (#2 - #3)
         j = 2;
       }
-      j = 3;
-      if(i < 7) {                // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+3]]:8 = #4 (HasCodeBefore = 0)
+      j = 3;                     // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE+6]]:6 = (#2 - #3)
+      if(i < 7) {                // CHECK: File 0, [[@LINE]]:17 -> [[@LINE+3]]:8 = #4
         continue;
-        j = 4;                   // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = 0 (HasCodeBefore = 0)
-      } else j = 5;              // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+1]]:12 = ((#2 - #3) - #4) (HasCodeBefore = 0)
-      j = 6;
-    } else                       // CHECK-NEXT: File 0, [[@LINE+1]]:7 -> [[@LINE+1]]:12 = (#1 - #2) (HasCodeBefore = 0)
+        j = 4;                   // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE+1]]:8 = 0
+      } else j = 5;              // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE]]:19 = ((#2 - #3) - #4)
+      j = 6;                     // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE+1]]:6 = ((#2 - #3) - #4)
+    } else                       // CHECK-NEXT: File 0, [[@LINE+1]]:7 -> [[@LINE+1]]:12 = (#1 - #2)
       j = 7;
-    j = 8;                       // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = ((#1 - #3) - #4) (HasCodeBefore = 0)
+    j = 8;                       // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+1]]:4 = ((#1 - #3) - #4)
   }
 }
diff --git a/test/CoverageMapping/header.cpp b/test/CoverageMapping/header.cpp
index c268191..e495d5a 100644
--- a/test/CoverageMapping/header.cpp
+++ b/test/CoverageMapping/header.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name tu1.cpp %s > %tmapping
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name header.cpp %s > %tmapping
 // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-FUNC
 // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-STATIC-FUNC
 // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-STATIC-FUNC2
@@ -11,17 +11,14 @@
 }
 
 // CHECK-FUNC: func
-// CHECK-FUNC: File 0, 4:25 -> 11:2 = #0 (HasCodeBefore = 0)
-// CHECK-FUNC: File 0, 6:15 -> 8:4 = #1 (HasCodeBefore = 0)
-// CHECK-FUNC: File 0, 8:10 -> 10:4 = (#0 - #1) (HasCodeBefore = 0)
-// CHECK-FUNC: Expansion,File 1, 6:10 -> 6:28 = #0 (HasCodeBefore = 0, Expanded file = 0)
+// CHECK-FUNC: File 0, 4:25 -> 11:2 = #0
+// CHECK-FUNC: File 0, 6:15 -> 8:4 = #1
+// CHECK-FUNC: File 0, 8:10 -> 10:4 = (#0 - #1)
 
 // CHECK-STATIC-FUNC: static_func
-// CHECK-STATIC-FUNC: File 0, 12:32 -> 20:2 = #0 (HasCodeBefore = 0)
-// CHECK-STATIC-FUNC: File 0, 14:15 -> 16:4 = #1 (HasCodeBefore = 0)
-// CHECK-STATIC-FUNC: File 0, 16:10 -> 18:4 = (#0 - #1) (HasCodeBefore = 0)
-// CHECK-STATIC-FUNC: Expansion,File 1, 6:10 -> 6:28 = #0 (HasCodeBefore = 0, Expanded file = 0)
+// CHECK-STATIC-FUNC: File 0, 12:32 -> 20:2 = #0
+// CHECK-STATIC-FUNC: File 0, 14:15 -> 16:4 = #1
+// CHECK-STATIC-FUNC: File 0, 16:10 -> 18:4 = (#0 - #1)
 
 // CHECK-STATIC-FUNC2: static_func2
-// CHECK-STATIC-FUNC2: File 0, 21:33 -> 29:2 = 0 (HasCodeBefore = 0)
-// CHECK-STATIC-FUNC2: Expansion,File 1, 6:10 -> 6:28 = 0 (HasCodeBefore = 0, Expanded file = 0)
+// CHECK-STATIC-FUNC2: File 0, 21:33 -> 29:2 = 0
diff --git a/test/CoverageMapping/if.c b/test/CoverageMapping/if.c
index 4767b40..73b2308 100644
--- a/test/CoverageMapping/if.c
+++ b/test/CoverageMapping/if.c
@@ -1,24 +1,28 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name if.c %s | FileCheck %s
 
-int main() {                    // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+21]]:2 = #0 (HasCodeBefore = 0)
+int main() {                    // CHECK: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int i = 0;
-  if(i == 0) i = 1;             // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE]]:19 = #1 (HasCodeBefore = 0)
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i == 0) i = 1;             // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE]]:19 = #1
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
   if(i == 1)
-    i = 2;                      // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = #2 (HasCodeBefore = 0)
-  if(i == 0) { i = 1;           // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #3 (HasCodeBefore = 0)
+    i = 2;                      // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = #2
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i == 0) { i = 1;           // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #3
     i = 2;
   }
-  if(i != 0) {                  // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #4 (HasCodeBefore = 0)
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i != 0) {                  // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #4
     i = 1;
-  } else {                      // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:4 = (#0 - #4) (HasCodeBefore = 0)
+  } else {                      // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:4 = (#0 - #4)
     i = 3;
   }
 
   i = i == 0?
-        i + 1 :                 // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = #5 (HasCodeBefore = 0)
-        i + 2;                  // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = (#0 - #5) (HasCodeBefore = 0)
-                                // CHECK-NEXT: File 0, [[@LINE+1]]:14 -> [[@LINE+1]]:20 = #6 (HasCodeBefore = 0)
-  i = i == 0?i + 12:i + 10;     // CHECK-NEXT: File 0, [[@LINE]]:21 -> [[@LINE]]:27 = (#0 - #6) (HasCodeBefore = 0)
+        i + 1 :                 // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = #5
+        i + 2;                  // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:14 = (#0 - #5)
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:14 -> [[@LINE+1]]:20 = #6
+  i = i == 0?i + 12:i + 10;     // CHECK-NEXT: File 0, [[@LINE]]:21 -> [[@LINE]]:27 = (#0 - #6)
 
   return 0;
 }
diff --git a/test/CoverageMapping/includehell.cpp b/test/CoverageMapping/includehell.cpp
index 653f414..5a9ff78 100644
--- a/test/CoverageMapping/includehell.cpp
+++ b/test/CoverageMapping/includehell.cpp
@@ -1,12 +1,79 @@
-// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name includehell.cpp %s | FileCheck %s
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name includehell.cpp %s > %tmapping
 
-int main() {               // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+4]]:2 = #0 (HasCodeBefore = 0)
+int main() {
   int x = 0;
-  #include "Inputs/code.h" // CHECK-NEXT: Expansion,File 0, [[@LINE]]:12 -> [[@LINE]]:27 = #0 (HasCodeBefore = 0, Expanded file = 1)
+
+  #include "Inputs/starts_a_scope"
+    x = x;
+    #include "Inputs/code.h"
+    x = x;
+  #include "Inputs/ends_a_scope"
+
+  #include "Inputs/starts_a_scope"
+    #include "Inputs/code.h"
+  #include "Inputs/ends_a_scope"
+
+  #include "Inputs/starts_a_scope"
+  #include "Inputs/ends_a_scope"
+
   return 0;
 }
-// CHECK-NEXT: File 1, 1:1 -> 9:7 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 2:13 -> 4:2 = #1 (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 4:8 -> 6:2 = (#0 - #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 7:11 -> 9:2 = #2 (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 9:8 -> 11:2 = (#0 - #2) (HasCodeBefore = 0)
+
+// RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-MAIN
+// RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-START
+// RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-CODE
+// RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-END
+
+// CHECK-MAIN: File [[MAIN:[0-9]]], 3:12 -> 20:2 = #0
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 6:12 -> 6:35 = #0
+// CHECK-MAIN-NEXT: File [[MAIN]], 6:35 -> 10:33 = #1
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 8:14 -> 8:29 = #1
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 10:12 -> 10:33 = #1
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 12:12 -> 12:35 = #0
+// CHECK-MAIN-NEXT: File [[MAIN]], 12:35 -> 14:33 = #5
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 13:14 -> 13:29 = #5
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 14:12 -> 14:33 = #5
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 16:12 -> 16:35 = #0
+// CHECK-MAIN-NEXT: File [[MAIN]], 16:35 -> 17:33 = #9
+// CHECK-MAIN-NEXT: Expansion,File [[MAIN]], 17:12 -> 17:33 = #9
+
+// CHECK-START:      File [[START1:[0-9]]], 1:1 -> 5:1 = #0
+// CHECK-START-NEXT: File [[START1]], 4:17 -> 4:22 = (#0 + #1)
+// CHECK-START-NEXT: File [[START1]], 4:24 -> 4:27 = #1
+// CHECK-START-NEXT: File [[START1]], 4:29 -> 5:1 = #1
+// CHECK-START:      File [[START2:[0-9]]], 1:1 -> 5:1 = #0
+// CHECK-START-NEXT: File [[START2]], 4:17 -> 4:22 = (#0 + #5)
+// CHECK-START-NEXT: File [[START2]], 4:24 -> 4:27 = #5
+// CHECK-START-NEXT: File [[START2]], 4:29 -> 5:1 = #5
+// CHECK-START:      File [[START3:[0-9]]], 1:1 -> 5:1 = #0
+// CHECK-START-NEXT: File [[START3]], 4:17 -> 4:22 = (#0 + #9)
+// CHECK-START-NEXT: File [[START3]], 4:24 -> 4:27 = #9
+// CHECK-START-NEXT: File [[START3]], 4:29 -> 5:1 = #9
+
+// CHECK-CODE:      File [[CODE1:[0-9]]], 1:1 -> 14:1 = #1
+// CHECK-CODE-NEXT: File [[CODE1]], 4:5 -> 4:11 = #1
+// CHECK-CODE-NEXT: File [[CODE1]], 4:13 -> 6:2 = #2
+// CHECK-CODE-NEXT: File [[CODE1]], 6:8 -> 8:2 = (#1 - #2)
+// CHECK-CODE-NEXT: File [[CODE1]], 9:5 -> 9:9 = #1
+// CHECK-CODE-NEXT: File [[CODE1]], 9:11 -> 11:2 = #3
+// CHECK-CODE-NEXT: File [[CODE1]], 11:8 -> 13:2 = (#1 - #3)
+// CHECK-CODE:      File [[CODE2:[0-9]]], 1:1 -> 14:1 = #5
+// CHECK-CODE-NEXT: File [[CODE2]], 4:5 -> 4:11 = #5
+// CHECK-CODE-NEXT: File [[CODE2]], 4:13 -> 6:2 = #6
+// CHECK-CODE-NEXT: File [[CODE2]], 6:8 -> 8:2 = (#5 - #6)
+// CHECK-CODE-NEXT: File [[CODE2]], 9:5 -> 9:9 = #5
+// CHECK-CODE-NEXT: File [[CODE2]], 9:11 -> 11:2 = #7
+// CHECK-CODE-NEXT: File [[CODE2]], 11:8 -> 13:2 = (#5 - #7)
+
+// CHECK-END:      File [[END1:[0-9]]], 1:1 -> 3:2 = #1
+// CHECK-END-NEXT: File [[END1]], 1:1 -> 6:1 = #0
+// CHECK-END-NEXT: File [[END1]], 5:5 -> 5:9 = #0
+// CHECK-END-NEXT: File [[END1]], 5:11 -> 5:16 = #4
+// CHECK-END:      File [[END2:[0-9]]], 1:1 -> 3:2 = #5
+// CHECK-END-NEXT: File [[END2]], 1:1 -> 6:1 = #0
+// CHECK-END-NEXT: File [[END2]], 5:5 -> 5:9 = #0
+// CHECK-END-NEXT: File [[END2]], 5:11 -> 5:16 = #8
+// CHECK-END:      File [[END3:[0-9]]], 1:1 -> 3:2 = #9
+// CHECK-END-NEXT: File [[END3]], 1:1 -> 6:1 = #0
+// CHECK-END-NEXT: File [[END3]], 5:5 -> 5:9 = #0
+// CHECK-END-NEXT: File [[END3]], 5:11 -> 5:16 = #10
diff --git a/test/CoverageMapping/label.cpp b/test/CoverageMapping/label.cpp
index d936260..52618f7 100644
--- a/test/CoverageMapping/label.cpp
+++ b/test/CoverageMapping/label.cpp
@@ -1,63 +1,65 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name label.cpp %s | FileCheck %s
 
                              // CHECK: func
-void func() {                // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE+18]]:2 = #0 (HasCodeBefore = 0)
-  int i = 0;                 // CHECK-NEXT: File 0, [[@LINE+2]]:14 -> [[@LINE+2]]:20 = (#0 + #3) (HasCodeBefore = 0)
-                             // CHECK-NEXT: File 0, [[@LINE+1]]:22 -> [[@LINE+1]]:25 = #3 (HasCodeBefore = 0)
-  for(i = 0; i < 10; ++i) {  // CHECK-NEXT: File 0, [[@LINE]]:27 -> [[@LINE+10]]:4 = #1 (HasCodeBefore = 0)
-    if(i < 5) {              // CHECK-NEXT: File 0, [[@LINE]]:15 -> [[@LINE+6]]:6 = #2 (HasCodeBefore = 0)
+void func() {                // CHECK-NEXT: File 0, [[@LINE]]:13 -> {{[0-9]+}}:2 = #0
+  int i = 0;                 // CHECK-NEXT: File 0, [[@LINE+2]]:14 -> [[@LINE+2]]:20 = (#0 + #3)
+                             // CHECK-NEXT: File 0, [[@LINE+1]]:22 -> [[@LINE+1]]:25 = #3
+  for(i = 0; i < 10; ++i) {  // CHECK-NEXT: File 0, [[@LINE]]:27 -> [[@LINE+11]]:4 = #1
+                             // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:13 = #1
+    if(i < 5) {              // CHECK-NEXT: File 0, [[@LINE]]:15 -> [[@LINE+6]]:6 = #2
       {
-        x:                   // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE+6]]:14 = #3 (HasCodeBefore = 0)
+        x:                   // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE+4]]:6 = #3
           int j = 1;
       }
       int m = 2;
     } else
-      goto x;                // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:13 = (#1 - #2) (HasCodeBefore = 0)
-    int k = 3;
+      goto x;                // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:13 = (#1 - #2)
+    int k = 3;               // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+1]]:4 = #3
   }
-  static int j = 0;          // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:12 = ((#0 + #3) - #1) (HasCodeBefore = 0)
+  static int j = 0;          // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+4]]:2 = ((#0 + #3) - #1)
   ++j;
-  if(j == 1)
-    goto x;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #4 (HasCodeBefore = 0)
+  if(j == 1)                 // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:12 = ((#0 + #3) - #1)
+    goto x;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #4
 }
 
                              // CHECK-NEXT: test1
-void test1(int x) {          // CHECK-NEXT: File 0, [[@LINE]]:19 -> [[@LINE+7]]:2 = #0 (HasCodeBefore = 0)
-  if(x == 0)
-    goto a;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #1 (HasCodeBefore = 0)
-  goto b;                    // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:9 = (#0 - #1) (HasCodeBefore = 0)
-a:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE]]:2 = #2 (HasCodeBefore = 0)
-b:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE+1]]:12 = #3 (HasCodeBefore = 0)
+void test1(int x) {          // CHECK-NEXT: File 0, [[@LINE]]:19 -> {{[0-9]+}}:2 = #0
+  if(x == 0)                 // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:12 = #0
+    goto a;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #1
+  goto b;                    // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:9 = (#0 - #1)
+a:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE+3]]:2 = #2
+b:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE+2]]:2 = #3
   x = x + 1;
 }
 
                              // CHECK-NEXT: test2
-void test2(int x) {          // CHECK-NEXT: File 0, [[@LINE]]:19 -> [[@LINE+8]]:2 = #0 (HasCodeBefore = 0)
-  if(x == 0)
-    goto a;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #1 (HasCodeBefore = 0)
-                             // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:17 = (#0 - #1) (HasCodeBefore = 0)
-  else if(x == 1) goto b;    // CHECK-NEXT: File 0, [[@LINE]]:19 -> [[@LINE]]:25 = #2 (HasCodeBefore = 0)
-a:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE]]:2 = #3 (HasCodeBefore = 0)
-b:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE+1]]:12 = #4 (HasCodeBefore = 0)
+void test2(int x) {          // CHECK-NEXT: File 0, [[@LINE]]:19 -> {{[0-9]+}}:2 = #0
+  if(x == 0)                 // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:12 = #0
+    goto a;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = #1
+                             // CHECK-NEXT: File 0, [[@LINE+2]]:8 -> [[@LINE+2]]:25 = (#0 - #1)
+                             // CHECK-NEXT: File 0, [[@LINE+1]]:11 -> [[@LINE+1]]:17 = (#0 - #1)
+  else if(x == 1) goto b;    // CHECK-NEXT: File 0, [[@LINE]]:19 -> [[@LINE]]:25 = #2
+a:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE+3]]:2 = #3
+b:                           // CHECK-NEXT: File 0, [[@LINE]]:1 -> [[@LINE+2]]:2 = #4
   x = x + 1;
 }
 
                              // CHECK-NEXT: main
-int main() {                 // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+17]]:2 = #0 (HasCodeBefore = 0)
+int main() {                 // CHECK-NEXT: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int j = 0;
-  for(int i = 0; i < 10; ++i) { // CHECK: File 0, [[@LINE]]:31 -> [[@LINE+11]]:4 = #1 (HasCodeBefore = 0)
-  a:                         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:13 = #2 (HasCodeBefore = 0)
-    if(i < 3)
-      goto e;                // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:13 = #3 (HasCodeBefore = 0)
-    goto c;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = (#2 - #3) (HasCodeBefore = 0)
-  b:                         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #4 (HasCodeBefore = 0)
+  for(int i = 0; i < 10; ++i) { // CHECK: File 0, [[@LINE]]:31 -> [[@LINE+11]]:4 = #1
+  a:                         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+10]]:4 = #2
+    if(i < 3)                // CHECK-NEXT: File 0, [[@LINE]]:8 -> [[@LINE]]:13 = #2
+      goto e;                // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:13 = #3
+    goto c;                  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:11 = (#2 - #3)
+  b:                         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:4 = #4
     j = 2;
-  c:                         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #5 (HasCodeBefore = 0)
+  c:                         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+4]]:4 = #5
     j = 1;
-                             // CHECK-NEXT: File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:4 = #6 (HasCodeBefore = 0)
-  e: f: ;                    // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:10 = #7 (HasCodeBefore = 0)
+                             // CHECK-NEXT: File 0, [[@LINE+1]]:3 -> [[@LINE+2]]:4 = #6
+  e: f: ;                    // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE+1]]:4 = #7
   }
-  func();                    // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:11 = ((#0 + #7) - #1) (HasCodeBefore = 0)
+  func();                    // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:2 = ((#0 + #7) - #1)
   test1(0);
   test2(2);
 }
diff --git a/test/CoverageMapping/lambda.cpp b/test/CoverageMapping/lambda.cpp
new file mode 100644
index 0000000..fb018e6
--- /dev/null
+++ b/test/CoverageMapping/lambda.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -x c++ -std=c++11 -triple %itanium_abi_triple -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only %s -main-file-name lambda.cpp | FileCheck %s
+
+// CHECK-LABEL: _Z3fooi:
+void foo(int i) { // CHECK: File 0, [[@LINE]]:17 -> {{[0-9]+}}:2 = #0
+  auto f = [](int x) {
+    return x + 1;
+  };
+
+  f(i);
+  // Make sure the zero region after the return doesn't escape the lambda.
+  // CHECK-NOT: File 0, {{[0-9:]+}} -> [[@LINE+1]]:2 = 0
+}
+
+int main(int argc, const char *argv[]) {
+  foo(1);
+  return 0;
+}
diff --git a/test/CoverageMapping/logical.cpp b/test/CoverageMapping/logical.cpp
index 0971c75..ece3102 100644
--- a/test/CoverageMapping/logical.cpp
+++ b/test/CoverageMapping/logical.cpp
@@ -1,13 +1,13 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name logical.cpp %s | FileCheck %s
 
-int main() {                        // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+10]]:2 = #0 (HasCodeBefore = 0)
+int main() {                        // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+10]]:2 = #0
   bool bt = true;
   bool bf = false;
-  bool a = bt && bf;                // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE]]:20 = #1 (HasCodeBefore = 0)
+  bool a = bt && bf;                // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE]]:20 = #1
   a = bt &&
-      bf;                           // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:9 = #2 (HasCodeBefore = 0)
-  a = bf || bt;                     // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE]]:15 = #3 (HasCodeBefore = 0)
+      bf;                           // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:9 = #2
+  a = bf || bt;                     // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE]]:15 = #3
   a = bf ||
-      bt;                           // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:9 = #4 (HasCodeBefore = 0)
+      bt;                           // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:9 = #4
   return 0;
 }
diff --git a/test/CoverageMapping/loopmacro.c b/test/CoverageMapping/loopmacro.c
index 8480dbd..bbd0c45 100644
--- a/test/CoverageMapping/loopmacro.c
+++ b/test/CoverageMapping/loopmacro.c
@@ -1,40 +1,47 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name loopmacro.c %s | FileCheck %s
 
-#   define HASH_BITS  15
-#define MIN_MATCH  3
-#define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
-#define WMASK 0xFFFF
-#define HASH_MASK 0xFFFF
-#define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
+// CHECK: main
+// CHECK-NEXT: File 0, {{[0-9]+}}:12 -> {{[0-9]+}}:2 = #0
+// CHECK-NEXT: File 0, {{[0-9]+}}:6 -> {{[0-9]+}}:4 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 0, {{[0-9]+}}:7 -> {{[0-9]+}}:20 = (#0 + #1)
+// CHECK-NEXT: File 0, {{[0-9]+}}:12 -> {{[0-9]+}}:30 = (#0 + #1)
+
+// CHECK-NEXT: File 1, [[@LINE+4]]:4 -> [[@LINE+6]]:23 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 1, [[@LINE+3]]:5 -> [[@LINE+3]]:16 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 1, [[@LINE+3]]:16 -> [[@LINE+3]]:21 = (#0 + #1)
 #define INSERT_STRING(s, match_head) \
    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
     prev[(s) & WMASK] = match_head = head[ins_h], \
     head[ins_h] = (s))
+// CHECK-NEXT: File 2, [[@LINE+3]]:26 -> [[@LINE+3]]:66 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 2, [[@LINE+2]]:38 -> [[@LINE+2]]:45 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 2, [[@LINE+1]]:56 -> [[@LINE+1]]:65 = (#0 + #1)
+#define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
+// CHECK-NEXT: File 3, [[@LINE+1]]:15 -> [[@LINE+1]]:21 = (#0 + #1)
+#define WMASK 0xFFFF
+// CHECK-NEXT: File 4, [[@LINE+4]]:18 -> [[@LINE+4]]:53 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 4, [[@LINE+3]]:20 -> [[@LINE+3]]:29 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 4, [[@LINE+2]]:30 -> [[@LINE+2]]:39 = (#0 + #1)
+// CHECK-NEXT: Expansion,File 4, [[@LINE+1]]:43 -> [[@LINE+1]]:52 = (#0 + #1)
+#define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
+// CHECK-NEXT: File 5, [[@LINE+1]]:19 -> [[@LINE+1]]:25 = (#0 + #1)
+#define HASH_MASK 0xFFFF
+// CHECK-NEXT: File 6, [[@LINE+1]]:20 -> [[@LINE+1]]:22 = (#0 + #1)
+#define HASH_BITS  15
+// CHECK-NEXT: File 7, [[@LINE+2]]:20 -> [[@LINE+2]]:21 = (#0 + #1)
+// CHECK-NEXT: File 8, [[@LINE+1]]:20 -> [[@LINE+1]]:21 = (#0 + #1)
+#define MIN_MATCH  3
 
-int main() {                                // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+12]]:2 = #0 (HasCodeBefore = 0)
+int main() {
   int strstart = 0;
   int hash_head = 2;
   int prev_length = 5;
   int ins_h = 1;
-  int prev[32] = { 0 };
-  int head[32] = { 0 };
+  int prev[32<<10] = { 0 };
+  int head[32<<10] = { 0 };
   int window[1024] = { 0 };
-  do {                                     // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE+3]]:30 = (#0 + #1) (HasCodeBefore = 0)
+  do {
       strstart++;
-      INSERT_STRING(strstart, hash_head);  // CHECK-NEXT: Expansion,File 0, [[@LINE]]:7 -> [[@LINE]]:20 = (#0 + #1) (HasCodeBefore = 0, Expanded file = 1)
+      INSERT_STRING(strstart, hash_head);
   } while (--prev_length != 0);
 }
-// CHECK-NEXT: File 0, 24:21 -> 24:29 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 0, 24:21 -> 24:29 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 0, 24:21 -> 24:29 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 0, 24:31 -> 24:40 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 10:4 -> 12:23 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 1, 10:5 -> 10:16 = (#0 + #1) (HasCodeBefore = 0, Expanded file = 2)
-// CHECK-NEXT: File 1, 10:17 -> 10:22 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 10:17 -> 10:22 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 10:24 -> 10:32 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 10:33 -> 10:36 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 10:46 -> 10:49 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: File 2, 8:26 -> 8:66 = (#0 + #1) (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 2, 8:38 -> 8:45 = (#0 + #1) (HasCodeBefore = 0, Expanded file = 3)
-// CHECK-NEXT: File 3, 5:18 -> 5:53 = (#0 + #1) (HasCodeBefore = 0)
diff --git a/test/CoverageMapping/loops.cpp b/test/CoverageMapping/loops.cpp
index 81fad91..d619879 100644
--- a/test/CoverageMapping/loops.cpp
+++ b/test/CoverageMapping/loops.cpp
@@ -1,37 +1,37 @@
 // RUN: %clang_cc1 -std=c++11 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name loops.cpp %s | FileCheck %s
 
                                     // CHECK: rangedFor
-void rangedFor() {                  // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+6]]:2 = #0 (HasCodeBefore = 0)
+void rangedFor() {                  // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+6]]:2 = #0
   int arr[] = { 1, 2, 3, 4, 5 };
   int sum = 0;
-  for(auto i : arr) {               // CHECK-NEXT: File 0, [[@LINE]]:21 -> [[@LINE+2]]:4 = #1 (HasCodeBefore = 0)
+  for(auto i : arr) {               // CHECK-NEXT: File 0, [[@LINE]]:21 -> [[@LINE+2]]:4 = #1
     sum += i;
   }
 }
 
                                     // CHECK-NEXT: main
-int main() {                        // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+24]]:2 = #0 (HasCodeBefore = 0)
-                                    // CHECK-NEXT: File 0, [[@LINE+1]]:18 -> [[@LINE+1]]:24 = (#0 + #1) (HasCodeBefore = 0)
-  for(int i = 0; i < 10; ++i)       // CHECK-NEXT: File 0, [[@LINE]]:26 -> [[@LINE]]:29 = #1 (HasCodeBefore = 0)
-     ;                              // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:7 = #1 (HasCodeBefore = 0)
+int main() {                        // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+24]]:2 = #0
+                                    // CHECK-NEXT: File 0, [[@LINE+1]]:18 -> [[@LINE+1]]:24 = (#0 + #1)
+  for(int i = 0; i < 10; ++i)       // CHECK-NEXT: File 0, [[@LINE]]:26 -> [[@LINE]]:29 = #1
+     ;                              // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:7 = #1
   for(int i = 0;
-      i < 10;                       // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:13 = (#0 + #2) (HasCodeBefore = 0)
-      ++i)                          // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:10 = #2 (HasCodeBefore = 0)
-  {                                 // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:4 = #2 (HasCodeBefore = 0)
+      i < 10;                       // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:13 = (#0 + #2)
+      ++i)                          // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:10 = #2
+  {                                 // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:4 = #2
     int x = 0;
   }
-  int j = 0;                        // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:14 = (#0 + #3) (HasCodeBefore = 0)
-  while(j < 5) ++j;                 // CHECK-NEXT: File 0, [[@LINE]]:16 -> [[@LINE]]:19 = #3 (HasCodeBefore = 0)
-  do {                              // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE+2]]:17 = (#0 + #4) (HasCodeBefore = 0)
+  int j = 0;                        // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:14 = (#0 + #3)
+  while(j < 5) ++j;                 // CHECK-NEXT: File 0, [[@LINE]]:16 -> [[@LINE]]:19 = #3
+  do {                              // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE+2]]:4 = (#0 + #4)
     ++j;
-  } while(j < 10);
+  } while(j < 10);                  // CHECK-NEXT: File 0, [[@LINE]]:11 -> [[@LINE]]:17 = (#0 + #4)
   j = 0;
   while
-   (j < 5)                          // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = (#0 + #5) (HasCodeBefore = 0)
-     ++j;                           // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:9 = #5 (HasCodeBefore = 0)
+   (j < 5)                          // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = (#0 + #5)
+     ++j;                           // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:9 = #5
   do
-    ++j;                            // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+1]]:15 = (#0 + #6) (HasCodeBefore = 0)
-  while(j < 10);
+    ++j;                            // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:8 = (#0 + #6)
+  while(j < 10);                    // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:15 = (#0 + #6)
   rangedFor();
   return 0;
 }
diff --git a/test/CoverageMapping/macro-expansion.c b/test/CoverageMapping/macro-expansion.c
new file mode 100644
index 0000000..e87f444
--- /dev/null
+++ b/test/CoverageMapping/macro-expansion.c
@@ -0,0 +1,58 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macro-expansion.c %s | FileCheck %s
+
+// CHECK: func
+// CHECK:      File 1, [[@LINE+5]]:12 -> [[@LINE+5]]:38 = #0
+// CHECK-NEXT: File 1, [[@LINE+4]]:15 -> [[@LINE+4]]:28 = (#0 + #2)
+// CHECK-NEXT: File 1, [[@LINE+3]]:21 -> [[@LINE+3]]:22 = (#0 + #2)
+// CHECK-NEXT: File 1, [[@LINE+2]]:24 -> [[@LINE+2]]:26 = #3
+// CHECK-NEXT: File 1, [[@LINE+1]]:36 -> [[@LINE+1]]:37 = (#0 + #2)
+#define M1 do { if (0) {} } while (0)
+// CHECK-NEXT: File 2, [[@LINE+10]]:15 -> [[@LINE+10]]:41 = #0
+// CHECK-NEXT: File 2, [[@LINE+9]]:18 -> [[@LINE+9]]:31 = (#0 + #4)
+// CHECK-NEXT: File 2, [[@LINE+8]]:24 -> [[@LINE+8]]:25 = (#0 + #4)
+// CHECK-NEXT: File 2, [[@LINE+7]]:27 -> [[@LINE+7]]:29 = #5
+// CHECK-NEXT: File 2, [[@LINE+6]]:39 -> [[@LINE+6]]:40 = (#0 + #4)
+// CHECK-NEXT: File 3, [[@LINE+5]]:15 -> [[@LINE+5]]:41 = #0
+// CHECK-NEXT: File 3, [[@LINE+4]]:18 -> [[@LINE+4]]:31 = (#0 + #6)
+// CHECK-NEXT: File 3, [[@LINE+3]]:24 -> [[@LINE+3]]:25 = (#0 + #6)
+// CHECK-NEXT: File 3, [[@LINE+2]]:27 -> [[@LINE+2]]:29 = #7
+// CHECK-NEXT: File 3, [[@LINE+1]]:39 -> [[@LINE+1]]:40 = (#0 + #6)
+#define M2(x) do { if (x) {} } while (0)
+// CHECK-NEXT: File 4, [[@LINE+4]]:15 -> [[@LINE+4]]:38 = #0
+// CHECK-NEXT: File 4, [[@LINE+3]]:18 -> [[@LINE+3]]:28 = (#0 + #8)
+// CHECK-NEXT: Expansion,File 4, [[@LINE+2]]:20 -> [[@LINE+2]]:22 = (#0 + #8)
+// CHECK-NEXT: File 4, [[@LINE+1]]:36 -> [[@LINE+1]]:37 = (#0 + #8)
+#define M3(x) do { M2(x); } while (0)
+// CHECK-NEXT: File 5, [[@LINE+2]]:15 -> [[@LINE+2]]:27 = #0
+// CHECK-NEXT: File 5, [[@LINE+1]]:23 -> [[@LINE+1]]:26 = #12
+#define M4(x) ((x) && (x))
+// CHECK-NEXT: File 6, [[@LINE+2]]:15 -> [[@LINE+2]]:27 = #0
+// CHECK-NEXT: File 6, [[@LINE+1]]:23 -> [[@LINE+1]]:26 = #14
+#define M5(x) ((x) || (x))
+// CHECK-NEXT: File 7, [[@LINE+1]]:15 -> [[@LINE+1]]:26 = #0
+#define M6(x) ((x) + (x))
+// CHECK-NEXT: File 8, [[@LINE+1]]:15 -> [[@LINE+1]]:18 = #0
+#define M7(x) (x)
+
+// Check for the expansion of M2 within M3.
+// CHECK-NEXT: File 9, {{[0-9]+}}:15 -> {{[0-9]+}}:41 = (#0 + #8)
+// CHECK-NEXT: File 9, {{[0-9]+}}:18 -> {{[0-9]+}}:31 = ((#0 + #8) + #9)
+// CHECK-NEXT: File 9, {{[0-9]+}}:24 -> {{[0-9]+}}:25 = ((#0 + #8) + #9)
+// CHECK-NEXT: File 9, {{[0-9]+}}:27 -> {{[0-9]+}}:29 = #10
+// CHECK-NEXT: File 9, {{[0-9]+}}:39 -> {{[0-9]+}}:40 = ((#0 + #8) + #9)
+
+void func(int x) {
+  if (x) {}
+  M1;
+  M2(!x);
+  M2(x);
+  M3(x);
+  if (M4(x)) {}
+  if (M5(x)) {}
+  if (M6(x)) {}
+  if (M7(x)) {}
+}
+
+int main(int argc, const char *argv[]) {
+  func(0);
+}
diff --git a/test/CoverageMapping/macro-expressions.cpp b/test/CoverageMapping/macro-expressions.cpp
new file mode 100644
index 0000000..00e273b
--- /dev/null
+++ b/test/CoverageMapping/macro-expressions.cpp
@@ -0,0 +1,76 @@
+// RUN: %clang_cc1 -std=c++11 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macro-expressions.cpp %s | FileCheck %s
+
+#define EXPR(x) (x)
+#define NEXPR(x) (!x)
+#define DECL(T, x) T x
+#define ASSIGN(x, y) x = y
+#define LT(x, y) x < y
+#define INC(x) ++x
+#define ARR(T, x, y, z) (T[3]){x, y, z}
+
+#define PRI_64_LENGTH_MODIFIER "ll"
+#define PRIo64 PRI_64_LENGTH_MODIFIER "o"
+#define PRIu64 PRI_64_LENGTH_MODIFIER "u"
+
+// CHECK: foo
+// CHECK-NEXT: File 0, [[@LINE+1]]:17 -> {{[0-9]+}}:2 = #0
+void foo(int i) {
+  // CHECK-NEXT: File 0, [[@LINE+2]]:7 -> [[@LINE+2]]:8 = #0
+  // CHECK-NEXT: File 0, [[@LINE+1]]:10 -> [[@LINE+1]]:12 = #1
+  if (0) {}
+
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:7 -> [[@LINE+2]]:11 = #0
+  // CHECK-NEXT: File 0, [[@LINE+1]]:16 -> [[@LINE+1]]:18 = #2
+  if (EXPR(i)) {}
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:9 -> [[@LINE+2]]:14 = (#0 + #3)
+  // CHECK-NEXT: File 0, [[@LINE+1]]:20 -> [[@LINE+1]]:22 = #3
+  for (;NEXPR(i);) {}
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+4]]:8 -> [[@LINE+4]]:14 = #0
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:33 -> [[@LINE+3]]:35 = (#0 + #4)
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:43 -> [[@LINE+2]]:46 = #4
+  // CHECK-NEXT: File 0, [[@LINE+1]]:51 -> [[@LINE+1]]:53 = #4
+  for (ASSIGN(DECL(int, j), 0); LT(j, i); INC(j)) {}
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:9 = #0
+  ASSIGN(DECL(int, k), 0);
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:10 -> [[@LINE+3]]:12 = (#0 + #5)
+  // CHECK-NEXT: File 0, [[@LINE+2]]:20 -> [[@LINE+2]]:31 = #5
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:22 -> [[@LINE+1]]:25 = #5
+  while (LT(k, i)) { INC(k); }
+  // CHECK-NEXT: File 0, [[@LINE+2]]:6 -> [[@LINE+2]]:8 = (#0 + #6)
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:16 -> [[@LINE+1]]:21 = (#0 + #6)
+  do {} while (NEXPR(i));
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:8 -> [[@LINE+3]]:12 = #0
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:23 -> [[@LINE+2]]:26 = #0
+  // CHECK-NEXT: File 0, [[@LINE+1]]:42 -> [[@LINE+1]]:44 = #7
+  for (DECL(int, j) : ARR(int, 1, 2, 3)) {}
+
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:14 -> [[@LINE+2]]:20 = #8
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:23 -> [[@LINE+1]]:29 = #0
+  (void)(i ? PRIo64 : PRIu64);
+}
+
+// CHECK-NEXT: File {{[0-9]+}}, 3:17 -> 3:20 = #0
+// CHECK-NEXT: File {{[0-9]+}}, 4:18 -> 4:22 = (#0 + #3)
+// CHECK-NEXT: File {{[0-9]+}}, 6:22 -> 6:27 = #0
+// CHECK-NEXT: File {{[0-9]+}}, 8:16 -> 8:19 = #4
+// CHECK-NEXT: File {{[0-9]+}}, 7:18 -> 7:23 = (#0 + #4)
+// CHECK-NEXT: File {{[0-9]+}}, 6:22 -> 6:27 = #0
+// CHECK-NEXT: File {{[0-9]+}}, 8:16 -> 8:19 = #5
+// CHECK-NEXT: File {{[0-9]+}}, 7:18 -> 7:23 = (#0 + #5)
+// CHECK-NEXT: File {{[0-9]+}}, 4:18 -> 4:22 = (#0 + #6)
+// CHECK-NEXT: File {{[0-9]+}}, 5:20 -> 5:23 = #0
+// CHECK-NEXT: File {{[0-9]+}}, 9:25 -> 9:40 = #0
+// CHECK-NEXT: Expansion,File {{[0-9]+}}, 12:16 -> 12:38 = #8
+// CHECK-NEXT: File {{[0-9]+}}, 12:38 -> 12:42 = #8
+// CHECK-NEXT: File {{[0-9]+}}, 13:16 -> 13:42 = #0
+// CHECK-NEXT: Expansion,File {{[0-9]+}}, 13:16 -> 13:38 = (#0 - #8)
+// CHECK-NEXT: File {{[0-9]+}}, 13:38 -> 13:42 = (#0 - #8)
+// CHECK-NEXT: File {{[0-9]+}}, 11:32 -> 11:36 = #8
+// CHECK-NEXT: File {{[0-9]+}}, 11:32 -> 11:36 = (#0 - #8)
+
+// CHECK-NOT: File {{[0-9]+}},
+// CHECK: main
+
+int main(int argc, const char *argv[]) {
+  foo(10);
+}
diff --git a/test/CoverageMapping/macroception.c b/test/CoverageMapping/macroception.c
index edbd84a..bde38ff 100644
--- a/test/CoverageMapping/macroception.c
+++ b/test/CoverageMapping/macroception.c
@@ -6,35 +6,47 @@
 #define M11 M22
 
 // CHECK-LABEL: main:
-int main() M1       // CHECK-NEXT: Expansion,File 0, [[@LINE]]:12 -> [[@LINE]]:14 = #0 (HasCodeBefore = 0, Expanded file = 2)
-  return 0;         // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #0 (HasCodeBefore = 0)
+// CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:12 -> [[@LINE+2]]:14 = #0
+// CHECK-NEXT: File 0, [[@LINE+1]]:14 -> [[@LINE+3]]:2 = #0
+int main() M1
+  return 0;
 }
-// CHECK-NEXT: File 1, 3:12 -> 3:13 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 2, 4:12 -> 4:14 = #0 (HasCodeBefore = 0, Expanded file = 1)
-
+// CHECK-NEXT: File 1, 4:12 -> 4:14 = #0
+// CHECK-NEXT: Expansion,File 1, 4:12 -> 4:14 = #0
+// CHECK-NEXT: File 2, 3:12 -> 3:13 = #0
 
 // CHECK-LABEL: func2:
-void func2() {      // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+1]]:12 = #0 (HasCodeBefore = 0)
+// CHECK-NEXT: File 0, [[@LINE+2]]:14 -> [[@LINE+4]]:4 = #0
+// CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:1 -> [[@LINE+3]]:4 = #0
+void func2() {
   int x = 0;
-M11                 // CHECK-NEXT: Expansion,File 0, [[@LINE]]:1 -> [[@LINE]]:4 = #0 (HasCodeBefore = 0, Expanded file = 2)
-// CHECK-NEXT: File 1, 5:13 -> 5:14 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 2, 6:13 -> 6:16 = #0 (HasCodeBefore = 0, Expanded file = 1)
+M11
+// CHECK-NEXT: File 1, 6:13 -> 6:16 = #0
+// CHECK-NEXT: Expansion,File 1, 6:13 -> 6:16 = #0
+// CHECK-NEXT: File 2, 5:13 -> 5:14 = #0
 
 // CHECK-LABEL: func3:
-void func3() M1     // CHECK-NEXT: Expansion,File 0, [[@LINE]]:14 -> [[@LINE]]:16 = #0 (HasCodeBefore = 0, Expanded file = 2)
-  int x = 0;        // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:12 = #0 (HasCodeBefore = 0)
-M11                 // CHECK-NEXT: Expansion,File 0, [[@LINE]]:1 -> [[@LINE]]:4 = #0 (HasCodeBefore = 0, Expanded file = 4)
-
-// CHECK-NEXT: File 1, 3:12 -> 3:13 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 2, 4:12 -> 4:14 = #0 (HasCodeBefore = 0, Expanded file = 1)
-// CHECK-NEXT: File 3, 5:13 -> 5:14 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 4, 6:13 -> 6:16 = #0 (HasCodeBefore = 0, Expanded file = 3)
+// CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:14 -> [[@LINE+3]]:16 = #0
+// CHECK-NEXT: File 0, [[@LINE+2]]:16 -> [[@LINE+4]]:4 = #0
+// CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:1 -> [[@LINE+3]]:4 = #0
+void func3() M1
+  int x = 0;
+M11
+// CHECK-NEXT: File 1, 4:12 -> 4:14 = #0
+// CHECK-NEXT: Expansion,File 1, 4:12 -> 4:14 = #0
+// CHECK-NEXT: File 2, 6:13 -> 6:16 = #0
+// CHECK-NEXT: Expansion,File 2, 6:13 -> 6:16 = #0
+// CHECK-NEXT: File 3, 3:12 -> 3:13 = #0
+// CHECK-NEXT: File 4, 5:13 -> 5:14 = #0
 
 // CHECK-LABEL: func4:
-// CHECK-NEXT: File 0, 3:12 -> 3:13 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 1, 4:12 -> 4:14 = #0 (HasCodeBefore = 0, Expanded file = 0)
+// CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:14 -> [[@LINE+3]]:16 = #0
+// CHECK-NEXT: File 0, [[@LINE+2]]:16 -> [[@LINE+2]]:20 = #0
+// CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:17 -> [[@LINE+1]]:20 = #0
 void func4() M1 M11
-// CHECK-NEXT: Expansion,File 2, [[@LINE-1]]:14 -> [[@LINE-1]]:16 = #0 (HasCodeBefore = 0, Expanded file = 1)
-// CHECK-NEXT: Expansion,File 2, [[@LINE-2]]:17 -> [[@LINE-2]]:20 = #0 (HasCodeBefore = 0, Expanded file = 4)
-// CHECK-NEXT: File 3, 5:13 -> 5:14 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 4, 6:13 -> 6:16 = #0 (HasCodeBefore = 0, Expanded file = 3)
+// CHECK-NEXT: File 1, 4:12 -> 4:14 = #0
+// CHECK-NEXT: Expansion,File 1, 4:12 -> 4:14 = #0
+// CHECK-NEXT: File 2, 6:13 -> 6:16 = #0
+// CHECK-NEXT: Expansion,File 2, 6:13 -> 6:16 = #0
+// CHECK-NEXT: File 3, 3:12 -> 3:13 = #0
+// CHECK-NEXT: File 4, 5:13 -> 5:14 = #0
diff --git a/test/CoverageMapping/macroparams.c b/test/CoverageMapping/macroparams.c
index adf01ec..d2c8e55 100644
--- a/test/CoverageMapping/macroparams.c
+++ b/test/CoverageMapping/macroparams.c
@@ -1,12 +1,17 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macroparams.c %s | FileCheck %s
 
-#define MACRO2(X2) (X2 + 2) // CHECK-DAG: File 2, [[@LINE]]:20 -> [[@LINE]]:28 = #0 (HasCodeBefore = 0)
-#define MACRO(X) MACRO2(x)  // CHECK-DAG: File 1, [[@LINE]]:25 -> [[@LINE]]:26 = #0 (HasCodeBefore = 0)
-                            // CHECK-DAG: Expansion,File 1, [[@LINE-1]]:18 -> [[@LINE-1]]:24 = #0 (HasCodeBefore = 0, Expanded file = 2)
+// CHECK: main
+// CHECK-NEXT: File 0, {{[0-9]+}}:12 -> {{[0-9]+}}:2 = #0
+// CHECK-NEXT: Expansion,File 0, {{[0-9]+}}:3 -> {{[0-9]+}}:8 = #0
 
+// CHECK-NEXT: File 1, [[@LINE+2]]:18 -> [[@LINE+2]]:27 = #0
+// CHECK-NEXT: Expansion,File 1, [[@LINE+1]]:18 -> [[@LINE+1]]:24 = #0
+#define MACRO(X) MACRO2(x)
+// CHECK-NEXT: File 2, [[@LINE+1]]:20 -> [[@LINE+1]]:28 = #0
+#define MACRO2(X2) (X2 + 2)
 
-int main() {                // CHECK-DAG: File 0, [[@LINE]]:12 -> [[@LINE+4]]:2 = #0 (HasCodeBefore = 0)
+int main() {
   int x = 0;
-  MACRO(x);                 // CHECK-DAG: Expansion,File 0, [[@LINE]]:3 -> [[@LINE]]:8 = #0 (HasCodeBefore = 0, Expanded file = 1)
+  MACRO(x);
   return 0;
 }
diff --git a/test/CoverageMapping/macroparams2.c b/test/CoverageMapping/macroparams2.c
index 0445370..fc156de 100644
--- a/test/CoverageMapping/macroparams2.c
+++ b/test/CoverageMapping/macroparams2.c
@@ -1,20 +1,21 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macroparams2.c %s | FileCheck %s
 
-// A test case for when the first macro parameter is used after the second
-// macro parameter.
+#define MACRO(REFS, CALLS)  (4 * (CALLS) < (REFS))
 
 struct S {
   int i, j;
 };
 
-#define MACRO(REFS, CALLS)  (4 * (CALLS) < (REFS))
-
-int main() {                       // CHECK: File 0, [[@LINE]]:12 -> [[@LINE+7]]:2 = #0 (HasCodeBefore = 0)
-  struct S arr[32] = { 0 };        // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:7 -> [[@LINE+2]]:12 = #0 (HasCodeBefore = 0, Expanded file = 1)
-  int n = 0;                       // CHECK-NEXT: File 0, [[@LINE+1]]:13 -> [[@LINE+1]]:21 = #0 (HasCodeBefore = 0)
-  if (MACRO(arr[n].j, arr[n].i)) { // CHECK-NEXT: File 0, [[@LINE]]:23 -> [[@LINE]]:31 = #0 (HasCodeBefore = 0)
-    n = 1;                         // CHECK-NEXT: File 0, [[@LINE-1]]:34 -> [[@LINE+1]]:4 = #1 (HasCodeBefore = 0)
+// CHECK: File 0, [[@LINE+1]]:12 -> [[@LINE+10]]:2 = #0
+int main() {
+  struct S arr[32] = { 0 };
+  int n = 0;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:7 -> [[@LINE+2]]:12 = #0
+  // CHECK-NEXT: File 0, [[@LINE+1]]:34 -> [[@LINE+3]]:4 = #1
+  if (MACRO(arr[n].j, arr[n].i)) {
+    n = 1;
   }
   return n;
-}                                  // CHECK-NEXT: File 1, [[@LINE-9]]:29 -> [[@LINE-9]]:51 = #0 (HasCodeBefore = 0
+}
 
+// CHECK: File 1, 3:29 -> 3:51 = #0
diff --git a/test/CoverageMapping/macros.c b/test/CoverageMapping/macros.c
index d3a0e6a..02ecceb 100644
--- a/test/CoverageMapping/macros.c
+++ b/test/CoverageMapping/macros.c
@@ -1,26 +1,43 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macros.c %s | FileCheck %s
 
-void bar();
 #define MACRO return; bar()
 #define MACRO_2 bar()
 #define MACRO_1 return; MACRO_2
 
-               // CHECK: func
-void func() {  // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE+4]]:2 = #0 (HasCodeBefore = 0)
-  int i = 0;
-  MACRO;       // CHECK-NEXT: Expansion,File 0, [[@LINE]]:3 -> [[@LINE]]:8 = #0 (HasCodeBefore = 0, Expanded file = 1)
-  i = 2;       // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:8 = 0 (HasCodeBefore = 0)
-}
-// CHECK-NEXT: File 1, 4:15 -> 4:21 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: File 1, 4:23 -> 4:28 = 0 (HasCodeBefore = 0)
+void bar() {}
 
-               // CHECK-NEXT: func2
-void func2() { // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+4]]:2 = #0 (HasCodeBefore = 0)
+// CHECK: func
+void func() {  // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE+5]]:2 = #0
   int i = 0;
-  MACRO_1;     // CHECK-NEXT: Expansion,File 0, [[@LINE]]:3 -> [[@LINE]]:10 = #0 (HasCodeBefore = 0, Expanded file = 1)
-  i = 2;       // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:8 = 0 (HasCodeBefore = 0)
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:8 = #0
+  MACRO;       // CHECK-NEXT: File 0, [[@LINE]]:8 -> [[@LINE+2]]:2 = 0
+  i = 2;
 }
-// CHECK-NEXT: File 1, 6:17 -> 6:23 = #0 (HasCodeBefore = 0)
-// CHECK-NEXT: Expansion,File 1, 6:25 -> 6:32 = 0 (HasCodeBefore = 0, Expanded file = 2)
-// CHECK-NEXT: File 2, 5:17 -> 5:22 = 0 (HasCodeBefore = 0)
+// CHECK-NEXT: File 1, 3:15 -> 3:28 = #0
+// CHECK-NEXT: File 1, 3:23 -> 3:28 = 0
 
+// CHECK-NEXT: func2
+void func2() { // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+5]]:2 = #0
+  int i = 0;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:10 = #0
+  MACRO_1;     // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:2 = 0
+  i = 2;
+}
+// CHECK-NEXT: File 1, 5:17 -> 5:32 = #0
+// CHECK-NEXT: File 1, 5:25 -> 5:32 = 0
+// CHECK-NEXT: Expansion,File 1, 5:25 -> 5:32 = 0
+// CHECK-NEXT: File 2, 4:17 -> 4:22 = 0
+
+// CHECK-NEXT: func3
+void func3() { // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+3]]:2 = #0
+  MACRO_2; // CHECK-NEXT: Expansion,File 0, [[@LINE]]:3 -> [[@LINE]]:10 = #0
+  MACRO_2; // CHECK-NEXT: Expansion,File 0, [[@LINE]]:3 -> [[@LINE]]:10 = #0
+}
+// CHECK-NEXT: File 1, 4:17 -> 4:22 = #0
+// CHECK-NEXT: File 2, 4:17 -> 4:22 = #0
+
+int main(int argc, const char *argv[]) {
+  func();
+  func2();
+  func3();
+}
diff --git a/test/CoverageMapping/macroscopes.cpp b/test/CoverageMapping/macroscopes.cpp
new file mode 100644
index 0000000..a3a9297
--- /dev/null
+++ b/test/CoverageMapping/macroscopes.cpp
@@ -0,0 +1,105 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macroscopes.cpp %s | FileCheck %s
+
+#define starts_a_scope for (int i = 0; i < 2; ++i) {
+
+#define ends_a_scope \
+  x = x;             \
+  }
+
+#define some_code \
+  x = x;          \
+  if (x == 0) {   \
+    x = 1;        \
+  } else {        \
+    x = 2;        \
+  }               \
+  if (true) {     \
+    x = x;        \
+  } else {        \
+    x = x;        \
+  }
+
+#define starts_a_while while (x < 5)
+#define simple_stmt ++x
+
+// CHECK: main
+// CHECK-NEXT: File 0, [[@LINE+1]]:12 -> {{[0-9]+}}:2 = #0
+int main() {
+  int x = 0;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:3 -> [[@LINE+2]]:17 = #0
+  // CHECK-NEXT: File 0, [[@LINE+1]]:17 -> [[@LINE+7]]:15 = #1
+  starts_a_scope
+    x = x;
+    // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:5 -> [[@LINE+1]]:14 = #1
+    some_code
+    x = x;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:15 = #1
+  ends_a_scope
+
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+4]]:3 -> [[@LINE+4]]:17 = #0
+  // CHECK-NEXT: File 0, [[@LINE+3]]:17 -> [[@LINE+5]]:15 = #4
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:5 -> [[@LINE+3]]:14 = #4
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:3 -> [[@LINE+3]]:15 = #4
+  starts_a_scope
+    some_code
+  ends_a_scope
+
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:3 -> [[@LINE+3]]:17 = #0
+  // CHECK-NEXT: File 0, [[@LINE+2]]:17 -> [[@LINE+3]]:15 = #7
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:3 -> [[@LINE+2]]:15 = #7
+  starts_a_scope
+  ends_a_scope
+
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:3 -> [[@LINE+2]]:17 = #0
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:5 -> [[@LINE+2]]:16 = #8
+  starts_a_while
+    simple_stmt;
+
+  x = 0;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+4]]:3 -> [[@LINE+4]]:17 = #0
+  // CHECK-NEXT: File 0, [[@LINE+3]]:18 -> [[@LINE+5]]:15 = #9
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:5 -> [[@LINE+3]]:16 = #9
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:3 -> [[@LINE+3]]:15 = #9
+  starts_a_while {
+    simple_stmt;
+  ends_a_scope
+
+  return 0;
+}
+
+// CHECK-NEXT: File 1, 3:24 -> 3:53 = #0
+// CHECK-NEXT: File 1, 3:40 -> 3:45 = (#0 + #1)
+// CHECK-NEXT: File 1, 3:47 -> 3:50 = #1
+// CHECK-NEXT: File 1, 3:52 -> 3:53 = #1
+// CHECK-NEXT: File 2, 10:3 -> 20:4 = #1
+// CHECK-NEXT: File 2, 11:7 -> 11:13 = #1
+// CHECK-NEXT: File 2, 11:15 -> 13:4 = #2
+// CHECK-NEXT: File 2, 13:10 -> 15:4 = (#1 - #2)
+// CHECK-NEXT: File 2, 16:7 -> 16:11 = #1
+// CHECK-NEXT: File 2, 16:13 -> 18:4 = #3
+// CHECK-NEXT: File 2, 18:10 -> 20:4 = (#1 - #3)
+// CHECK-NEXT: File 3, 6:3 -> 7:4 = #1
+// CHECK-NEXT: File 4, 3:24 -> 3:53 = #0
+// CHECK-NEXT: File 4, 3:40 -> 3:45 = (#0 + #4)
+// CHECK-NEXT: File 4, 3:47 -> 3:50 = #4
+// CHECK-NEXT: File 4, 3:52 -> 3:53 = #4
+// CHECK-NEXT: File 5, 10:3 -> 20:4 = #4
+// CHECK-NEXT: File 5, 11:7 -> 11:13 = #4
+// CHECK-NEXT: File 5, 11:15 -> 13:4 = #5
+// CHECK-NEXT: File 5, 13:10 -> 15:4 = (#4 - #5)
+// CHECK-NEXT: File 5, 16:7 -> 16:11 = #4
+// CHECK-NEXT: File 5, 16:13 -> 18:4 = #6
+// CHECK-NEXT: File 5, 18:10 -> 20:4 = (#4 - #6)
+// CHECK-NEXT: File 6, 6:3 -> 7:4 = #4
+// CHECK-NEXT: File 7, 3:24 -> 3:53 = #0
+// CHECK-NEXT: File 7, 3:40 -> 3:45 = (#0 + #7)
+// CHECK-NEXT: File 7, 3:47 -> 3:50 = #7
+// CHECK-NEXT: File 7, 3:52 -> 3:53 = #7
+// CHECK-NEXT: File 8, 6:3 -> 7:4 = #7
+// CHECK-NEXT: File 9, 22:24 -> 22:37 = #0
+// CHECK-NEXT: File 9, 22:31 -> 22:36 = (#0 + #8)
+// CHECK-NEXT: File 10, 23:21 -> 23:24 = #8
+// CHECK-NEXT: File 11, 22:24 -> 22:37 = #0
+// CHECK-NEXT: File 11, 22:31 -> 22:36 = (#0 + #9)
+// CHECK-NEXT: File 12, 23:21 -> 23:24 = #9
+// CHECK-NEXT: File 13, 6:3 -> 7:4 = #9
diff --git a/test/CoverageMapping/md.cpp b/test/CoverageMapping/md.cpp
new file mode 100644
index 0000000..fff0df3
--- /dev/null
+++ b/test/CoverageMapping/md.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -std=c++11 %s | FileCheck %s
+
+#define BREAK break
+
+enum class MD {
+  Val1,
+  Val2
+};
+
+void nop() {}
+
+// CHECK: foo
+// CHECK-NEXT: File 0, [[@LINE+1]]:16 -> {{[0-9]+}}:2 = #0
+void foo(MD i) {
+  switch (i) {
+  #define HANDLE_MD(X)                                          \
+  case MD::X:                                                   \
+    break;
+  #include "Inputs/md.def"
+  default:
+    BREAK;
+  }
+
+  if (false)
+    nop();
+  #define HANDLE_MD(X) else if (i == MD::X) { nop(); }
+  #include "Inputs/md.def"
+}
+
+int main(int argc, const char *argv[]) {
+  foo(MD::Val1);
+  return 0;
+}
diff --git a/test/CoverageMapping/moremacros.c b/test/CoverageMapping/moremacros.c
new file mode 100644
index 0000000..d4a8f87
--- /dev/null
+++ b/test/CoverageMapping/moremacros.c
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name macro-expansion.c %s | FileCheck %s
+
+#define LBRAC {
+#define RBRAC }
+
+// CHECK: main:
+// CHECK-NEXT: File 0, [[@LINE+1]]:40 -> {{[0-9]+}}:2 = #0
+int main(int argc, const char *argv[]) {
+  // CHECK-NEXT: File 0, [[@LINE+1]]:7 -> [[@LINE+1]]:12 = #0
+  if (!argc) {} // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE]]:16 = #1
+
+  // CHECK-NEXT: File 0, [[@LINE+3]]:7 -> [[@LINE+3]]:12 = #0
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:14 -> [[@LINE+2]]:19 = #2
+  // CHECK-NEXT: File 0, [[@LINE+1]]:19 -> [[@LINE+4]]:8 = #2
+  if (!argc) LBRAC
+    return 0;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:8 = #2
+  RBRAC
+
+  // CHECK-NEXT: File 0, [[@LINE+4]]:3 -> [[@LINE+15]]:2 = (#0 - #2)
+  // CHECK-NEXT: File 0, [[@LINE+3]]:7 -> [[@LINE+3]]:12 = (#0 - #2)
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:14 -> [[@LINE+2]]:19 = #3
+  // CHECK-NEXT: File 0, [[@LINE+1]]:19 -> [[@LINE+3]]:4 = #3
+  if (!argc) LBRAC
+    return 0;
+  }
+
+  // CHECK-NEXT: File 0, [[@LINE+3]]:3 -> [[@LINE+7]]:2 = ((#0 - #2) - #3)
+  // CHECK-NEXT: File 0, [[@LINE+2]]:7 -> [[@LINE+2]]:12 = ((#0 - #2) - #3)
+  // CHECK-NEXT: File 0, [[@LINE+1]]:14 -> [[@LINE+4]]:8 = #4
+  if (!argc) {
+    return 0;
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:8 = #4
+  RBRAC
+}
+
+// CHECK-NEXT: File 1, 3:15 -> 3:16 = #2
+// CHECK-NEXT: File 2, 4:15 -> 4:16 = #2
+// CHECK-NEXT: File 3, 3:15 -> 3:16 = #3
+// CHECK-NEXT: File 4, 4:15 -> 4:16 = #4
diff --git a/test/CoverageMapping/nestedclass.cpp b/test/CoverageMapping/nestedclass.cpp
index aca4abf..be4e0ba 100644
--- a/test/CoverageMapping/nestedclass.cpp
+++ b/test/CoverageMapping/nestedclass.cpp
@@ -4,15 +4,15 @@
 // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-INNERMOST
 
 struct Test {                   // CHECK-OUTER: emitTest
-  void emitTest() {             // CHECK-OUTER: File 0, [[@LINE]]:19 -> [[@LINE+2]]:4 = #0 (HasCodeBefore = 0)
+  void emitTest() {             // CHECK-OUTER: File 0, [[@LINE]]:19 -> [[@LINE+2]]:4 = #0
     int i = 0;
   }
   struct Test2 {                // CHECK-INNER: emitTest2
-    void emitTest2() {          // CHECK-INNER: File 0, [[@LINE]]:22 -> [[@LINE+2]]:6 = #0 (HasCodeBefore = 0)
+    void emitTest2() {          // CHECK-INNER: File 0, [[@LINE]]:22 -> [[@LINE+2]]:6 = #0
       int i = 0;
     }
     struct Test3 {              // CHECK-INNERMOST: emitTest3
-      static void emitTest3() { // CHECK-INNERMOST: File 0, [[@LINE]]:31 -> [[@LINE+2]]:8 = 0 (HasCodeBefore = 0)
+      static void emitTest3() { // CHECK-INNERMOST: File 0, [[@LINE]]:31 -> [[@LINE+2]]:8 = 0
         int i = 0;
       }
     };
diff --git a/test/CoverageMapping/objc.m b/test/CoverageMapping/objc.m
index b41ab94..8456dc3 100644
--- a/test/CoverageMapping/objc.m
+++ b/test/CoverageMapping/objc.m
@@ -5,9 +5,9 @@
 @end
 
                       // CHECK: func
-void func(A *a) {     // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+3]]:2 = #0 (HasCodeBefore = 0)
-  if (a)
-    [a bork:  20  ];  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:20 = #1 (HasCodeBefore = 0)
+void func(A *a) {     // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+3]]:2 = #0
+  if (a)              // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:8 = #0
+    [a bork:  20  ];  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:20 = #1
 }
 
 @interface NSArray
@@ -16,12 +16,13 @@
 @end
 
                                // CHECK: func2
-void func2(NSArray *array) {   // CHECK-NEXT: File 0, [[@LINE]]:28 -> [[@LINE+10]]:2 = #0 (HasCodeBefore = 0)
+void func2(NSArray *array) {   // CHECK-NEXT: File 0, [[@LINE]]:28 -> {{[0-9]+}}:2 = #0
   int i = 0;
-  for (NSArray *x in array) {  // CHECK-NEXT: File 0, [[@LINE]]:29 -> [[@LINE+6]]:4 = #1 (HasCodeBefore = 0)
-    if (x) {                   // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = #2 (HasCodeBefore = 0)
+  for (NSArray *x in array) {  // CHECK-NEXT: File 0, [[@LINE]]:29 -> [[@LINE+7]]:4 = #1
+                               // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:10 = #1
+    if (x) {                   // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = #2
       i = 1;
-    } else {                   // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = (#1 - #2) (HasCodeBefore = 0)
+    } else {                   // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = (#1 - #2)
       i = -1;
     }
   }
diff --git a/test/CoverageMapping/preprocessor.c b/test/CoverageMapping/preprocessor.c
index a6edeb7..cdd448c 100644
--- a/test/CoverageMapping/preprocessor.c
+++ b/test/CoverageMapping/preprocessor.c
@@ -1,9 +1,9 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name preprocessor.c %s | FileCheck %s
 
                  // CHECK: func
-void func() {    // CHECK: File 0, [[@LINE]]:13 -> [[@LINE+5]]:2 = #0 (HasCodeBefore = 0)
+void func() {    // CHECK: File 0, [[@LINE]]:13 -> [[@LINE+5]]:2 = #0
   int i = 0;
-#ifdef MACRO     // CHECK-NEXT: Skipped,File 0, [[@LINE]]:2 -> [[@LINE+2]]:2 = 0 (HasCodeBefore = 0)
+#ifdef MACRO     // CHECK-NEXT: Skipped,File 0, [[@LINE]]:2 -> [[@LINE+2]]:2 = 0
   int x = i;
 #endif
 }
@@ -15,19 +15,20 @@
 #endif
 
                  // CHECK: main
-int main() {     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+19]]:2 = #0 (HasCodeBefore = 0)
+int main() {     // CHECK-NEXT: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int i = 0;
-#if 0            // CHECK-NEXT: Skipped,File 0, [[@LINE]]:2 -> [[@LINE+4]]:2 = 0 (HasCodeBefore = 0)
+#if 0            // CHECK-NEXT: Skipped,File 0, [[@LINE]]:2 -> [[@LINE+4]]:2 = 0
   if(i == 0) {
     i = 1;
   }
 #endif
 
 #if 1
-  if(i == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #1 (HasCodeBefore = 0)
+                 // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:12 = #0
+  if(i == 0) {   // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #1
     i = 1;
   }
-#else            // CHECK-NEXT: Skipped,File 0, [[@LINE]]:2 -> [[@LINE+5]]:2 = 0 (HasCodeBefore = 0)
+#else            // CHECK-NEXT: Skipped,File 0, [[@LINE]]:2 -> [[@LINE+5]]:2 = 0
   if(i == 1) {
     i = 0;
   }
diff --git a/test/CoverageMapping/return.c b/test/CoverageMapping/return.c
index 9c68759..ab63c2c 100644
--- a/test/CoverageMapping/return.c
+++ b/test/CoverageMapping/return.c
@@ -1,35 +1,44 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name return.c %s | FileCheck %s
 
                                 // CHECK: func
-void func() {                   // CHECK: File 0, [[@LINE]]:13 -> [[@LINE+3]]:2 = #0 (HasCodeBefore = 0)
+void func() {                   // CHECK: File 0, [[@LINE]]:13 -> [[@LINE+3]]:2 = #0
   return;
-  int i = 0;                    // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:12 = 0 (HasCodeBefore = 0)
+  int i = 0;                    // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = 0
 }
 
                                 // CHECK-NEXT: func2
-void func2() {                  // CHECK-NEXT: File 0, [[@LINE]]:14 -> [[@LINE+13]]:2 = #0 (HasCodeBefore = 0)
-                                // CHECK-NEXT: File 0, [[@LINE+2]]:18 -> [[@LINE+2]]:24 = ((#0 + #1) - #2) (HasCodeBefore = 0)
-                                // CHECK-NEXT: File 0, [[@LINE+1]]:26 -> [[@LINE+1]]:29 = (#1 - #2) (HasCodeBefore = 0)
-  for(int i = 0; i < 10; ++i) { // CHECK-NEXT: File 0, [[@LINE]]:31 -> [[@LINE+9]]:4 = #1 (HasCodeBefore = 0)
-    if(i > 2) {                 // CHECK-NEXT: File 0, [[@LINE]]:15 -> [[@LINE+2]]:6 = #2 (HasCodeBefore = 0)
+void func2() {                  // CHECK-NEXT: File 0, [[@LINE]]:14 -> {{[0-9]+}}:2 = #0
+                                // CHECK-NEXT: File 0, [[@LINE+2]]:18 -> [[@LINE+2]]:24 = ((#0 + #1) - #2)
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:26 -> [[@LINE+1]]:29 = (#1 - #2)
+  for(int i = 0; i < 10; ++i) { // CHECK-NEXT: File 0, [[@LINE]]:31 -> {{[0-9]+}}:4 = #1
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:13 = #1
+    if(i > 2) {                 // CHECK-NEXT: File 0, [[@LINE]]:15 -> [[@LINE+2]]:6 = #2
       return;
-    }                           // CHECK-NEXT: File 0, [[@LINE+1]]:5 -> [[@LINE+3]]:11 = (#1 - #2) (HasCodeBefore = 0)
-    if(i == 3) {                // CHECK-NEXT: File 0, [[@LINE]]:16 -> [[@LINE+2]]:6 = #3 (HasCodeBefore = 0)
+    }                           // CHECK-NEXT: File 0, [[@LINE+2]]:5 -> {{[0-9]+}}:4 = (#1 - #2)
+                                // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+1]]:14 = (#1 - #2)
+    if(i == 3) {                // CHECK-NEXT: File 0, [[@LINE]]:16 -> [[@LINE+2]]:6 = #3
       int j = 1;
-    } else {                    // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = ((#1 - #2) - #3) (HasCodeBefore = 0)
+    } else {                    // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+2]]:6 = ((#1 - #2) - #3)
       int j = 2;
     }
   }
 }
 
                                // CHECK-NEXT: func3
-void func3(int x) {            // CHECK-NEXT: File 0, [[@LINE]]:19 -> [[@LINE+9]]:2 = #0 (HasCodeBefore = 0)
-  if(x > 5) {                  // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE+6]]:4 = #1 (HasCodeBefore = 0)
-    while(x >= 9) {            // CHECK-NEXT: File 0, [[@LINE]]:11 -> [[@LINE]]:17 = #1 (HasCodeBefore = 0)
-      return;                  // CHECK-NEXT: File 0, [[@LINE-1]]:19 -> [[@LINE+2]]:6 = #2 (HasCodeBefore = 0)
-      --x;                     // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:10 = 0 (HasCodeBefore = 0)
+void func3(int x) {            // CHECK-NEXT: File 0, [[@LINE]]:19 -> {{[0-9]+}}:2 = #0
+                               // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:11 = #0
+  if(x > 5) {                  // CHECK-NEXT: File 0, [[@LINE]]:13 -> [[@LINE+6]]:4 = #1
+    while(x >= 9) {            // CHECK-NEXT: File 0, [[@LINE]]:11 -> [[@LINE]]:17 = #1
+      return;                  // CHECK-NEXT: File 0, [[@LINE-1]]:19 -> [[@LINE+2]]:6 = #2
+      --x;                     // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE+1]]:6 = 0
     }
-    int i = 0;                 // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:14 = (#1 - #2) (HasCodeBefore = 0)
+    int i = 0;                 // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+1]]:4 = (#1 - #2)
   }
-  int j = 0;                   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:12 = (#0 - #2) (HasCodeBefore = 0)
+  int j = 0;                   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = (#0 - #2)
+}
+
+int main(int argc, const char *argv[]) {
+  func();
+  func2();
+  func3(10);
 }
diff --git a/test/CoverageMapping/switch.c b/test/CoverageMapping/switch.c
index b667225..3c0b032 100644
--- a/test/CoverageMapping/switch.c
+++ b/test/CoverageMapping/switch.c
@@ -1,48 +1,73 @@
 // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name switch.c %s | FileCheck %s
                     // CHECK: foo
-void foo(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+8]]:2 = #0 (HasCodeBefore = 0)
+void foo(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+8]]:2 = #0
   switch(i) {
-  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = #2 (HasCodeBefore = 0)
+  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:10 = #2
     return;
-  case 2:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #3 (HasCodeBefore = 0)
+  case 2:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #3
     break;
-  }                 // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:12 = #1 (HasCodeBefore = 0)
-  int x = 0;
+  }
+  int x = 0;        // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #1
+}
+
+void nop() {}
+
+                    // CHECK: bar
+void bar(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+20]]:2 = #0
+  switch (i)
+    ;               // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:6 = 0
+
+  switch (i) {      // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+16]]:2 = #1
+  }
+
+  switch (i)        // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+13]]:2 = #2
+    nop();          // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = 0
+
+  switch (i)        // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+10]]:2 = #3
+  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #5
+    nop();
+
+  switch (i) {      // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:2 = #4
+    nop();          // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+2]]:10 = 0
+  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #7
+    nop();
+  }
+  nop();            // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #6
 }
 
                     // CHECK-NEXT: main
-int main() {        // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+34]]:2 = #0 (HasCodeBefore = 0)
+int main() {        // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+34]]:2 = #0
   int i = 0;
   switch(i) {
-  case 0:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #2 (HasCodeBefore = 0)
+  case 0:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+7]]:10 = #2
     i = 1;
     break;
-  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #3 (HasCodeBefore = 0)
+  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #3
     i = 2;
     break;
-  default:          // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #4 (HasCodeBefore = 0)
+  default:          // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #4
     break;
-  }                 // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:14 = #1 (HasCodeBefore = 0)
-  switch(i) {
-  case 0:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #6 (HasCodeBefore = 0)
+  }
+  switch(i) {       // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+22]]:2 = #1
+  case 0:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:10 = #6
     i = 1;
     break;
-  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #7 (HasCodeBefore = 0)
+  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:10 = #7
     i = 2;
-  default:          // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = (#7 + #8) (HasCodeBefore = 0)
+  default:          // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = (#7 + #8)
     break;
-  }                 // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:14 = #5 (HasCodeBefore = 0)
+  }
 
-
-  switch(i) {
-  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:10 = #10 (HasCodeBefore = 0)
-  case 2:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = (#10 + #11) (HasCodeBefore = 0)
+  switch(i) {       // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+12]]:2 = #5
+  case 1:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+5]]:11 = #10
+  case 2:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+4]]:11 = (#10 + #11)
     i = 11;
-  case 3:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:10 = ((#10 + #11) + #12) (HasCodeBefore = 0)
-  case 4:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = (((#10 + #11) + #12) + #13) (HasCodeBefore = 0)
+  case 3:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:11 = ((#10 + #11) + #12)
+  case 4:           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = (((#10 + #11) + #12) + #13)
     i = 99;
-  }                 // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:11 = #9 (HasCodeBefore = 0)
+  }
 
-  foo(1);
+  foo(1);           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:11 = #9
+  bar(1);
   return 0;
 }
diff --git a/test/CoverageMapping/switchmacro.c b/test/CoverageMapping/switchmacro.c
new file mode 100644
index 0000000..431d5c7
--- /dev/null
+++ b/test/CoverageMapping/switchmacro.c
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name switchmacro.c %s | FileCheck %s
+
+#define FOO(x) (void)x
+
+// CHECK: foo
+int foo(int i) { // CHECK-NEXT: File 0, [[@LINE]]:16 -> {{[0-9]+}}:2 = #0
+  switch (i) {
+  default:       // CHECK-NEXT: File 0, [[@LINE]]:3 -> {{[0-9]+}}:11 = #2
+    if (i == 1)  // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:15 = #2
+      return 0;  // CHECK-NEXT: File 0, [[@LINE]]:7 -> [[@LINE]]:15 = #3
+    // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:5 -> [[@LINE+2]]:8 = (#2 - #3)
+    // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> {{[0-9]+}}:11 = (#2 - #3)
+    FOO(1);
+  case 0:        // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:13 = ((#2 + #4) - #3)
+    return 2;
+
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:3 -> [[@LINE+2]]:6 = 0
+  // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> {{[0-9]+}}:11 = 0
+  FOO(1);
+  // CHECK-NEXT: File 0, [[@LINE+1]]:3 -> {{[0-9]+}}:11 = #5
+  label: ;
+  }
+}
+
+int main(int argc, const char *argv[]) {
+  foo(3);
+  return 0;
+}
diff --git a/test/CoverageMapping/test.c b/test/CoverageMapping/test.c
index 594bcf6..a274ce4 100644
--- a/test/CoverageMapping/test.c
+++ b/test/CoverageMapping/test.c
@@ -4,28 +4,29 @@
 static void static_func();
 
                                  // CHECK: main
-int main() {                     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+7]]:2 = #0 (HasCodeBefore = 0)
-                                 // CHECK-NEXT: File 0, [[@LINE+1]]:18 -> [[@LINE+1]]:24 = (#0 + #1) (HasCodeBefore = 0)
-  for(int i = 0; i < 10; ++i) {  // CHECK-NEXT: File 0, [[@LINE]]:26 -> [[@LINE]]:29 = #1 (HasCodeBefore = 0)
-    bar();                       // CHECK-NEXT: File 0, [[@LINE-1]]:31 -> [[@LINE+1]]:4 = #1 (HasCodeBefore = 0)
+int main() {                     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+7]]:2 = #0
+                                 // CHECK-NEXT: File 0, [[@LINE+1]]:18 -> [[@LINE+1]]:24 = (#0 + #1)
+  for(int i = 0; i < 10; ++i) {  // CHECK-NEXT: File 0, [[@LINE]]:26 -> [[@LINE]]:29 = #1
+    bar();                       // CHECK-NEXT: File 0, [[@LINE-1]]:31 -> [[@LINE+1]]:4 = #1
   }
   static_func();
   return 0;
 }
 
                                  // CHECK-NEXT: foo
-void foo() {                     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+4]]:2 = #0 (HasCodeBefore = 0)
-  if(1) {                        // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE+2]]:4 = #1 (HasCodeBefore = 0)
+void foo() {                     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+5]]:2 = #0
+                                 // CHECK-NEXT: File 0, [[@LINE+1]]:6 -> [[@LINE+1]]:7 = #0
+  if(1) {                        // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE+2]]:4 = #1
     int i = 0;
   }
 }
 
                                  // CHECK-NEXT: bar
-void bar() {                     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+1]]:2 = #0 (HasCodeBefore = 0)
+void bar() {                     // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+1]]:2 = #0
 }
 
                                  // CHECK-NEXT: static_func
-void static_func() { }           // CHECK: File 0, [[@LINE]]:20 -> [[@LINE]]:23 = #0 (HasCodeBefore = 0)
+void static_func() { }           // CHECK: File 0, [[@LINE]]:20 -> [[@LINE]]:23 = #0
 
                                  // CHECK-NEXT: func
-static void func() { }           // CHECK: File 0, [[@LINE]]:20 -> [[@LINE]]:23 = 0 (HasCodeBefore = 0)
+static void func() { }           // CHECK: File 0, [[@LINE]]:20 -> [[@LINE]]:23 = 0
diff --git a/test/CoverageMapping/trycatch.cpp b/test/CoverageMapping/trycatch.cpp
index a513845..696df54 100644
--- a/test/CoverageMapping/trycatch.cpp
+++ b/test/CoverageMapping/trycatch.cpp
@@ -10,25 +10,26 @@
 };
 
                                       // CHECK: func
-void func(int i) {                    // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+5]]:2 = #0 (HasCodeBefore = 0)
-  if(i % 2)
-    throw Error();                    // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:16 = #1 (HasCodeBefore = 0)
-  else if(i == 8)                     // CHECK-NEXT: File 0, [[@LINE]]:8 -> [[@LINE]]:17 = (#0 - #1) (HasCodeBefore = 0)
-    throw ImportantError();           // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:25 = #2 (HasCodeBefore = 0)
+void func(int i) {                    // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+6]]:2 = #0
+  if(i % 2)                           // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:11 = #0
+    throw Error();                    // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:18 = #1
+                                      // CHECK-NEXT: File 0, [[@LINE+1]]:8 -> [[@LINE+2]]:27 = (#0 - #1)
+  else if(i == 8)                     // CHECK-NEXT: File 0, [[@LINE]]:11 -> [[@LINE]]:17 = (#0 - #1)
+    throw ImportantError();           // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:27 = #2
 }
 
                                       // CHECK-NEXT: main
-int main() {                          // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+13]]:2 = #0 (HasCodeBefore = 0)
+int main() {                          // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+13]]:2 = #0
   int j = 0;
   try {
     func(j);
-  } catch(const Error &e) {           // CHECK-NEXT: File 0, [[@LINE]]:27 -> [[@LINE+2]]:10 = #2 (HasCodeBefore = 0)
+  } catch(const Error &e) {           // CHECK-NEXT: File 0, [[@LINE]]:27 -> [[@LINE+2]]:4 = #2
     j = 1;
-  } catch(const ImportantError &e) {  // CHECK-NEXT: File 0, [[@LINE]]:36 -> [[@LINE+3]]:8 = #3 (HasCodeBefore = 0)
+  } catch(const ImportantError &e) {  // CHECK-NEXT: File 0, [[@LINE]]:36 -> [[@LINE+2]]:4 = #3
     j = 11;
   }
-  catch(const Warning &w) {           // CHECK-NEXT: File 0, [[@LINE]]:27 -> [[@LINE+2]]:4 = #4 (HasCodeBefore = 0)
+  catch(const Warning &w) {           // CHECK-NEXT: File 0, [[@LINE]]:27 -> [[@LINE+2]]:4 = #4
     j = 0;
   }
-  return 0;                           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:11 = #1 (HasCodeBefore = 0)
+  return 0;                           // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE]]:11 = #1
 }
diff --git a/test/CoverageMapping/unused_names.c b/test/CoverageMapping/unused_names.c
new file mode 100644
index 0000000..8a57957
--- /dev/null
+++ b/test/CoverageMapping/unused_names.c
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -emit-llvm -main-file-name unused_names.c -o - %s > %t
+// RUN: FileCheck -input-file %t %s
+// RUN: FileCheck -check-prefix=SYSHEADER -input-file %t %s
+
+// Since foo is never emitted, there should not be a profile name for it.
+
+// CHECK-DAG: @__llvm_profile_name_bar = {{.*}} section "{{.*}}__llvm_prf_names"
+// CHECK-DAG: @__llvm_profile_name_baz = {{.*}} section "{{.*}}__llvm_prf_names"
+// CHECK-DAG: @"__llvm_profile_name_unused_names.c:qux" = {{.*}} section "{{.*}}__llvm_prf_names"
+
+// SYSHEADER-NOT: @__llvm_profile_name_foo =
+
+
+#ifdef IS_SYSHEADER
+
+#pragma clang system_header
+inline int foo() { return 0; }
+
+#else
+
+#define IS_SYSHEADER
+#include __FILE__
+
+int bar() { return 0; }
+inline int baz() { return 0; }
+static int qux() { return 42; }
+
+#endif
diff --git a/test/CoverageMapping/while.c b/test/CoverageMapping/while.c
new file mode 100644
index 0000000..a85957f
--- /dev/null
+++ b/test/CoverageMapping/while.c
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name loops.cpp %s | FileCheck %s
+
+                                    // CHECK: main
+int main() {                        // CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+8]]:2 = #0
+  int j = 0;                        // CHECK-NEXT: File 0, [[@LINE+1]]:9 -> [[@LINE+1]]:14 = (#0 + #1)
+  while(j < 5) ++j;                 // CHECK-NEXT: File 0, [[@LINE]]:16 -> [[@LINE]]:19 = #1
+  j = 0;
+  while
+   (j < 5)                          // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE]]:10 = (#0 + #2)
+     ++j;                           // CHECK-NEXT: File 0, [[@LINE]]:6 -> [[@LINE]]:9 = #2
+  return 0;
+}
diff --git a/test/Modules/macro-reexport/a2.h b/test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtbegin.o
similarity index 100%
copy from test/Modules/macro-reexport/a2.h
copy to test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtbegin.o
diff --git a/test/Modules/macro-reexport/a2.h b/test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtbeginS.o
similarity index 100%
copy from test/Modules/macro-reexport/a2.h
copy to test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtbeginS.o
diff --git a/test/Modules/macro-reexport/a2.h b/test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtbeginT.o
similarity index 100%
copy from test/Modules/macro-reexport/a2.h
copy to test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtbeginT.o
diff --git a/test/Modules/macro-reexport/a2.h b/test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtend.o
similarity index 100%
copy from test/Modules/macro-reexport/a2.h
copy to test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtend.o
diff --git a/test/Modules/macro-reexport/a2.h b/test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtendS.o
similarity index 100%
copy from test/Modules/macro-reexport/a2.h
copy to test/Driver/Inputs/basic_android_tree/lib/gcc/mipsel-linux-android/4.4.3/mips-r6/crtendS.o
diff --git a/test/Driver/aarch64-cpus.c b/test/Driver/aarch64-cpus.c
index 1627660..4380381 100644
--- a/test/Driver/aarch64-cpus.c
+++ b/test/Driver/aarch64-cpus.c
@@ -40,6 +40,20 @@
 // RUN: %clang -target arm64 -mlittle-endian -mtune=cortex-a57 -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-CA57 %s
 // ARM64-CA57: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "cortex-a57"
 
+// RUN: %clang -target aarch64 -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72 %s
+// RUN: %clang -target aarch64 -mlittle-endian -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72 %s
+// RUN: %clang -target aarch64_be -mlittle-endian -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72 %s
+// RUN: %clang -target aarch64 -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72 %s
+// RUN: %clang -target aarch64 -mlittle-endian -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72 %s
+// RUN: %clang -target aarch64_be -mlittle-endian -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72 %s
+// CA72: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-a72"
+
+// RUN: %clang -target arm64 -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-CA72 %s
+// RUN: %clang -target arm64 -mlittle-endian -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-CA72 %s
+// RUN: %clang -target arm64 -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-CA72 %s
+// RUN: %clang -target arm64 -mlittle-endian -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-CA72 %s
+// ARM64-CA72: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "cortex-a72"
+
 // RUN: %clang -target aarch64_be -### -c %s 2>&1 | FileCheck -check-prefix=GENERIC-BE %s
 // RUN: %clang -target aarch64 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=GENERIC-BE %s
 // RUN: %clang -target aarch64_be -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=GENERIC-BE %s
@@ -61,6 +75,16 @@
 // RUN: %clang -target aarch64_be -mbig-endian -mtune=cortex-a57 -### -c %s 2>&1 | FileCheck -check-prefix=CA57-BE %s
 // CA57-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "cortex-a57"
 
+// RUN: %clang -target aarch64_be -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72-BE %s
+// RUN: %clang -target aarch64 -mbig-endian -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72-BE %s
+// RUN: %clang -target aarch64_be -mbig-endian -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72-BE %s
+// RUN: %clang -target aarch64_be -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72-BE %s
+// RUN: %clang -target aarch64 -mbig-endian -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72-BE %s
+// RUN: %clang -target aarch64_be -mbig-endian -mtune=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CA72-BE %s
+// CA72-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "cortex-a72"
+
 // RUN: %clang -target aarch64 -mcpu=cortex-a57 -mtune=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=MCPU-MTUNE %s
 // RUN: %clang -target aarch64 -mtune=cortex-a53 -mcpu=cortex-a57  -### -c %s 2>&1 | FileCheck -check-prefix=MCPU-MTUNE %s
+// RUN: %clang -target aarch64 -mcpu=cortex-a72 -mtune=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=MCPU-MTUNE %s
+// RUN: %clang -target aarch64 -mtune=cortex-a53 -mcpu=cortex-a72  -### -c %s 2>&1 | FileCheck -check-prefix=MCPU-MTUNE %s
 // MCPU-MTUNE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "cortex-a53"
diff --git a/test/Driver/aarch64-fix-cortex-a53-835769.c b/test/Driver/aarch64-fix-cortex-a53-835769.c
new file mode 100644
index 0000000..3fe918a
--- /dev/null
+++ b/test/Driver/aarch64-fix-cortex-a53-835769.c
@@ -0,0 +1,13 @@
+// RUN: %clang -target aarch64-linux-eabi %s -### 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-DEF %s
+// RUN: %clang -target aarch64-linux-eabi -mfix-cortex-a53-835769 %s -### 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-YES %s
+// RUN: %clang -target aarch64-linux-eabi -mno-fix-cortex-a53-835769 %s -### 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO %s
+
+// RUN: %clang -target aarch64-android-eabi %s -### 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-YES %s
+
+// CHECK-DEF-NOT: "-backend-option" "-aarch64-fix-cortex-a53-835769"
+// CHECK-YES: "-backend-option" "-aarch64-fix-cortex-a53-835769=1"
+// CHECK-NO: "-backend-option" "-aarch64-fix-cortex-a53-835769=0"
diff --git a/test/Driver/aarch64-fixed-x18.c b/test/Driver/aarch64-fixed-x18.c
new file mode 100644
index 0000000..35d0caf
--- /dev/null
+++ b/test/Driver/aarch64-fixed-x18.c
@@ -0,0 +1,4 @@
+// RUN: %clang -target aarch64-none-gnu -ffixed-x18 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-FIXED-X18 < %t %s
+
+// CHECK-FIXED-X18: "-backend-option" "-aarch64-reserve-x18"
diff --git a/test/Driver/android-standalone.cpp b/test/Driver/android-standalone.cpp
index 2bdaedd..d563deb 100644
--- a/test/Driver/android-standalone.cpp
+++ b/test/Driver/android-standalone.cpp
@@ -93,3 +93,19 @@
 // CHECK-MIPSR2-A: "-L{{.*}}/lib/gcc/mipsel-linux-android/4.4.3/mips-r2"
 // CHECK-MIPSR2-A: "-L{{.*}}/lib/gcc/mipsel-linux-android/4.4.3/../../../../mipsel-linux-android/lib"
 // CHECK-MIPSR2-A: "-L{{.*}}/sysroot/usr/lib"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     -target mipsel-linux-android \
+// RUN:     -mips32r6 \
+// RUN:     -B%S/Inputs/basic_android_tree \
+// RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-MIPSR6 %s
+// CHECK-MIPSR6: {{.*}}clang{{.*}}" "-cc1"
+// CHECK-MIPSR6: "-internal-isystem" "{{.*}}/mipsel-linux-android/include/c++/4.4.3"
+// CHECK-MIPSR6: "-internal-isystem" "{{.*}}/mipsel-linux-android/include/c++/4.4.3/mipsel-linux-android"
+// CHECK-MIPSR6: "-internal-externc-isystem" "{{.*}}/sysroot/include"
+// CHECK-MIPSR6: "-internal-externc-isystem" "{{.*}}/sysroot/usr/include"
+// CHECK-MIPSR6: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-MIPSR6: "-L{{.*}}/lib/gcc/mipsel-linux-android/4.4.3/mips-r6"
+// CHECK-MIPSR6: "-L{{.*}}/lib/gcc/mipsel-linux-android/4.4.3/../../../../mipsel-linux-android/lib"
+// CHECK-MIPSR6: "-L{{.*}}/sysroot/usr/lib"
diff --git a/test/Driver/arm-cortex-cpus.c b/test/Driver/arm-cortex-cpus.c
index b1f2533..2be6630 100644
--- a/test/Driver/arm-cortex-cpus.c
+++ b/test/Driver/arm-cortex-cpus.c
@@ -69,6 +69,8 @@
 
 // RUN: %clang -target armv6m -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V6M %s
 // RUN: %clang -target arm -march=armv6m -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V6M %s
+// RUN: %clang -target armv6sm -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V6M %s
+// RUN: %clang -target arm -march=armv6sm -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V6M %s
 // CHECK-V6M: "-cc1"{{.*}} "-triple" "thumbv6m-{{.*}} "-target-cpu" "cortex-m0"
 
 // RUN: %clang -target armv6m -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V6M-BIG %s
@@ -228,10 +230,15 @@
 // CHECK-BE-CPUV7A-THUMB: "-cc1"{{.*}} "-triple" "thumbebv7-{{.*}}
 
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-m0 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV6M %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-m0plus -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV6M %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-m1 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV6M %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=sc000 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV6M %s
 // CHECK-CPUV6M: "-cc1"{{.*}} "-triple" "thumbv6m-{{.*}}
 
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-m3 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7M %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-m3 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7M %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=sc300 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7M %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=sc300 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7M %s
 // CHECK-CPUV7M: "-cc1"{{.*}} "-triple" "thumbv7m-{{.*}}
 
 // RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-m3 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7M %s
@@ -252,48 +259,64 @@
 
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r4 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r5 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r7 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r4 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r5 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r7 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R %s
 // CHECK-CPUV7R: "-cc1"{{.*}} "-triple" "armv7r-{{.*}}
 
 // RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-r4 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R %s
 // RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-r5 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R %s
+// RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-r7 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r4 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r5 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r7 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R %s
 // CHECK-BE-CPUV7R: "-cc1"{{.*}} "-triple" "armebv7r-{{.*}}
 
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r4 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R-THUMB %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r5 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R-THUMB %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r7 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R-THUMB %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r4 -mlittle-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R-THUMB %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r5 -mlittle-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R-THUMB %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r7 -mlittle-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV7R-THUMB %s
 // CHECK-CPUV7R-THUMB: "-cc1"{{.*}} "-triple" "thumbv7r-{{.*}}
 
 // RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-r4 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R-THUMB %s
 // RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-r5 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R-THUMB %s
+// RUN: %clang -target armeb-linux-gnueabi -mcpu=cortex-r7 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R-THUMB %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r4 -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R-THUMB %s
 // RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r5 -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R-THUMB %s
+// RUN: %clang -target arm-linux-gnueabi -mcpu=cortex-r7 -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV7R-THUMB %s
 // CHECK-BE-CPUV7R-THUMB: "-cc1"{{.*}} "-triple" "thumbebv7r-{{.*}}
 
 // RUN: %clang -target arm -mcpu=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A %s
 // RUN: %clang -target arm -mcpu=cortex-a57 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A %s
+// RUN: %clang -target arm -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A %s
 // RUN: %clang -target arm -mcpu=cortex-a53 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A %s
 // RUN: %clang -target arm -mcpu=cortex-a57 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A %s
+// RUN: %clang -target arm -mcpu=cortex-a72 -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A %s
 // CHECK-CPUV8A: "-cc1"{{.*}} "-triple" "armv8-{{.*}}
 
 // RUN: %clang -target armeb -mcpu=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A %s
 // RUN: %clang -target armeb -mcpu=cortex-a57 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A %s
+// RUN: %clang -target armeb -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A %s
 // RUN: %clang -target arm -mcpu=cortex-a53 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A %s
 // RUN: %clang -target arm -mcpu=cortex-a57 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A %s
+// RUN: %clang -target arm -mcpu=cortex-a72 -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A %s
 // CHECK-BE-CPUV8A: "-cc1"{{.*}} "-triple" "armebv8-{{.*}}
 
 // RUN: %clang -target arm -mcpu=cortex-a53 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A-THUMB %s
 // RUN: %clang -target arm -mcpu=cortex-a57 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A-THUMB %s
+// RUN: %clang -target arm -mcpu=cortex-a72 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A-THUMB %s
 // RUN: %clang -target arm -mcpu=cortex-a53 -mlittle-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A-THUMB %s
 // RUN: %clang -target arm -mcpu=cortex-a57 -mlittle-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A-THUMB %s
+// RUN: %clang -target arm -mcpu=cortex-a72 -mlittle-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CPUV8A-THUMB %s
 // CHECK-CPUV8A-THUMB: "-cc1"{{.*}} "-triple" "thumbv8-{{.*}}
 
 // RUN: %clang -target armeb -mcpu=cortex-a53 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A-THUMB %s
 // RUN: %clang -target armeb -mcpu=cortex-a57 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A-THUMB %s
+// RUN: %clang -target armeb -mcpu=cortex-a72 -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A-THUMB %s
 // RUN: %clang -target arm -mcpu=cortex-a53 -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A-THUMB %s
 // RUN: %clang -target arm -mcpu=cortex-a57 -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A-THUMB %s
+// RUN: %clang -target arm -mcpu=cortex-a72 -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-CPUV8A-THUMB %s
 // CHECK-BE-CPUV8A-THUMB: "-cc1"{{.*}} "-triple" "thumbebv8-{{.*}}
diff --git a/test/Driver/arm-mfpu.c b/test/Driver/arm-mfpu.c
index e762478..64d7d0b 100644
--- a/test/Driver/arm-mfpu.c
+++ b/test/Driver/arm-mfpu.c
@@ -19,14 +19,6 @@
 // CHECK-FPA: "-target-feature" "-vfp3"
 // CHECK-FPA: "-target-feature" "-neon"
 
-// RUN: %clang -target arm-linux-eabi -mfpu=vfp3-d16 %s -### -o %t.o 2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-VFP3-D16 %s
-// RUN: %clang -target arm-linux-eabi -mfpu=vfpv3-d16 %s -### -o %t.o 2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-VFP3-D16 %s
-// CHECK-VFP3-D16: "-target-feature" "+vfp3"
-// CHECK-VFP3-D16: "-target-feature" "+d16"
-// CHECK-VFP3-D16: "-target-feature" "-neon"
-
 // RUN: %clang -target arm-linux-eabi -mfpu=vfp %s -### -o %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-VFP %s
 // CHECK-VFP: "-target-feature" "+vfp2"
@@ -39,6 +31,14 @@
 // CHECK-VFP3: "-target-feature" "+vfp3"
 // CHECK-VFP3: "-target-feature" "-neon"
 
+// RUN: %clang -target arm-linux-eabi -mfpu=vfp3-d16 %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-VFP3-D16 %s
+// RUN: %clang -target arm-linux-eabi -mfpu=vfpv3-d16 %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-VFP3-D16 %s
+// CHECK-VFP3-D16: "-target-feature" "+vfp3"
+// CHECK-VFP3-D16: "-target-feature" "+d16"
+// CHECK-VFP3-D16: "-target-feature" "-neon"
+
 // RUN: %clang -target arm-linux-eabi -mfpu=vfp4 %s -### -o %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-VFP4 %s
 // RUN: %clang -target arm-linux-eabi -mfpu=vfpv4 %s -### -o %t.o 2>&1 \
@@ -86,6 +86,16 @@
 // RUN:   | FileCheck --check-prefix=CHECK-NEON %s
 // CHECK-NEON: "-target-feature" "+neon"
 
+// RUN: %clang -target arm-linux-eabi -mfpu=neon-vfpv3 %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NEON-VFPV3 %s
+// CHECK-NEON-VFPV3: "-target-feature" "+vfp3"
+// CHECK-NEON-VFPV3: "-target-feature" "+neon"
+
+// RUN: %clang -target arm-linux-eabi -mfpu=neon-vfpv4 %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NEON-VFPV4 %s
+// CHECK-NEON-VFPV4: "-target-feature" "+neon"
+// CHECK-NEON-VFPV4: "-target-feature" "+vfp4"
+
 // RUN: %clang -target arm-linux-eabi -msoft-float %s -### -o %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-SOFT-FLOAT %s
 // CHECK-SOFT-FLOAT: "-target-feature" "-neon"
diff --git a/test/Driver/ast.c b/test/Driver/ast.c
index 83dfcc3..c1d7b1a 100644
--- a/test/Driver/ast.c
+++ b/test/Driver/ast.c
@@ -16,9 +16,10 @@
 
 // COMPILE-AST-PHASES: 0: input,
 // COMPILE-AST-PHASES: , ast
-// COMPILE-AST-PHASES: 1: compiler, {0}, assembler
-// COMPILE-AST-PHASES: 2: assembler, {1}, object
-// COMPILE-AST-PHASES-NOT: 3:
+// COMPILE-AST-PHASES: 1: compiler, {0}, ir
+// COMPILE-AST-PHASES: 2: backend, {1}, assembler
+// COMPILE-AST-PHASES: 3: assembler, {2}, object
+// COMPILE-AST-PHASES-NOT: 4:
 // COMPILE-AST-PHASES: END
 
 // FIXME: There is a problem with compiling AST's in that the input language is
diff --git a/test/Driver/cl-eh.cpp b/test/Driver/cl-eh.cpp
index 8a3450a..a71491e 100644
--- a/test/Driver/cl-eh.cpp
+++ b/test/Driver/cl-eh.cpp
@@ -5,18 +5,23 @@
 // command-line option, e.g. on Mac where %s is commonly under /Users.
 
 // RUN: %clang_cl /c /EHsc -### -- %s 2>&1 | FileCheck -check-prefix=EHsc %s
+// EHsc: "-fcxx-exceptions"
 // EHsc: "-fexceptions"
 
 // RUN: %clang_cl /c /EHs-c- -### -- %s 2>&1 | FileCheck -check-prefix=EHs_c_ %s
+// EHs_c_-NOT: "-fcxx-exceptions"
 // EHs_c_-NOT: "-fexceptions"
 
 // RUN: %clang_cl /c /EHs- /EHc- -### -- %s 2>&1 | FileCheck -check-prefix=EHs_EHc_ %s
+// EHs_EHc_-NOT: "-fcxx-exceptions"
 // EHs_EHc_-NOT: "-fexceptions"
 
 // RUN: %clang_cl /c /EHs- /EHs -### -- %s 2>&1 | FileCheck -check-prefix=EHs_EHs %s
+// EHs_EHs: "-fcxx-exceptions"
 // EHs_EHs: "-fexceptions"
 
 // RUN: %clang_cl /c /EHs- /EHsa -### -- %s 2>&1 | FileCheck -check-prefix=EHs_EHa %s
+// EHs_EHa: "-fcxx-exceptions"
 // EHs_EHa: "-fexceptions"
 
 // RUN: %clang_cl /c /EHinvalid -### -- %s 2>&1 | FileCheck -check-prefix=EHinvalid %s
diff --git a/test/Driver/cl-options.c b/test/Driver/cl-options.c
index 44242c8..e7ace35 100644
--- a/test/Driver/cl-options.c
+++ b/test/Driver/cl-options.c
@@ -42,6 +42,13 @@
 // RUN: %clang_cl /Gy /Gy- -### -- %s 2>&1 | FileCheck -check-prefix=Gy_ %s
 // Gy_-NOT: -ffunction-sections
 
+// RUN: %clang_cl /Gs -### -- %s 2>&1 | FileCheck -check-prefix=Gs %s
+// Gs: "-mstack-probe-size=0"
+// RUN: %clang_cl /Gs0 -### -- %s 2>&1 | FileCheck -check-prefix=Gs0 %s
+// Gs0: "-mstack-probe-size=0"
+// RUN: %clang_cl /Gs4096 -### -- %s 2>&1 | FileCheck -check-prefix=Gs4096 %s
+// Gs4096: "-mstack-probe-size=4096"
+
 // RUN: %clang_cl /Gw -### -- %s 2>&1 | FileCheck -check-prefix=Gw %s
 // Gw: -fdata-sections
 
@@ -116,6 +123,12 @@
 // RUN: %clang_cl /vmg /vmm /vms -### -- %s 2>&1 | FileCheck -check-prefix=VMX %s
 // VMX: '/vms' not allowed with '/vmm'
 
+// RUN: %clang_cl /volatile:iso -### -- %s 2>&1 | FileCheck -check-prefix=VOLATILE-ISO %s
+// VOLATILE-ISO-NOT: "-fms-volatile"
+
+// RUN: %clang_cl /volatile:ms -### -- %s 2>&1 | FileCheck -check-prefix=VOLATILE-MS %s
+// VOLATILE-MS: "-fms-volatile"
+
 // RUN: %clang_cl /W0 -### -- %s 2>&1 | FileCheck -check-prefix=W0 %s
 // W0: -w
 
@@ -164,17 +177,22 @@
 // NOSTRICT: "-relaxed-aliasing"
 
 // For some warning ids, we can map from MSVC warning to Clang warning.
-// RUN: %clang_cl -wd4005 -### -- %s 2>&1 | FileCheck -check-prefix=wd4005 %s
-// wd4005: "-cc1"
-// wd4005: "-Wno-macro-redefined"
+// RUN: %clang_cl -wd4005 -wd4996 -### -- %s 2>&1 | FileCheck -check-prefix=Wno %s
+// Wno: "-cc1"
+// Wno: "-Wno-macro-redefined"
+// Wno: "-Wno-deprecated-declarations"
 
 // Ignored options. Check that we don't get "unused during compilation" errors.
 // (/Zs is for syntax-only)
 // RUN: %clang_cl /Zs \
 // RUN:    /analyze- \
+// RUN:    /cgthreads4 \
+// RUN:    /cgthreads8 \
 // RUN:    /d2Zi+ \
 // RUN:    /errorReport:foo \
+// RUN:    /Fdfoo \
 // RUN:    /FS \
+// RUN:    /Gd \
 // RUN:    /GF \
 // RUN:    /GS- \
 // RUN:    /kernel- \
@@ -185,12 +203,9 @@
 // RUN:    /sdl \
 // RUN:    /sdl- \
 // RUN:    /vmg \
+// RUN:    /volatile:iso \
 // RUN:    /w12345 \
 // RUN:    /wd1234 \
-// RUN:    /Zc:forScope \
-// RUN:    /Zc:wchar_t \
-// RUN:    /Zc:inline \
-// RUN:    /Zc:rvalueCast \
 // RUN:    /Zo \
 // RUN:    /Zo- \
 // RUN:    -### -- %s 2>&1 | FileCheck -check-prefix=IGNORED %s
@@ -223,7 +238,6 @@
 // RUN:     /FAu \
 // RUN:     /favor:blend \
 // RUN:     /FC \
-// RUN:     /Fdfoo \
 // RUN:     /Fifoo \
 // RUN:     /Fmfoo \
 // RUN:     /FpDebug\main.pch \
@@ -245,9 +259,9 @@
 // RUN:     /Gm- \
 // RUN:     /Gr \
 // RUN:     /GS \
-// RUN:     /Gs1000 \
 // RUN:     /GT \
 // RUN:     /GX \
+// RUN:     /Gv \
 // RUN:     /Gz \
 // RUN:     /GZ \
 // RUN:     /H \
@@ -266,7 +280,7 @@
 // RUN:     /Qvec-report:2 \
 // RUN:     /u \
 // RUN:     /V \
-// RUN:     /volatile \
+// RUN:     /volatile:ms \
 // RUN:     /wfoo \
 // RUN:     /WL \
 // RUN:     /Wp64 \
@@ -280,8 +294,6 @@
 // RUN:     /Yustdafx.h \
 // RUN:     /Z7 \
 // RUN:     /Za \
-// RUN:     /Zc:auto \
-// RUN:     /Zc:wchar_t- \
 // RUN:     /Ze \
 // RUN:     /Zg \
 // RUN:     /Zi \
diff --git a/test/Driver/cl-zc.cpp b/test/Driver/cl-zc.cpp
new file mode 100644
index 0000000..639095f
--- /dev/null
+++ b/test/Driver/cl-zc.cpp
@@ -0,0 +1,59 @@
+// Don't attempt slash switches on msys bash.
+// REQUIRES: shell-preserves-root
+
+// Note: %s must be preceded by --, otherwise it may be interpreted as a
+// command-line option, e.g. on Mac where %s is commonly under /Users.
+
+// RUN: %clang_cl /c -### -- %s 2>&1 | FileCheck -check-prefix=TRIGRAPHS-DEFAULT %s
+// cc1 will disable trigraphs for -fms-compatibility as long as -ftrigraphs
+// isn't explicitly passed.
+// TRIGRAPHS-DEFAULT-NOT: "-ftrigraphs"
+
+// RUN: %clang_cl /c -### /Zc:trigraphs -- %s 2>&1 | FileCheck -check-prefix=TRIGRAPHS-ON %s
+// TRIGRAPHS-ON: "-ftrigraphs"
+
+// RUN: %clang_cl /c -### /Zc:trigraphs- -- %s 2>&1 | FileCheck -check-prefix=TRIGRAPHS-OFF %s
+// TRIGRAPHS-OFF: "-fno-trigraphs"
+
+// RUN: %clang_cl /c -### -- %s 2>&1 | FileCheck -check-prefix=STRICTSTRINGS-DEFAULT %s
+// STRICTSTRINGS-DEFAULT-NOT: -Werror=c++11-compat-deprecated-writable-strings
+// RUN: %clang_cl /c -### /Zc:strictStrings -- %s 2>&1 | FileCheck -check-prefix=STRICTSTRINGS-ON %s
+// STRICTSTRINGS-ON: -Werror=c++11-compat-deprecated-writable-strings
+// RUN: %clang_cl /c -### /Zc:strictStrings- -- %s 2>&1 | FileCheck -check-prefix=STRICTSTRINGS-OFF %s
+// STRICTSTRINGS-OFF: argument unused during compilation
+
+
+// RUN: %clang_cl /c -### /Zc:foobar -- %s 2>&1 | FileCheck -check-prefix=FOOBAR-ON %s
+// FOOBAR-ON: argument unused during compilation
+// RUN: %clang_cl /c -### /Zc:foobar- -- %s 2>&1 | FileCheck -check-prefix=FOOBAR-ON %s
+// FOOBAR-OFF: argument unused during compilation
+
+// These are ignored if enabled, and warn if disabled.
+
+// RUN: %clang_cl /c -### /Zc:forScope -- %s 2>&1 | FileCheck -check-prefix=FORSCOPE-ON %s
+// FORSCOPE-ON-NOT: argument unused during compilation
+// RUN: %clang_cl /c -### /Zc:forScope- -- %s 2>&1 | FileCheck -check-prefix=FORSCOPE-OFF %s
+// FORSCOPE-OFF: argument unused during compilation
+
+// RUN: %clang_cl /c -### /Zc:wchar_t -- %s 2>&1 | FileCheck -check-prefix=WCHAR_T-ON %s
+// WCHAR_T-ON-NOT: argument unused during compilation
+// RUN: %clang_cl /c -### /Zc:wchar_t- -- %s 2>&1 | FileCheck -check-prefix=WCHAR_T-OFF %s
+// WCHAR_T-OFF: argument unused during compilation
+
+// RUN: %clang_cl /c -### /Zc:auto -- %s 2>&1 | FileCheck -check-prefix=AUTO-ON %s
+// AUTO-ON-NOT: argument unused during compilation
+// RUN: %clang_cl /c -### /Zc:auto- -- %s 2>&1 | FileCheck -check-prefix=AUTO-OFF %s
+// AUTO-OFF: argument unused during compilation
+
+// RUN: %clang_cl /c -### /Zc:inline -- %s 2>&1 | FileCheck -check-prefix=INLINE-ON %s
+// INLINE-ON-NOT: argument unused during compilation
+// RUN: %clang_cl /c -### /Zc:inline- -- %s 2>&1 | FileCheck -check-prefix=INLINE-OFF %s
+// INLINE-OFF: argument unused during compilation
+
+
+// These never warn, but don't have an effect yet.
+
+// RUN: %clang_cl /c -### /Zc:rvalueCast -- %s 2>&1 | FileCheck -check-prefix=RVALUECAST-ON %s
+// RVALUECAST-ON-NOT: argument unused during compilation
+// RUN: %clang_cl /c -### /Zc:rvalueCast- -- %s 2>&1 | FileCheck -check-prefix=RVALUECAST-OFF %s
+// RVALUECAST-OFF: argument unused during compilation
diff --git a/test/Driver/clang-exception-flags.cpp b/test/Driver/clang-exception-flags.cpp
index 90a9ebf..a5faed2 100644
--- a/test/Driver/clang-exception-flags.cpp
+++ b/test/Driver/clang-exception-flags.cpp
@@ -1,4 +1,6 @@
-// RUN: %clang -### %s 2>&1 | FileCheck %s -check-prefix=DEFAULT
+// We force the target to unknown because clang's default behavior for
+// exception handling is target dependent.
+// RUN: %clang -### -target unknown %s 2>&1 | FileCheck %s -check-prefix=DEFAULT
 // DEFAULT: "-cc1" {{.*}} "-fcxx-exceptions" "-fexceptions"
 //
 // RUN: %clang -### -fexceptions %s 2>&1 | FileCheck %s -check-prefix=ON1
@@ -21,3 +23,6 @@
 //
 // RUN: %clang -### -fexceptions -fno-cxx-exceptions %s 2>&1 | FileCheck %s -check-prefix=OFF4
 // OFF4-NOT: "-cc1" {{.*}} "-fcxx-exceptions"
+//
+// RUN: %clang -### -target x86_64-scei-ps4 %s 2>&1 | FileCheck %s -check-prefix=PS4-OFF
+// PS4-OFF-NOT: "-cc1" {{.*}} "-f{{(cxx-)?}}exceptions"
diff --git a/test/Driver/clang-s-opts.s b/test/Driver/clang-s-opts.s
new file mode 100644
index 0000000..f292708
--- /dev/null
+++ b/test/Driver/clang-s-opts.s
@@ -0,0 +1,4 @@
+// RUN: %clang -### -c -flto -fno-lto %s 2>&1 | FileCheck %s
+// RUN: %clang -### -c -flto -fno-lto -fno-integrated-as %s 2>&1 | FileCheck %s
+
+// CHECK-NOT: argument unused during compilation
diff --git a/test/Driver/clang_f_opts.c b/test/Driver/clang_f_opts.c
index 3ca9f28..f6fe9b9 100644
--- a/test/Driver/clang_f_opts.c
+++ b/test/Driver/clang_f_opts.c
@@ -384,9 +384,13 @@
 // CHECK-NO-WARNING2-NOT: optimization flag '-finline-limit' is not supported
 
 
-// RUN: %clang -### -fshort-wchar -fno-short-wchar %s 2>&1 | FileCheck -check-prefix=CHECK-WCHAR1 %s
-// RUN: %clang -### -fno-short-wchar -fshort-wchar %s 2>&1 | FileCheck -check-prefix=CHECK-WCHAR2 %s
+// RUN: %clang -### -fshort-wchar -fno-short-wchar %s 2>&1 | FileCheck -check-prefix=CHECK-WCHAR1 -check-prefix=DELIMITERS %s
+// RUN: %clang -### -fno-short-wchar -fshort-wchar %s 2>&1 | FileCheck -check-prefix=CHECK-WCHAR2 -check-prefix=DELIMITERS %s
+// Make sure we don't match the -NOT lines with the linker invocation.
+// Delimiters match the start of the cc1 and the start of the linker lines
+// DELIMITERS: {{^ *"}}
 // CHECK-WCHAR1: -fno-short-wchar
 // CHECK-WCHAR1-NOT: -fshort-wchar
 // CHECK-WCHAR2: -fshort-wchar
 // CHECK-WCHAR2-NOT: -fno-short-wchar
+// DELIMITERS: {{^ *"}}
diff --git a/test/Driver/constructors.c b/test/Driver/constructors.c
index a8b0942..cd14ed7 100644
--- a/test/Driver/constructors.c
+++ b/test/Driver/constructors.c
@@ -7,49 +7,58 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target i386-unknown-linux \
 // RUN:     --sysroot=%S/Inputs/fake_install_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -fno-use-init-array \
 // RUN:     -target i386-unknown-linux \
 // RUN:     --sysroot=%S/Inputs/fake_install_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -fno-use-init-array -fuse-init-array \
 // RUN:     -target i386-unknown-linux \
 // RUN:     --sysroot=%S/Inputs/fake_install_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target i386-unknown-linux \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -fuse-init-array \
 // RUN:     -target i386-unknown-linux \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target arm-unknown-linux-androideabi \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target mipsel-unknown-linux-android \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target i386-unknown-linux-android \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target aarch64-none-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
@@ -59,6 +68,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target arm64-none-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-INIT-ARRAY %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
diff --git a/test/Driver/coverage-ld.c b/test/Driver/coverage-ld.c
index 0e39249..f3c3c49 100644
--- a/test/Driver/coverage-ld.c
+++ b/test/Driver/coverage-ld.c
@@ -26,3 +26,12 @@
 //
 // CHECK-FREEBSD-X86-64: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
 // CHECK-FREEBSD-X86-64: "{{.*}}/Inputs/resource_dir{{/|\\\\}}lib{{/|\\\\}}freebsd{{/|\\\\}}libclang_rt.profile-x86_64.a"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     -target arm-linux-androideabi --coverage \
+// RUN:     -resource-dir=%S/Inputs/resource_dir \
+// RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ANDROID-ARM %s
+//
+// CHECK-ANDROID-ARM: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ANDROID-ARM: "{{.*}}/Inputs/resource_dir{{/|\\\\}}lib{{/|\\\\}}linux{{/|\\\\}}libclang_rt.profile-arm-android.a"
diff --git a/test/Driver/darwin-debug-flags.c b/test/Driver/darwin-debug-flags.c
index 1b12ad5..abe3f69 100644
--- a/test/Driver/darwin-debug-flags.c
+++ b/test/Driver/darwin-debug-flags.c
@@ -5,7 +5,7 @@
 // <rdar://problem/12955296>
 // RUN: %clang -### -target i386-apple-darwin9 -c -g %t.s 2>&1 | FileCheck -check-prefix=P %s
 
-// CHECK: !0 = metadata !{
+// CHECK: !0 = !{
 // CHECK: -I path\5C with\5C \5C\5Cspaces
 // CHECK: -g -Os
 // CHECK: -mmacosx-version-min=10.5.0
diff --git a/test/Driver/darwin-dsymutil.c b/test/Driver/darwin-dsymutil.c
index 59084a2..0e2c490 100644
--- a/test/Driver/darwin-dsymutil.c
+++ b/test/Driver/darwin-dsymutil.c
@@ -6,13 +6,14 @@
 //
 // CHECK-MULTIARCH-ACTIONS: 0: input, "{{.*}}darwin-dsymutil.c", c
 // CHECK-MULTIARCH-ACTIONS: 1: preprocessor, {0}, cpp-output
-// CHECK-MULTIARCH-ACTIONS: 2: compiler, {1}, assembler
-// CHECK-MULTIARCH-ACTIONS: 3: assembler, {2}, object
-// CHECK-MULTIARCH-ACTIONS: 4: linker, {3}, image
-// CHECK-MULTIARCH-ACTIONS: 5: bind-arch, "i386", {4}, image
-// CHECK-MULTIARCH-ACTIONS: 6: bind-arch, "x86_64", {4}, image
-// CHECK-MULTIARCH-ACTIONS: 7: lipo, {5, 6}, image
-// CHECK-MULTIARCH-ACTIONS: 8: dsymutil, {7}, dSYM
+// CHECK-MULTIARCH-ACTIONS: 2: compiler, {1}, ir
+// CHECK-MULTIARCH-ACTIONS: 3: backend, {2}, assembler
+// CHECK-MULTIARCH-ACTIONS: 4: assembler, {3}, object
+// CHECK-MULTIARCH-ACTIONS: 5: linker, {4}, image
+// CHECK-MULTIARCH-ACTIONS: 6: bind-arch, "i386", {5}, image
+// CHECK-MULTIARCH-ACTIONS: 7: bind-arch, "x86_64", {5}, image
+// CHECK-MULTIARCH-ACTIONS: 8: lipo, {6, 7}, image
+// CHECK-MULTIARCH-ACTIONS: 9: dsymutil, {8}, dSYM
 //
 // RUN: %clang -target x86_64-apple-darwin10 -ccc-print-bindings \
 // RUN:   -arch i386 -arch x86_64 %s -g 2> %t
diff --git a/test/Driver/darwin-ld.c b/test/Driver/darwin-ld.c
index d3d0f1d..a5f9608 100644
--- a/test/Driver/darwin-ld.c
+++ b/test/Driver/darwin-ld.c
@@ -204,3 +204,9 @@
 // RUN: FileCheck -check-prefix=LINK_IOS_SIMULATOR_VERSION_MIN %s < %t.log
 // LINK_IPHONEOS_VERSION_MIN: -iphoneos_version_min
 // LINK_IOS_SIMULATOR_VERSION_MIN: -ios_simulator_version_min
+
+// Check -iframework gets forward to ld as -F
+// RUN: %clang -target x86_64-apple-darwin %s -iframework Bar -framework Foo -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=LINK-IFRAMEWORK %s
+// LINK-IFRAMEWORK: {{ld(.exe)?"}}
+// LINK-IFRAMEWORK: "-FBar"
diff --git a/test/Driver/darwin-verify-debug.c b/test/Driver/darwin-verify-debug.c
index 50a6cf3..ebbf89a 100644
--- a/test/Driver/darwin-verify-debug.c
+++ b/test/Driver/darwin-verify-debug.c
@@ -5,8 +5,8 @@
 // RUN: FileCheck -check-prefix=CHECK-MULTIARCH-ACTIONS < %t %s
 //
 // CHECK-MULTIARCH-ACTIONS: 0: input, "{{.*}}darwin-verify-debug.c", c
-// CHECK-MULTIARCH-ACTIONS: 8: dsymutil, {7}, dSYM
-// CHECK-MULTIARCH-ACTIONS: 9: verify-debug-info, {8}, none
+// CHECK-MULTIARCH-ACTIONS: 9: dsymutil, {8}, dSYM
+// CHECK-MULTIARCH-ACTIONS: 10: verify-debug-info, {9}, none
 //
 // RUN: %clang -target x86_64-apple-darwin10 -ccc-print-bindings \
 // RUN:   --verify-debug-info -arch i386 -arch x86_64 %s -g 2> %t
diff --git a/test/Driver/darwin-version.c b/test/Driver/darwin-version.c
index 2478a99..494c911 100644
--- a/test/Driver/darwin-version.c
+++ b/test/Driver/darwin-version.c
@@ -1,31 +1,49 @@
-// RUN: env MACOSX_DEPLOYMENT_TARGET=10.1 \
-// RUN:   %clang -target i386-apple-darwin9 -DTEST0 -E %s
-#ifdef TEST0
-#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ != 1010
-#error Invalid version
-#endif
-#endif
+// RUN: %clang -target armv6-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX %s
+// CHECK-VERSION-OSX: "armv6-apple-macosx10.5.0"
+// RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=2.0 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS2 %s
+// CHECK-VERSION-IOS2: "armv6-apple-ios2.0.0"
+// RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=2.2 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS22 %s
+// CHECK-VERSION-IOS22: "armv6-apple-ios2.2.0"
+// RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=3.0 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS3 %s
+// CHECK-VERSION-IOS3: "armv6-apple-ios3.0.0"
+// RUN: %clang -target i686-apple-darwin8 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
+// RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.4 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
+// CHECK-VERSION-OSX4: "i386-apple-macosx10.4.0"
+// RUN: %clang -target i686-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
+// RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.5 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
+// CHECK-VERSION-OSX5: "i386-apple-macosx10.5.0"
+// RUN: %clang -target i686-apple-darwin10 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
+// RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.6 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
+// CHECK-VERSION-OSX6: "i386-apple-macosx10.6.0"
+// RUN: %clang -target x86_64-apple-darwin14 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX10 %s
+// RUN: %clang -target x86_64-apple-macosx -mmacosx-version-min=10.10 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX10 %s
+// CHECK-VERSION-OSX10: "x86_64-apple-macosx10.10.0"
 
+// Check environment variable gets interpreted correctly
+// RUN: env MACOSX_DEPLOYMENT_TARGET=10.5 \
+// RUN:   %clang -target i386-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
 // RUN: env IPHONEOS_DEPLOYMENT_TARGET=2.0 \
-// RUN:   %clang -target i386-apple-darwin9 -DTEST1 -E %s
-#ifdef TEST1
-#if __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ != 20000
-#error Invalid version
-#endif
-#endif
-
-// RUN: env IPHONEOS_DEPLOYMENT_TARGET=2.3.1 \
-// RUN:   %clang -target i386-apple-darwin9 -DTEST2 -E %s
-#ifdef TEST2
-#if __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ != 20301
-#error Invalid version
-#endif
-#endif
+// RUN:   %clang -target armv6-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS2 %s
 
 // RUN: env MACOSX_DEPLOYMENT_TARGET=10.4.10 \
-// RUN:   %clang -target i386-apple-darwin9 -DTEST3 -E %s
-#ifdef TEST3
-#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ != 1049
-#error Invalid version
-#endif
-#endif
+// RUN:   %clang -target i386-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX49 %s
+// CHECK-VERSION-OSX49: "i386-apple-macosx10.4.10"
+// RUN: env IPHONEOS_DEPLOYMENT_TARGET=2.3.1 \
+// RUN:   %clang -target armv6-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS231 %s
+// CHECK-VERSION-IOS231: "armv6-apple-ios2.3.1"
diff --git a/test/Driver/default-image-name.c b/test/Driver/default-image-name.c
new file mode 100644
index 0000000..00cf7df
--- /dev/null
+++ b/test/Driver/default-image-name.c
@@ -0,0 +1,7 @@
+// RUN: %clang -target i386-unknown-linux-gnu %s -### 2>&1 | FileCheck -check-prefix=LINUX %s
+// LINUX: a.out
+
+// RUN: %clang -target i686-pc-windows-msvc %s -### 2>&1 | FileCheck -check-prefix=WIN %s
+// RUN: %clang -target i686-pc-windows-gnu %s -### 2>&1 | FileCheck -check-prefix=WIN %s
+// RUN: %clang -target i686-windows-gnu %s -### 2>&1 | FileCheck -check-prefix=WIN %s
+// WIN: a.exe
diff --git a/test/Driver/env.c b/test/Driver/env.c
new file mode 100644
index 0000000..f243fa64
--- /dev/null
+++ b/test/Driver/env.c
@@ -0,0 +1,28 @@
+// These tests try to ensure that the driver operates reasonably when run with
+// a strange environment. Unfortunately, it requires a normal shell and the
+// 'env' command.
+//
+// REQUIRES: shell
+// The PATH variable is heavily used when trying to find a linker.
+// RUN: env -i LC_ALL=C LD_LIBRARY_PATH="$LD_LIBRARY_PATH" \
+// RUN:   %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=i386-unknown-linux \
+// RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:     --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-32 %s
+//
+// RUN: env -i LC_ALL=C PATH="" LD_LIBRARY_PATH="$LD_LIBRARY_PATH" \
+// RUN:   %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=i386-unknown-linux \
+// RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:     --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-32 %s
+//
+// CHECK-LD-32-NOT: warning:
+// CHECK-LD-32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-LD-32: "{{.*}}/usr/lib/gcc/i386-unknown-linux/4.6.0{{/|\\\\}}crtbegin.o"
+// CHECK-LD-32: "-L[[SYSROOT]]/usr/lib/gcc/i386-unknown-linux/4.6.0"
+// CHECK-LD-32: "-L[[SYSROOT]]/usr/lib/gcc/i386-unknown-linux/4.6.0/../../../../i386-unknown-linux/lib"
+// CHECK-LD-32: "-L[[SYSROOT]]/usr/lib/gcc/i386-unknown-linux/4.6.0/../../.."
+// CHECK-LD-32: "-L[[SYSROOT]]/lib"
+// CHECK-LD-32: "-L[[SYSROOT]]/usr/lib"
diff --git a/test/Driver/fast-math.c b/test/Driver/fast-math.c
index 690d7a1..bacd7fe 100644
--- a/test/Driver/fast-math.c
+++ b/test/Driver/fast-math.c
@@ -25,6 +25,21 @@
 // CHECK-NO-INFS-NO-FAST-MATH: "-cc1"
 // CHECK-NO-INFS-NO-FAST-MATH-NOT: "-menable-no-infs"
 //
+// RUN: %clang -### -fno-signed-zeros -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-SIGNED-ZEROS %s
+// CHECK-NO-SIGNED-ZEROS: "-cc1"
+// CHECK-NO-SIGNED-ZEROS: "-fno-signed-zeros"
+//
+// RUN: %clang -### -fno-fast-math -fno-signed-zeros -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-FAST-MATH-NO-SIGNED-ZEROS %s
+// CHECK-NO-FAST-MATH-NO-SIGNED-ZEROS: "-cc1"
+// CHECK-NO-FAST-MATH-NO-SIGNED-ZEROS: "-fno-signed-zeros"
+//
+// RUN: %clang -### -fno-signed-zeros -fno-fast-math -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-SIGNED-ZEROS-NO-FAST-MATH %s
+// CHECK-NO-SIGNED-ZEROS-NO-FAST-MATH: "-cc1"
+// CHECK-NO-SIGNED-ZEROS-NO-FAST-MATH-NOT: "-fno-signed-zeros"
+//
 // RUN: %clang -### -fno-honor-nans -c %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-NANS %s
 // CHECK-NO-NANS: "-cc1"
diff --git a/test/Driver/fortran.f95 b/test/Driver/fortran.f95
new file mode 100644
index 0000000..9334cbe
--- /dev/null
+++ b/test/Driver/fortran.f95
@@ -0,0 +1,9 @@
+// Check that the clang driver can invoke gcc to compile Fortran.
+
+// RUN: %clang -target x86_64-unknown-linux-gnu -integrated-as -c %s -### 2>&1 \
+// RUN:   | FileCheck %s
+// CHECK: gcc
+// CHECK: "-S"
+// CHECK: "-x" "f95"
+// CHECK: clang
+// CHECK: "-cc1as"
diff --git a/test/Driver/frame-pointer-elim.c b/test/Driver/frame-pointer-elim.c
index 286cd6e..5355cbe 100644
--- a/test/Driver/frame-pointer-elim.c
+++ b/test/Driver/frame-pointer-elim.c
@@ -26,5 +26,10 @@
 // RUN:   FileCheck --check-prefix=OMIT_LEAF %s
 // OMIT_LEAF: "-momit-leaf-frame-pointer"
 
+// On the PS4, we default to omitting the frame pointer on leaf functions
+// (OMIT_LEAF check line is above)
+// RUN: %clang -### -target x86_64-scei-ps4 -S %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=OMIT_LEAF %s
+
 void f0() {}
 void f1() { f0(); }
diff --git a/test/Driver/freebsd.c b/test/Driver/freebsd.c
index 0c04fd2..a7448c1 100644
--- a/test/Driver/freebsd.c
+++ b/test/Driver/freebsd.c
@@ -128,11 +128,11 @@
 // RUN:   | FileCheck --check-prefix=CHECK-LTO %s
 // CHECK-LTO: ld{{.*}}" "-plugin{{.*}}LLVMgold.so
 
-// RUN: %clang -target sparc-unknown-freebsd8 %s -### -fpic 2>&1 \
+// RUN: %clang -target sparc-unknown-freebsd8 %s -### -fpic -no-integrated-as 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-SPARC-PIE %s
 // CHECK-SPARC-PIE: as{{.*}}" "-KPIC
 
-// RUN: %clang -mcpu=ultrasparc -target sparc64-unknown-freebsd8 %s -### 2>&1 \
+// RUN: %clang -mcpu=ultrasparc -target sparc64-unknown-freebsd8 %s -### -no-integrated-as 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-SPARC-CPU %s
 // CHECK-SPARC-CPU: cc1{{.*}}" "-target-cpu" "ultrasparc"
 // CHECK-SPARC-CPU: as{{.*}}" "-Av9a
diff --git a/test/Driver/freebsd.cc b/test/Driver/freebsd.cpp
similarity index 100%
rename from test/Driver/freebsd.cc
rename to test/Driver/freebsd.cpp
diff --git a/test/Driver/fsanitize-blacklist.c b/test/Driver/fsanitize-blacklist.c
index 690bc87..c7180de 100644
--- a/test/Driver/fsanitize-blacklist.c
+++ b/test/Driver/fsanitize-blacklist.c
@@ -3,18 +3,25 @@
 // PR12920
 // REQUIRES: clang-driver, shell
 
+// Make sure we don't match the -NOT lines with the linker invocation.
+// Delimiters match the start of the cc1 and the start of the linker lines
+// for fragile tests.
+// DELIMITERS: {{^ *"}}
+
 // RUN: echo "fun:foo" > %t.good
+// RUN: echo "fun:bar" > %t.second
 // RUN: echo "badline" > %t.bad
 
-// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.good %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-BLACKLIST
-// CHECK-BLACKLIST: -fsanitize-blacklist
+// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.good -fsanitize-blacklist=%t.second %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-BLACKLIST
+// CHECK-BLACKLIST: -fsanitize-blacklist={{.*}}.good
+// CHECK-BLACKLIST: -fsanitize-blacklist={{.*}}.second
 
 // Ignore -fsanitize-blacklist flag if there is no -fsanitize flag.
-// RUN: %clang -fsanitize-blacklist=%t.good %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-SANITIZE
+// RUN: %clang -fsanitize-blacklist=%t.good %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-SANITIZE --check-prefix=DELIMITERS
 // CHECK-NO-SANITIZE-NOT: -fsanitize-blacklist
 
 // Flag -fno-sanitize-blacklist wins if it is specified later.
-// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.good -fno-sanitize-blacklist %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-BLACKLIST
+// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.good -fno-sanitize-blacklist %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-BLACKLIST --check-prefix=DELIMITERS
 // CHECK-NO-BLACKLIST-NOT: -fsanitize-blacklist
 
 // Driver barks on unexisting blacklist files.
@@ -22,5 +29,13 @@
 // CHECK-NO-SUCH-FILE: error: no such file or directory: 'unexisting.txt'
 
 // Driver properly reports malformed blacklist files.
-// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.bad %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-BAD-BLACKLIST
-// CHECK-BAD-BLACKLIST: error: malformed sanitizer blacklist
+// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.second -fsanitize-blacklist=%t.bad -fsanitize-blacklist=%t.good %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-BAD-BLACKLIST
+// CHECK-BAD-BLACKLIST: error: malformed sanitizer blacklist: 'error parsing file '{{.*}}.bad': malformed line 1: 'badline''
+
+// -fno-sanitize-blacklist disables all blacklists specified earlier.
+// RUN: %clang -fsanitize=address -fsanitize-blacklist=%t.good -fno-sanitize-blacklist -fsanitize-blacklist=%t.second %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ONLY-FIRST-DISABLED
+// CHECK-ONLY_FIRST-DISABLED-NOT: good
+// CHECK-ONLY-FIRST-DISABLED: -fsanitize-blacklist={{.*}}.second
+// CHECK-ONLY_FIRST-DISABLED-NOT: good
+
+// DELIMITERS: {{^ *"}}
diff --git a/test/Driver/fsanitize.c b/test/Driver/fsanitize.c
index c78dfc6..97232e3 100644
--- a/test/Driver/fsanitize.c
+++ b/test/Driver/fsanitize.c
@@ -15,6 +15,12 @@
 // RUN: %clang -fsanitize=bounds -### -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=CHECK-BOUNDS
 // CHECK-BOUNDS: "-fsanitize={{((array-bounds|local-bounds),?){2}"}}
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=all %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSANITIZE-ALL
+// CHECK-FSANITIZE-ALL: error: unsupported argument 'all' to option 'fsanitize='
+
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=address,undefined -fno-sanitize=all -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FNO-SANITIZE-ALL
+// CHECK-FNO-SANITIZE-ALL: "-fsanitize=thread"
+
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=thread,undefined -fno-sanitize=thread -fno-sanitize=float-cast-overflow,vptr,bool,enum %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-PARTIAL-UNDEFINED
 // CHECK-PARTIAL-UNDEFINED: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|function|shift|unreachable|return|vla-bound|alignment|null|object-size|array-bounds|returns-nonnull-attribute|nonnull-attribute),?){14}"}}
 
@@ -25,9 +31,11 @@
 // CHECK-UNDEFINED-TRAP-ON-ERROR-VPTR: '-fsanitize=vptr' not allowed with '-fsanitize-undefined-trap-on-error'
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=vptr -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-NO-RTTI
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-NO-RTTI
 // CHECK-VPTR-NO-RTTI: '-fsanitize=vptr' not allowed with '-fno-rtti'
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-UNDEFINED-NO-RTTI
+// CHECK-UNDEFINED-NO-RTTI-NOT: vptr
+
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address,thread -fno-rtti %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANA-SANT
 // CHECK-SANA-SANT: '-fsanitize=address' not allowed with '-fsanitize=thread'
 
@@ -58,11 +66,13 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -pie %s -### 2>&1
 // OK
 
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=1 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=2 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fno-sanitize-memory-track-origins -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
-// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=0 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=1 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=2 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fno-sanitize-memory-track-origins -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=0 -fsanitize-memory-track-origins=1 -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-memory-track-origins=0 -fsanitize-memory-track-origins -pie %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TRACK-ORIGINS-2
 
 // CHECK-TRACK-ORIGINS-1: -fsanitize-memory-track-origins=1
 
@@ -84,11 +94,19 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address                       %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-0
 // CHECK-SANITIZE-COVERAGE-0-NOT: fsanitize-coverage
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=memory -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=leak -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-1
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bool -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-1
 // CHECK-SANITIZE-COVERAGE-1: fsanitize-coverage=1
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-coverage=4 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-4
 // CHECK-SANITIZE-COVERAGE-4: fsanitize-coverage=4
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-coverage=5 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-5
 // CHECK-SANITIZE-COVERAGE-5: error: invalid value '5' in '-fsanitize-coverage=5'
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread   -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-UNUSED
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-UNUSED
+// RUN: %clang -target x86_64-linux-gnu                     -fsanitize-coverage=1 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-UNUSED
+// CHECK-SANITIZE-COVERAGE-UNUSED: argument unused during compilation: '-fsanitize-coverage=1'
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-field-padding=0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-FIELD-PADDING-0
 // CHECK-ASAN-FIELD-PADDING-0-NOT: -fsanitize-address-field-padding
@@ -105,8 +123,7 @@
 // OK
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-NO-PIE
-// CHECK-TSAN-NO-PIE: "-mrelocation-model" "pic" "-pic-level" "2" "-pie-level" "2"
-// CHECK-TSAN-NO-PIE: "-pie"
+// CHECK-TSAN-NO-PIE: "-mrelocation-model" "static"
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-NO-PIE
 // CHECK-MSAN-NO-PIE: "-mrelocation-model" "pic" "-pic-level" "2" "-pie-level" "2"
@@ -121,11 +138,20 @@
 
 // RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER
 // RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover=all -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER
 // RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER
-// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover -fsanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER
-// RUZ: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover -fno-sanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER
-// CHECK-RECOVER-NOT: sanitize-recover
-// CHECK-NO-RECOVER: "-fno-sanitize-recover"
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover=all -fsanitize-recover=thread -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover -fsanitize-recover=undefined -### 2>&1 | FileCheck %s --check-prefix=CHECK-RECOVER
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover -fno-sanitize-recover -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-RECOVER
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fno-sanitize-recover=all -fsanitize-recover=object-size -### 2>&1 | FileCheck %s --check-prefix=CHECK-PARTIAL-RECOVER
+
+// CHECK-RECOVER: "-fsanitize-recover={{((signed-integer-overflow|integer-divide-by-zero|float-divide-by-zero|function|shift|vla-bound|alignment|null|vptr|object-size|float-cast-overflow|array-bounds|enum|bool|returns-nonnull-attribute|nonnull-attribute),?){16}"}}
+// CHECK-NO-RECOVER-NOT: sanitize-recover
+// CHECK-PARTIAL-RECOVER: "-fsanitize-recover=object-size"
+
+// RUN: %clang -target x86_64-linux-gnu %s -fsanitize=undefined -fsanitize-recover=address,foobar,object-size,unreachable -### 2>&1 | FileCheck %s --check-prefix=CHECK-DIAG-RECOVER
+// CHECK-DIAG-RECOVER: unsupported argument 'foobar' to option 'fsanitize-recover='
+// CHECK-DIAG-RECOVER: unsupported argument 'address,unreachable' to option 'fsanitize-recover='
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANL
 // CHECK-SANL: "-fsanitize=leak"
@@ -135,6 +161,8 @@
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN
 // CHECK-MSAN: "-fno-assume-sane-operator-new"
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN
+// CHECK-ASAN: "-fno-assume-sane-operator-new"
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=zzz %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-DIAG1
 // CHECK-DIAG1: unsupported argument 'zzz' to option 'fsanitize='
@@ -164,6 +192,10 @@
 // RUN: %clang -target x86_64-apple-darwin10 -fsanitize=function -fsanitize=undefined %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-FSAN-UBSAN-DARWIN
 // CHECK-FSAN-UBSAN-DARWIN: unsupported option '-fsanitize=function' for target 'x86_64-apple-darwin10'
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi-vptr -c %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CFI
+// CHECK-CFI: -emit-llvm-bc{{.*}}-fsanitize=cfi-vptr
+
 // RUN: %clang_cl -fsanitize=address -c -MDd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
 // RUN: %clang_cl -fsanitize=address -c -MTd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
 // RUN: %clang_cl -fsanitize=address -c -LDd -### -- %s 2>&1 | FileCheck %s -check-prefix=CHECK-ASAN-DEBUGRTL
diff --git a/test/Driver/function-sections.c b/test/Driver/function-sections.c
index fe6d303..ba065b1 100644
--- a/test/Driver/function-sections.c
+++ b/test/Driver/function-sections.c
@@ -4,6 +4,8 @@
 // CHECK-NOFS-NOT: -ffunction-sections
 // CHECK-DS: -fdata-sections
 // CHECK-NODS-NOT: -fdata-sections
+// CHECK-US-NOT: -fno-unique-section-names
+// CHECK-NOUS: -fno-unique-section-names
 
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1       \
 // RUN:     -target i386-unknown-linux \
@@ -60,3 +62,13 @@
 // RUN:     -fdata-sections -fno-data-sections -fdata-sections \
 // RUN:   | FileCheck --check-prefix=CHECK-DS %s
 
+
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1        \
+// RUN:     -target i386-unknown-linux \
+// RUN:     -funique-section-names \
+// RUN:   | FileCheck --check-prefix=CHECK-US %s
+
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1        \
+// RUN:     -target i386-unknown-linux \
+// RUN:     -fno-unique-section-names \
+// RUN:   | FileCheck --check-prefix=CHECK-NOUS %s
diff --git a/test/Driver/gcc-version-debug.c b/test/Driver/gcc-version-debug.c
index ff38c28..daa9606 100644
--- a/test/Driver/gcc-version-debug.c
+++ b/test/Driver/gcc-version-debug.c
@@ -1,4 +1,5 @@
 // RUN: %clang -v --target=i386-unknown-linux \
+// RUN:           --gcc-toolchain="" \
 // RUN:           --sysroot=%S/Inputs/debian_multiarch_tree 2>&1 | FileCheck %s
 
 // CHECK: Found candidate GCC installation: {{.*}}Inputs{{.}}debian_multiarch_tree{{.}}usr{{.}}lib{{.}}gcc{{.}}i686-linux-gnu{{.}}4.5
diff --git a/test/Driver/gcc_forward.c b/test/Driver/gcc_forward.c
index 3bc4131..4892bd9 100644
--- a/test/Driver/gcc_forward.c
+++ b/test/Driver/gcc_forward.c
@@ -11,10 +11,6 @@
 //
 // clang-cc1
 // CHECK: "-Wall" "-Wdocumentation"
-// CHECK: "-o" "{{[^"]+}}.s"
-//
-// gnu-as
-// CHECK: as{{[^"]*}}"
 // CHECK: "-o" "{{[^"]+}}.o"
 //
 // gcc-ld
diff --git a/test/Driver/gfortran.f90 b/test/Driver/gfortran.f90
index d531f59..e687e51 100644
--- a/test/Driver/gfortran.f90
+++ b/test/Driver/gfortran.f90
@@ -242,3 +242,19 @@
 !
 ! Clang understands this one and orders it weirdly.
 ! CHECK: "-fsyntax-only"
+!
+! PR22234: Ensure that -fsyntax-only doesn't complain about output types and
+!          passes along correctly.
+! RUN: %clang -no-canonical-prefixes -target i386-linux -fsyntax-only -### %s -o %t 2>&1 | \
+! grep for error message and command-line
+! RUN: grep -e error: -e -fsyntax-only | FileCheck %s --check-prefix=CHECK-PR22234
+!
+! CHECK-PR22234-NOT: clang: error: invalid output type
+! CHECK-PR22234: "-fsyntax-only"
+!
+! Regression test for the bug introduced with PR22234 fix.
+! Make sure -fsyntax-only is not passed to gfortran during normal compilation.
+!
+! RUN: %clang -no-canonical-prefixes -target i386-linux -### %s -o %t 2>&1 \
+! RUN: | FileCheck %s --check-prefix=CHECK-PR22234-R
+! CHECK-PR22234-R-NOT: "-fsyntax-only"
diff --git a/test/Driver/ident_md.c b/test/Driver/ident_md.c
index 7b2b2f6..0e664c2 100644
--- a/test/Driver/ident_md.c
+++ b/test/Driver/ident_md.c
@@ -2,5 +2,5 @@
 // Verify that clang version appears in the llvm.ident metadata.
 
 // CHECK: !llvm.ident = !{{{.*}}}
-// CHECK: !{{[0-9]+}} = metadata !{metadata !{{.*}}
+// CHECK: !{{[0-9]+}} = !{!{{.*}}
 
diff --git a/test/Driver/inline-asm.c b/test/Driver/inline-asm.c
new file mode 100644
index 0000000..bafd03d
--- /dev/null
+++ b/test/Driver/inline-asm.c
@@ -0,0 +1,24 @@
+// RUN: %clang -target x86_64-apple-darwin10 \
+// RUN:   -### -fsyntax-only -fasm-blocks %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-BLOCKS < %t %s
+
+// RUN: %clang -target x86_64-apple-darwin10 \
+// RUN:   -### -fsyntax-only -fno-asm-blocks -fasm-blocks %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-BLOCKS < %t %s
+
+// CHECK-BLOCKS: "-fasm-blocks"
+
+// RUN: %clang -target x86_64-apple-darwin10 \
+// RUN:   -### -fsyntax-only -fasm-blocks -fno-asm-blocks %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-NO-BLOCKS < %t %s
+
+// CHECK-NO-BLOCKS-NOT: "-fasm-blocks"
+
+// RUN: %clang -target x86_64-apple-darwin10 \
+// RUN:   -### -fsyntax-only -fno-gnu-inline-asm %s 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-NO-GNU-INLINE-ASM %s
+// RUN: %clang -target x86_64-apple-darwin10 \
+// RUN:   -### -fsyntax-only -fgnu-inline-asm -fno-gnu-inline-asm %s 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-NO-GNU-INLINE-ASM %s
+
+// CHECK-NO-GNU-INLINE-ASM: "-fno-gnu-inline-asm"
diff --git a/test/Driver/linux-header-search.cpp b/test/Driver/linux-header-search.cpp
index 309ece2..574ae22 100644
--- a/test/Driver/linux-header-search.cpp
+++ b/test/Driver/linux-header-search.cpp
@@ -8,6 +8,7 @@
 // RUN:     -stdlib=libc++ \
 // RUN:     -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
 // RUN:     --sysroot=%S/Inputs/basic_linux_libcxx_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-SYSROOT %s
 // CHECK-BASIC-LIBCXX-SYSROOT: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-isysroot" "[[SYSROOT:[^"]+]]"
@@ -18,6 +19,7 @@
 // RUN:     -stdlib=libc++ \
 // RUN:     -ccc-install-dir %S/Inputs/basic_linux_libcxx_tree/usr/bin \
 // RUN:     --sysroot=%S/Inputs/basic_linux_libcxx_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-INSTALL %s
 // CHECK-BASIC-LIBCXX-INSTALL: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
 // CHECK-BASIC-LIBCXX-INSTALL: "-isysroot" "[[SYSROOT:[^"]+]]"
@@ -28,28 +30,32 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target i386-unknown-linux \
 // RUN:     --sysroot=%S/Inputs/ubuntu_11.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-11-04 %s
 // CHECK-UBUNTU-11-04: "{{.*}}clang{{.*}}" "-cc1"
+// CHECK-UBUNTU-11-04: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-UBUNTU-11-04: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5"
 // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/i686-linux-gnu"
 // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5/../../../../../include/c++/4.5/backward"
 // CHECK-UBUNTU-11-04: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-UBUNTU-11-04: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-UBUNTU-11-04: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-UBUNTU-11-04: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-UBUNTU-11-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/ubuntu_13.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-13-04 %s
 // CHECK-UBUNTU-13-04: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-UBUNTU-13-04: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-UBUNTU-13-04: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-UBUNTU-13-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7"
 // CHECK-UBUNTU-13-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/x86_64-linux-gnu/c++/4.7"
 // CHECK-UBUNTU-13-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/backward"
 // CHECK-UBUNTU-13-04: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-UBUNTU-13-04: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-UBUNTU-13-04: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-UBUNTU-13-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/x86_64-linux-gnu"
 // CHECK-UBUNTU-13-04: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-UBUNTU-13-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
@@ -57,14 +63,16 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnux32 \
 // RUN:     --sysroot=%S/Inputs/ubuntu_14.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-14-04 %s
 // CHECK-UBUNTU-14-04: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-UBUNTU-14-04: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-UBUNTU-14-04: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-UBUNTU-14-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8"
 // CHECK-UBUNTU-14-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../include/x86_64-linux-gnu/c++/4.8/x32"
 // CHECK-UBUNTU-14-04: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/backward"
 // CHECK-UBUNTU-14-04: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-UBUNTU-14-04: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|x32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-UBUNTU-14-04: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-UBUNTU-14-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/x86_64-linux-gnu"
 // CHECK-UBUNTU-14-04: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-UBUNTU-14-04: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
@@ -72,14 +80,16 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target arm-linux-gnueabihf \
 // RUN:     --sysroot=%S/Inputs/ubuntu_13.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-13-04-CROSS %s
 // CHECK-UBUNTU-13-04-CROSS: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-UBUNTU-13-04-CROSS: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-UBUNTU-13-04-CROSS: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-UBUNTU-13-04-CROSS: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc-cross/arm-linux-gnueabihf/4.7/../../../../include/c++/4.7"
 // CHECK-UBUNTU-13-04-CROSS: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc-cross/arm-linux-gnueabihf/4.7/../../../../include/arm-linux-gnueabihf/c++/4.7"
 // CHECK-UBUNTU-13-04-CROSS: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc-cross/arm-linux-gnueabihf/4.7/../../../../include/c++/4.7/backward"
 // CHECK-UBUNTU-13-04-CROSS: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-UBUNTU-13-04-CROSS: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-UBUNTU-13-04-CROSS: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-UBUNTU-13-04-CROSS: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-UBUNTU-13-04-CROSS: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 //
@@ -87,6 +97,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnu -m32 \
 // RUN:     --sysroot=%S/Inputs/ubuntu_13.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-13-04-M32 %s
 // CHECK-UBUNTU-13-04-M32: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
 // CHECK-UBUNTU-13-04-M32: "-triple" "i386-unknown-linux-gnu"
@@ -100,6 +111,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnu -m32 \
 // RUN:     --sysroot=%S/Inputs/ubuntu_14.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-14-04-M32 %s
 // CHECK-UBUNTU-14-04-M32: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
 // CHECK-UBUNTU-14-04-M32: "-triple" "i386-unknown-linux-gnu"
@@ -114,6 +126,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnu -m32 \
 // RUN:     --sysroot=%S/Inputs/ubuntu_14.04_multiarch_tree2 \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-14-04-I686 %s
 // CHECK-UBUNTU-14-04-I686: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
 // CHECK-UBUNTU-14-04-I686: "-triple" "i386-unknown-linux-gnu"
@@ -126,6 +139,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target powerpc64le-unknown-linux-gnu -m32 \
 // RUN:     --sysroot=%S/Inputs/ubuntu_14.04_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-14-04-PPC64LE %s
 // CHECK-UBUNTU-14-04-PPC64LE: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
 // CHECK-UBUNTU-14-04-PPC64LE: "-triple" "powerpc64le-unknown-linux-gnu"
@@ -141,56 +155,64 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target i686-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-X86 %s
 // CHECK-DEBIAN-X86: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-DEBIAN-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-DEBIAN-X86: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-DEBIAN-X86: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/i686-linux-gnu/4.5/../../../../include/c++/4.5"
 // CHECK-DEBIAN-X86: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/i686-linux-gnu/4.5/../../../../include/c++/4.5/i686-linux-gnu"
 // CHECK-DEBIAN-X86: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/i686-linux-gnu/4.5/../../../../include/c++/4.5/backward"
 // CHECK-DEBIAN-X86: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-DEBIAN-X86: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-DEBIAN-X86: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-DEBIAN-X86: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/i386-linux-gnu"
 // CHECK-DEBIAN-X86: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-DEBIAN-X86: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-X86-64 %s
 // CHECK-DEBIAN-X86-64: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-DEBIAN-X86-64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-DEBIAN-X86-64: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-DEBIAN-X86-64: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.5/../../../../include/c++/4.5"
 // CHECK-DEBIAN-X86-64: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.5/../../../../include/c++/4.5/x86_64-linux-gnu"
 // CHECK-DEBIAN-X86-64: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-linux-gnu/4.5/../../../../include/c++/4.5/backward"
 // CHECK-DEBIAN-X86-64: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-DEBIAN-X86-64: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-DEBIAN-X86-64: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-DEBIAN-X86-64: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/x86_64-linux-gnu"
 // CHECK-DEBIAN-X86-64: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-DEBIAN-X86-64: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target powerpc-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-PPC %s
 // CHECK-DEBIAN-PPC: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-DEBIAN-PPC: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-DEBIAN-PPC: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-DEBIAN-PPC: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/powerpc-linux-gnu/4.5/../../../../include/c++/4.5"
 // CHECK-DEBIAN-PPC: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/powerpc-linux-gnu/4.5/../../../../include/c++/4.5/powerpc-linux-gnu"
 // CHECK-DEBIAN-PPC: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/powerpc-linux-gnu/4.5/../../../../include/c++/4.5/backward"
 // CHECK-DEBIAN-PPC: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-DEBIAN-PPC: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-DEBIAN-PPC: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-DEBIAN-PPC: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/powerpc-linux-gnu"
 // CHECK-DEBIAN-PPC: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-DEBIAN-PPC: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target powerpc64-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-PPC64 %s
 // CHECK-DEBIAN-PPC64: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-DEBIAN-PPC64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-DEBIAN-PPC64: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-DEBIAN-PPC64: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/powerpc64-linux-gnu/4.5/../../../../include/c++/4.5"
 // CHECK-DEBIAN-PPC64: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/powerpc64-linux-gnu/4.5/../../../../include/c++/4.5/powerpc64-linux-gnu"
 // CHECK-DEBIAN-PPC64: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/powerpc64-linux-gnu/4.5/../../../../include/c++/4.5/backward"
 // CHECK-DEBIAN-PPC64: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-DEBIAN-PPC64: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-DEBIAN-PPC64: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-DEBIAN-PPC64: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/powerpc64-linux-gnu"
 // CHECK-DEBIAN-PPC64: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-DEBIAN-PPC64: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
@@ -200,27 +222,31 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/gentoo_linux_gcc_4.6.2_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-GENTOO-4-6-2 %s
 // CHECK-GENTOO-4-6-2: "{{.*}}clang{{.*}}" "-cc1"
+// CHECK-GENTOO-4-6-2: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-GENTOO-4-6-2: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-GENTOO-4-6-2: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-pc-linux-gnu/4.6.2/include/g++-v4"
 // CHECK-GENTOO-4-6-2: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-pc-linux-gnu/4.6.2/include/g++-v4/x86_64-pc-linux-gnu"
 // CHECK-GENTOO-4-6-2: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-pc-linux-gnu/4.6.2/include/g++-v4/backward"
 // CHECK-GENTOO-4-6-2: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-GENTOO-4-6-2: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-GENTOO-4-6-2: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-GENTOO-4-6-2: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-GENTOO-4-6-2: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target x86_64-unknown-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/gentoo_linux_gcc_4.6.4_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-GENTOO-4-6-4 %s
 // CHECK-GENTOO-4-6-4: "{{.*}}clang{{.*}}" "-cc1"
+// CHECK-GENTOO-4-6-4: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-GENTOO-4-6-4: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-GENTOO-4-6-4: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-pc-linux-gnu/4.6.4/include/g++-v4.6"
 // CHECK-GENTOO-4-6-4: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-pc-linux-gnu/4.6.4/include/g++-v4.6/x86_64-pc-linux-gnu"
 // CHECK-GENTOO-4-6-4: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/x86_64-pc-linux-gnu/4.6.4/include/g++-v4.6/backward"
 // CHECK-GENTOO-4-6-4: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-GENTOO-4-6-4: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-GENTOO-4-6-4: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-GENTOO-4-6-4: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-GENTOO-4-6-4: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
 //
@@ -228,14 +254,16 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target mips64-unknown-linux-gnuabi64 \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips64_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64-GNUABI %s
 // CHECK-MIPS64-GNUABI: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-MIPS64-GNUABI: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-MIPS64-GNUABI: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-MIPS64-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/mips64-linux-gnuabi64/4.9/../../../../include/c++/4.9"
 // CHECK-MIPS64-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/mips64-linux-gnuabi64/4.9/../../../../include/c++/4.9/mips64-linux-gnuabi64"
 // CHECK-MIPS64-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/mips64-linux-gnuabi64/4.9/../../../../include/c++/4.9/backward"
 // CHECK-MIPS64-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-MIPS64-GNUABI: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-MIPS64-GNUABI: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-MIPS64-GNUABI: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/mips64-linux-gnuabi64"
 // CHECK-MIPS64-GNUABI: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-MIPS64-GNUABI: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
@@ -244,14 +272,16 @@
 // RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
 // RUN:     -target mips64el-unknown-linux-gnuabi64 \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips64_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-GNUABI %s
 // CHECK-MIPS64EL-GNUABI: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-MIPS64EL-GNUABI: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-MIPS64EL-GNUABI: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-MIPS64EL-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/mips64el-linux-gnuabi64/4.9/../../../../include/c++/4.9"
 // CHECK-MIPS64EL-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/mips64el-linux-gnuabi64/4.9/../../../../include/c++/4.9/mips64el-linux-gnuabi64"
 // CHECK-MIPS64EL-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/lib/gcc/mips64el-linux-gnuabi64/4.9/../../../../include/c++/4.9/backward"
 // CHECK-MIPS64EL-GNUABI: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-// CHECK-MIPS64EL-GNUABI: "-internal-isystem" "{{.*}}{{/|\\\\}}lib{{(64|32)?}}{{/|\\\\}}clang{{/|\\\\}}{{[0-9]\.[0-9]\.[0-9]}}{{/|\\\\}}include"
+// CHECK-MIPS64EL-GNUABI: "-internal-isystem" "[[RESOURCE_DIR]]{{/|\\\\}}include"
 // CHECK-MIPS64EL-GNUABI: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/mips64el-linux-gnuabi64"
 // CHECK-MIPS64EL-GNUABI: "-internal-externc-isystem" "[[SYSROOT]]/include"
 // CHECK-MIPS64EL-GNUABI: "-internal-externc-isystem" "[[SYSROOT]]/usr/include"
diff --git a/test/Driver/linux-ld.c b/test/Driver/linux-ld.c
index b3c1aeb..b431b1c 100644
--- a/test/Driver/linux-ld.c
+++ b/test/Driver/linux-ld.c
@@ -3,6 +3,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-32 %s
 // CHECK-LD-32-NOT: warning:
@@ -16,6 +17,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-64 %s
 // CHECK-LD-64-NOT: warning:
@@ -35,6 +37,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux-gnux32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-X32 %s
 // CHECK-LD-X32-NOT: warning:
@@ -48,6 +51,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:     --rtlib=compiler-rt \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-RT %s
@@ -67,7 +71,23 @@
 // CHECK-LD-RT: libclang_rt.builtins-x86_64.a" "-lgcc_s"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=arm-linux-androideabi \
+// RUN:     --gcc-toolchain="" \
+// RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:     --rtlib=compiler-rt \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-RT-ANDROID %s
+// CHECK-LD-RT-ANDROID-NOT: warning:
+// CHECK-LD-RT-ANDROID: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-LD-RT-ANDROID: "--eh-frame-hdr"
+// CHECK-LD-RT-ANDROID: "-m" "armelf_linux_eabi"
+// CHECK-LD-RT-ANDROID: "-dynamic-linker"
+// CHECK-LD-RT-ANDROID: libclang_rt.builtins-arm-android.a" "-lgcc_s"
+// CHECK-LD-RT-ANDROID: "-lc"
+// CHECK-LD-RT-ANDROID: libclang_rt.builtins-arm-android.a" "-lgcc_s"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:     --rtlib=libgcc \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-GCC %s
@@ -89,6 +109,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux \
 // RUN:     -static-libgcc \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-64-STATIC-LIBGCC %s
 // CHECK-LD-64-STATIC-LIBGCC-NOT: warning:
@@ -109,6 +130,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux \
 // RUN:     -static \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-64-STATIC %s
 // CHECK-LD-64-STATIC-NOT: warning:
@@ -129,11 +151,13 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux \
 // RUN:     -static-libgcc -static \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-64-STATIC %s
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_32bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-32-TO-32 %s
 // CHECK-32-TO-32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -150,6 +174,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m64 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_32bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-32-TO-64 %s
 // CHECK-32-TO-64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -167,6 +192,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux -m64 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-64-TO-64 %s
 // CHECK-64-TO-64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -183,6 +209,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux -m32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-64-TO-32 %s
 // CHECK-64-TO-32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -200,6 +227,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux-gnux32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-X32 %s
 // CHECK-X32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -217,6 +245,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux -mx32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-64-TO-X32 %s
 // CHECK-64-TO-X32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -234,6 +263,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -mx32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-32-TO-X32 %s
 // CHECK-32-TO-X32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -251,6 +281,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux-gnux32 -m64 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-X32-TO-64 %s
 // CHECK-X32-TO-64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -267,6 +298,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux-gnux32 -m32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/multilib_64bit_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-X32-TO-32 %s
 // CHECK-X32-TO-32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -299,6 +331,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m32 \
 // RUN:     -ccc-install-dir %S/Inputs/fake_install_tree/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-INSTALL-DIR-32 %s
 // CHECK-INSTALL-DIR-32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -310,6 +343,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux -m64 \
 // RUN:     -ccc-install-dir %S/Inputs/fake_install_tree/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-INSTALL-DIR-64 %s
 // CHECK-INSTALL-DIR-64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -321,6 +355,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m32 \
 // RUN:     -ccc-install-dir %S/Inputs/gcc_version_parsing1/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-GCC-VERSION1 %s
 // CHECK-GCC-VERSION1: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -329,6 +364,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m32 \
 // RUN:     -ccc-install-dir %S/Inputs/gcc_version_parsing2/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-GCC-VERSION2 %s
 // CHECK-GCC-VERSION2: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -337,6 +373,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m32 \
 // RUN:     -ccc-install-dir %S/Inputs/gcc_version_parsing3/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-GCC-VERSION3 %s
 // CHECK-GCC-VERSION3: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -345,6 +382,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux -m32 \
 // RUN:     -ccc-install-dir %S/Inputs/gcc_version_parsing4/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-GCC-VERSION4 %s
 // CHECK-GCC-VERSION4: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -357,6 +395,7 @@
 // RUN:     -target x86_64-unknown-linux-gnu \
 // RUN:     -stdlib=libc++ \
 // RUN:     -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_libcxx_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-SYSROOT %s
 // CHECK-BASIC-LIBCXX-SYSROOT: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
@@ -368,6 +407,7 @@
 // RUN:     -target x86_64-unknown-linux-gnu \
 // RUN:     -stdlib=libc++ \
 // RUN:     -ccc-install-dir %S/Inputs/basic_linux_libcxx_tree/usr/bin \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_linux_libcxx_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-INSTALL %s
 // CHECK-BASIC-LIBCXX-INSTALL: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
@@ -380,6 +420,7 @@
 // Test a very broken version of multiarch that shipped in Ubuntu 11.04.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i386-unknown-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/ubuntu_11.04_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-11-04 %s
 // CHECK-UBUNTU-11-04: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -394,6 +435,7 @@
 // Check multi arch support on Ubuntu 12.04 LTS.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-unknown-linux-gnueabihf \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/ubuntu_12.04_LTS_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-12-04-ARM-HF %s
 // CHECK-UBUNTU-12-04-ARM-HF: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -411,6 +453,7 @@
 // Check Ubuntu 13.10 on x86-64 targeting arm-linux-gnueabihf.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-gnueabihf \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/x86-64_ubuntu_13.10 \
 // RUN:   | FileCheck --check-prefix=CHECK-X86-64-UBUNTU-13-10-ARM-HF %s
 // CHECK-X86-64-UBUNTU-13-10-ARM-HF: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -429,6 +472,7 @@
 // Check Ubuntu 13.10 on x86-64 targeting arm-linux-gnueabi.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-gnueabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/x86-64_ubuntu_13.10 \
 // RUN:   | FileCheck --check-prefix=CHECK-X86-64-UBUNTU-13-10-ARM %s
 // CHECK-X86-64-UBUNTU-13-10-ARM: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -447,6 +491,7 @@
 // Check Ubuntu 14.04 on powerpc64le.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=powerpc64le-unknown-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/ubuntu_14.04_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-14-04-PPC64LE %s
 // CHECK-UBUNTU-14-04-PPC64LE: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -465,6 +510,7 @@
 // "/usr/lib/gcc/x86_64-linux-gnu/4.8/x32/crtend.o" "/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../../libx32/crtn.o"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-unknown-linux-gnux32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/ubuntu_14.04_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-14-04-X32 %s
 // CHECK-UBUNTU-14-04-X32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -484,6 +530,7 @@
 // Check fedora 18 on arm.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=armv7-unknown-linux-gnueabihf \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/fedora_18_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-FEDORA-18-ARM-HF %s
 // CHECK-FEDORA-18-ARM-HF: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -498,10 +545,12 @@
 // Check Fedora 21 on AArch64.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm64-unknown-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/fedora_21_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-FEDORA-21-AARCH64 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-unknown-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/fedora_21_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-FEDORA-21-AARCH64 %s
 // CHECK-FEDORA-21-AARCH64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -515,6 +564,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-unknown-linux-gnueabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/ubuntu_12.04_LTS_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-UBUNTU-12-04-ARM %s
 // CHECK-UBUNTU-12-04-ARM: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -532,6 +582,7 @@
 // Test the setup that shipped in SUSE 10.3 on ppc64.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=powerpc64-suse-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/suse_10.3_ppc64_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-SUSE-10-3-PPC64 %s
 // CHECK-SUSE-10-3-PPC64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -701,6 +752,7 @@
 // Thoroughly exercise the Debian multiarch environment.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-X86 %s
 // CHECK-DEBIAN-X86: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -713,6 +765,7 @@
 // CHECK-DEBIAN-X86: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-X86-64 %s
 // CHECK-DEBIAN-X86-64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -725,6 +778,7 @@
 // CHECK-DEBIAN-X86-64: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=powerpc-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-PPC %s
 // CHECK-DEBIAN-PPC: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -737,6 +791,7 @@
 // CHECK-DEBIAN-PPC: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=powerpc64-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-PPC64 %s
 // CHECK-DEBIAN-PPC64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -749,6 +804,7 @@
 // CHECK-DEBIAN-PPC64: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPS %s
 // CHECK-DEBIAN-MIPS: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -761,6 +817,7 @@
 // CHECK-DEBIAN-MIPS: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPSEL %s
 // CHECK-DEBIAN-MIPSEL: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -773,6 +830,7 @@
 // CHECK-DEBIAN-MIPSEL: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPS64 %s
 // CHECK-DEBIAN-MIPS64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -784,6 +842,7 @@
 // CHECK-DEBIAN-MIPS64: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPS64EL %s
 // CHECK-DEBIAN-MIPS64EL: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -795,6 +854,7 @@
 // CHECK-DEBIAN-MIPS64EL: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64-linux-gnu -mabi=n32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPS64-N32 %s
 // CHECK-DEBIAN-MIPS64-N32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -806,6 +866,7 @@
 // CHECK-DEBIAN-MIPS64-N32: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-gnu -mabi=n32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_multiarch_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPS64EL-N32 %s
 // CHECK-DEBIAN-MIPS64EL-N32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -819,34 +880,42 @@
 // Test linker invocation on Android.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID %s
 // CHECK-ANDROID: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -859,16 +928,19 @@
 // CHECK-ANDROID: "{{.*}}{{/|\\\\}}crtend_android.o"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
@@ -879,21 +951,25 @@
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-SO %s
@@ -908,6 +984,7 @@
 // CHECK-ANDROID-SO: "{{.*}}{{/|\\\\}}crtend_so.o"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -static \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
@@ -918,6 +995,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -static \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
@@ -928,21 +1006,25 @@
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -static \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -static \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -static \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -static \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-STATIC %s
@@ -956,41 +1038,49 @@
 // CHECK-ANDROID-STATIC: "{{.*}}{{/|\\\\}}crtend_android.o"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot  \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot  \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot  \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -pie \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PIE %s
@@ -1003,34 +1093,42 @@
 // CHECK-ANDROID-PIE: "{{.*}}{{/|\\\\}}crtend_android.o"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-32 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-32 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-32 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-64 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-64 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-64 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-32 %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-64 %s
 // CHECK-ANDROID-32: "-dynamic-linker" "/system/bin/linker"
@@ -1039,18 +1137,22 @@
 // Test that -pthread does not add -lpthread on Android.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm64-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
@@ -1059,53 +1161,64 @@
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-androideabi -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=aarch64-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=arm64-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=i686-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=x86_64-linux-android -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:     -shared \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD %s
@@ -1113,6 +1226,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %t.o -### -o %t 2>&1 \
 // RUN:     --target=arm-linux-androideabi -pthread \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN:   | FileCheck --check-prefix=CHECK-ANDROID-PTHREAD-LINK %s
 // CHECK-ANDROID-PTHREAD-LINK-NOT: argument unused during compilation: '-pthread'
@@ -1120,6 +1234,7 @@
 // Check linker invocation on Debian 6 MIPS 32/64-bit.
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-ML-MIPSEL %s
 // CHECK-DEBIAN-ML-MIPSEL: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1136,6 +1251,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-gnu \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-ML-MIPS64EL %s
 // CHECK-DEBIAN-ML-MIPS64EL: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1152,6 +1268,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-gnu -mabi=n32 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-ML-MIPS64EL-N32 %s
 // CHECK-DEBIAN-ML-MIPS64EL-N32: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1168,6 +1285,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64-linux-gnuabi64 -mabi=n64 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips64_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-ML-MIPS64-GNUABI %s
 // CHECK-DEBIAN-ML-MIPS64-GNUABI: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1187,6 +1305,7 @@
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips64el-linux-gnuabi64 -mabi=n64 \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/debian_6_mips64_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-ML-MIPS64EL-GNUABI %s
 // CHECK-DEBIAN-ML-MIPS64EL-GNUABI: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1207,6 +1326,7 @@
 // Test linker invocation for Freescale SDK (OpenEmbedded).
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=powerpc-fsl-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/freescale_ppc_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-FSL-PPC %s
 // CHECK-FSL-PPC: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1216,6 +1336,7 @@
 // CHECK-FSL-PPC: "-L[[SYSROOT]]/usr/lib"
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=powerpc64-fsl-linux \
+// RUN:     --gcc-toolchain="" \
 // RUN:     --sysroot=%S/Inputs/freescale_ppc64_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-FSL-PPC64 %s
 // CHECK-FSL-PPC64: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
@@ -1226,41 +1347,53 @@
 //
 // Check that crtfastmath.o is linked with -ffast-math and with -Ofast.
 // RUN: %clang --target=x86_64-unknown-linux -### %s \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NOCRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -ffast-math \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -funsafe-math-optimizations\
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -Ofast\
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -Ofast -O3\
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NOCRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -O3 -Ofast\
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -ffast-math -fno-fast-math \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NOCRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -Ofast -fno-fast-math \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -Ofast -fno-unsafe-math-optimizations \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -fno-fast-math -Ofast  \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // RUN: %clang --target=x86_64-unknown-linux -### %s -fno-unsafe-math-optimizations -Ofast \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-CRTFASTMATH %s
 // We don't have crtfastmath.o in the i386 tree, use it to check that file
 // detection works.
 // RUN: %clang --target=i386-unknown-linux -### %s -ffast-math \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NOCRTFASTMATH %s
 // CHECK-CRTFASTMATH: usr/lib/gcc/x86_64-unknown-linux/4.6.0{{/|\\\\}}crtfastmath.o
@@ -1268,12 +1401,32 @@
 
 // Check that we link in gcrt1.o when compiling with -pg
 // RUN: %clang -pg --target=x86_64-unknown-linux -### %s \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>& 1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PG %s
 // CHECK-PG: gcrt1.o
 
 // GCC forwards -u to the linker.
 // RUN: %clang -u asdf --target=x86_64-unknown-linux -### %s \
+// RUN:        --gcc-toolchain="" \
 // RUN:        --sysroot=%S/Inputs/basic_linux_tree 2>& 1 \
 // RUN:   | FileCheck --check-prefix=CHECK-u %s
 // CHECK-u: "-u" "asdf"
+
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=armeb-unknown-linux \
+// RUN:     --gcc-toolchain="" \
+// RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-ARMEB %s
+// CHECK-ARMEB: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-ARMEB-NOT: "--be8"
+// CHECK-ARMEB: "-m" "armebelf_linux_eabi"
+
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=armebv7-unknown-linux \
+// RUN:     --gcc-toolchain="" \
+// RUN:     --sysroot=%S/Inputs/basic_linux_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-ARMV7EB %s
+// CHECK-ARMV7EB: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-ARMV7EB: "--be8"
+// CHECK-ARMV7EB: "-m" "armebelf_linux_eabi"
diff --git a/test/Driver/lto.c b/test/Driver/lto.c
index 91524bf..62300bd 100644
--- a/test/Driver/lto.c
+++ b/test/Driver/lto.c
@@ -1,19 +1,22 @@
 // -flto causes a switch to llvm-bc object files.
 // RUN: %clang -ccc-print-phases -c %s -flto 2> %t.log
-// RUN: grep '2: compiler, {1}, lto-bc' %t.log
+// RUN: grep '2: compiler, {1}, ir' %t.log
+// RUN: grep '3: backend, {2}, lto-bc' %t.log
 
 // RUN: %clang -ccc-print-phases %s -flto 2> %t.log
 // RUN: grep '0: input, ".*lto.c", c' %t.log
 // RUN: grep '1: preprocessor, {0}, cpp-output' %t.log
-// RUN: grep '2: compiler, {1}, lto-bc' %t.log
-// RUN: grep '3: linker, {2}, image' %t.log
+// RUN: grep '2: compiler, {1}, ir' %t.log
+// RUN: grep '3: backend, {2}, lto-bc' %t.log
+// RUN: grep '4: linker, {3}, image' %t.log
 
 // llvm-bc and llvm-ll outputs need to match regular suffixes
 // (unfortunately).
 // RUN: %clang %s -flto -save-temps -### 2> %t.log
 // RUN: grep '"-o" ".*lto\.i" "-x" "c" ".*lto\.c"' %t.log
-// RUN: grep '"-o" ".*lto\.o" .*".*lto\.i"' %t.log
-// RUN: grep '".*a.out" .*".*lto\.o"' %t.log
+// RUN: grep '"-o" ".*lto\.bc" .*".*lto\.i"' %t.log
+// RUN: grep '"-o" ".*lto\.o" .*".*lto\.bc"' %t.log
+// RUN: grep '".*a\.\(out\|exe\)" .*".*lto\.o"' %t.log
 
 // RUN: %clang %s -flto -S -### 2> %t.log
 // RUN: grep '"-o" ".*lto\.s" "-x" "c" ".*lto\.c"' %t.log
diff --git a/test/Driver/mg.c b/test/Driver/mg.c
index 4f43814..82d8a60 100644
--- a/test/Driver/mg.c
+++ b/test/Driver/mg.c
@@ -1,5 +1,5 @@
-// RUN: %clang -M -MG -include nonexistent-preinclude.h %s > %t
-// RUN: fgrep nonexistent-preinclude.h %t
-// RUN: fgrep nonexistent-ppinclude.h %t
+// RUN: %clang -M -MG -include nonexistent-preinclude.h %s | FileCheck %s
+// CHECK: nonexistent-preinclude.h
+// CHECK: nonexistent-ppinclude.h
 
 #include "nonexistent-ppinclude.h"
diff --git a/test/Driver/mips-as.c b/test/Driver/mips-as.c
index 12f1844..755ae83 100644
--- a/test/Driver/mips-as.c
+++ b/test/Driver/mips-as.c
@@ -98,6 +98,16 @@
 // RUN:   | FileCheck -check-prefix=MIPS-ALIAS-32R2 %s
 // MIPS-ALIAS-32R2: as{{(.exe)?}}" "-march" "mips32r2" "-mabi" "32" "-mno-shared" "-call_nonpic" "-EB"
 //
+// RUN: %clang -target mips-linux-gnu -mips32r3 -### \
+// RUN:   -no-integrated-as -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=MIPS-ALIAS-32R3 %s
+// MIPS-ALIAS-32R3: as{{(.exe)?}}" "-march" "mips32r3" "-mabi" "32" "-mno-shared" "-call_nonpic" "-EB"
+//
+// RUN: %clang -target mips-linux-gnu -mips32r5 -### \
+// RUN:   -no-integrated-as -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=MIPS-ALIAS-32R5 %s
+// MIPS-ALIAS-32R5: as{{(.exe)?}}" "-march" "mips32r5" "-mabi" "32" "-mno-shared" "-call_nonpic" "-EB"
+//
 // RUN: %clang -target mips-linux-gnu -mips32r6 -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=MIPS-ALIAS-32R6 %s
@@ -113,6 +123,16 @@
 // RUN:   | FileCheck -check-prefix=MIPS-ALIAS-64R2 %s
 // MIPS-ALIAS-64R2: as{{(.exe)?}}" "-march" "mips64r2" "-mabi" "64" "-mno-shared" "-KPIC" "-EB"
 //
+// RUN: %clang -target mips64-linux-gnu -mips64r3 -### \
+// RUN:   -no-integrated-as -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=MIPS-ALIAS-64R3 %s
+// MIPS-ALIAS-64R3: as{{(.exe)?}}" "-march" "mips64r3" "-mabi" "64" "-mno-shared" "-KPIC" "-EB"
+//
+// RUN: %clang -target mips64-linux-gnu -mips64r5 -### \
+// RUN:   -no-integrated-as -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=MIPS-ALIAS-64R5 %s
+// MIPS-ALIAS-64R5: as{{(.exe)?}}" "-march" "mips64r5" "-mabi" "64" "-mno-shared" "-KPIC" "-EB"
+//
 // RUN: %clang -target mips64-linux-gnu -mips64r6 -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=MIPS-ALIAS-64R6 %s
diff --git a/test/Driver/mips-fsf.cpp b/test/Driver/mips-fsf.cpp
index 07b95c8..e39b24e 100644
--- a/test/Driver/mips-fsf.cpp
+++ b/test/Driver/mips-fsf.cpp
@@ -2699,3 +2699,113 @@
 // CHECK-EL-NAN64-64R2-64-DEF: "-L[[TC]]/../../../../sysroot/mips64r2/64/el/nan2008/usr/lib"
 // CHECK-EL-NAN64-64R2-64-DEF: "[[TC]]/mips64r2/64/el/nan2008{{/|\\\\}}crtend.o"
 // CHECK-EL-NAN64-64R2-64-DEF: "[[TC]]/../../../../sysroot/mips64r2/64/el/nan2008/usr/lib{{/|\\\\}}crtn.o"
+//
+// Check that mips32r3 and mips32r5 are equal to mips32r2
+//
+// = Big-endian, mips32r3, hard float
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=mips-linux-gnu -mips32r3 -mhard-float \
+// RUN:     --gcc-toolchain=%S/Inputs/mips_fsf_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-BE-HF-32R3 %s
+// CHECK-BE-HF-32R3: "-internal-isystem"
+// CHECK-BE-HF-32R3: "[[TC:[^"]+/lib/gcc/mips-mti-linux-gnu/4.9.0]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0"
+// CHECK-BE-HF-32R3: "-internal-isystem"
+// CHECK-BE-HF-32R3: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/mips-mti-linux-gnu"
+// CHECK-BE-HF-32R3: "-internal-isystem"
+// CHECK-BE-HF-32R3: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/backward"
+// CHECK-BE-HF-32R3: "-internal-externc-isystem"
+// CHECK-BE-HF-32R3: "[[TC]]/include"
+// CHECK-BE-HF-32R3: "-internal-externc-isystem"
+// CHECK-BE-HF-32R3: "[[TC]]/../../../../sysroot/usr/include"
+// CHECK-BE-HF-32R3: "{{.*}}ld{{(.exe)?}}"
+// CHECK-BE-HF-32R3: "--sysroot=[[TC]]/../../../../sysroot"
+// CHECK-BE-HF-32R3: "-dynamic-linker" "/lib/ld.so.1"
+// CHECK-BE-HF-32R3: "[[TC]]/../../../../sysroot/usr/lib/../lib{{/|\\\\}}crt1.o"
+// CHECK-BE-HF-32R3: "[[TC]]/../../../../sysroot/usr/lib/../lib{{/|\\\\}}crti.o"
+// CHECK-BE-HF-32R3: "[[TC]]{{/|\\\\}}crtbegin.o"
+// CHECK-BE-HF-32R3: "-L[[TC]]"
+// CHECK-BE-HF-32R3: "-L[[TC]]/../../../../mips-mti-linux-gnu/lib/../lib"
+// CHECK-BE-HF-32R3: "-L[[TC]]/../../../../sysroot/usr/lib/../lib"
+// CHECK-BE-HF-32R3: "[[TC]]{{/|\\\\}}crtend.o"
+// CHECK-BE-HF-32R3: "[[TC]]/../../../../sysroot/usr/lib/../lib{{/|\\\\}}crtn.o"
+//
+// = Big-endian, mips32r5, hard float
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=mips-linux-gnu -mips32r5 -mhard-float \
+// RUN:     --gcc-toolchain=%S/Inputs/mips_fsf_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-BE-HF-32R5 %s
+// CHECK-BE-HF-32R5: "-internal-isystem"
+// CHECK-BE-HF-32R5: "[[TC:[^"]+/lib/gcc/mips-mti-linux-gnu/4.9.0]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0"
+// CHECK-BE-HF-32R5: "-internal-isystem"
+// CHECK-BE-HF-32R5: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/mips-mti-linux-gnu"
+// CHECK-BE-HF-32R5: "-internal-isystem"
+// CHECK-BE-HF-32R5: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/backward"
+// CHECK-BE-HF-32R5: "-internal-externc-isystem"
+// CHECK-BE-HF-32R5: "[[TC]]/include"
+// CHECK-BE-HF-32R5: "-internal-externc-isystem"
+// CHECK-BE-HF-32R5: "[[TC]]/../../../../sysroot/usr/include"
+// CHECK-BE-HF-32R5: "{{.*}}ld{{(.exe)?}}"
+// CHECK-BE-HF-32R5: "--sysroot=[[TC]]/../../../../sysroot"
+// CHECK-BE-HF-32R5: "-dynamic-linker" "/lib/ld.so.1"
+// CHECK-BE-HF-32R5: "[[TC]]/../../../../sysroot/usr/lib/../lib{{/|\\\\}}crt1.o"
+// CHECK-BE-HF-32R5: "[[TC]]/../../../../sysroot/usr/lib/../lib{{/|\\\\}}crti.o"
+// CHECK-BE-HF-32R5: "[[TC]]{{/|\\\\}}crtbegin.o"
+// CHECK-BE-HF-32R5: "-L[[TC]]"
+// CHECK-BE-HF-32R5: "-L[[TC]]/../../../../mips-mti-linux-gnu/lib/../lib"
+// CHECK-BE-HF-32R5: "-L[[TC]]/../../../../sysroot/usr/lib/../lib"
+// CHECK-BE-HF-32R5: "[[TC]]{{/|\\\\}}crtend.o"
+// CHECK-BE-HF-32R5: "[[TC]]/../../../../sysroot/usr/lib/../lib{{/|\\\\}}crtn.o"
+//
+// = Big-endian, mips64r3, ABI 64, hard float
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=mips64-linux-gnu -mips64r3 -mabi=64 -mhard-float \
+// RUN:     --gcc-toolchain=%S/Inputs/mips_fsf_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-BE-HF-64R3-64 %s
+// CHECK-BE-HF-64R3-64: "-internal-isystem"
+// CHECK-BE-HF-64R3-64: "[[TC:[^"]+/lib/gcc/mips-mti-linux-gnu/4.9.0]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0"
+// CHECK-BE-HF-64R3-64: "-internal-isystem"
+// CHECK-BE-HF-64R3-64: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/mips-mti-linux-gnu/mips64r2/64"
+// CHECK-BE-HF-64R3-64: "-internal-isystem"
+// CHECK-BE-HF-64R3-64: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/backward"
+// CHECK-BE-HF-64R3-64: "-internal-externc-isystem"
+// CHECK-BE-HF-64R3-64: "[[TC]]/include"
+// CHECK-BE-HF-64R3-64: "-internal-externc-isystem"
+// CHECK-BE-HF-64R3-64: "[[TC]]/../../../../sysroot/usr/include"
+// CHECK-BE-HF-64R3-64: "{{.*}}ld{{(.exe)?}}"
+// CHECK-BE-HF-64R3-64: "--sysroot=[[TC]]/../../../../sysroot/mips64r2/64"
+// CHECK-BE-HF-64R3-64: "-dynamic-linker" "/lib64/ld.so.1"
+// CHECK-BE-HF-64R3-64: "[[TC]]/../../../../sysroot/mips64r2/64/usr/lib{{/|\\\\}}crt1.o"
+// CHECK-BE-HF-64R3-64: "[[TC]]/../../../../sysroot/mips64r2/64/usr/lib{{/|\\\\}}crti.o"
+// CHECK-BE-HF-64R3-64: "[[TC]]/mips64r2/64{{/|\\\\}}crtbegin.o"
+// CHECK-BE-HF-64R3-64: "-L[[TC]]/mips64r2/64"
+// CHECK-BE-HF-64R3-64: "-L[[TC]]/../../../../mips-mti-linux-gnu/lib/mips64r2/64"
+// CHECK-BE-HF-64R3-64: "-L[[TC]]/../../../../sysroot/mips64r2/64/usr/lib"
+// CHECK-BE-HF-64R3-64: "[[TC]]/mips64r2/64{{/|\\\\}}crtend.o"
+// CHECK-BE-HF-64R3-64: "[[TC]]/../../../../sysroot/mips64r2/64/usr/lib{{/|\\\\}}crtn.o"
+//
+// = Big-endian, mips64r5, ABI 64, hard float
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN:     --target=mips64-linux-gnu -mips64r5 -mabi=64 -mhard-float \
+// RUN:     --gcc-toolchain=%S/Inputs/mips_fsf_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-BE-HF-64R5-64 %s
+// CHECK-BE-HF-64R5-64: "-internal-isystem"
+// CHECK-BE-HF-64R5-64: "[[TC:[^"]+/lib/gcc/mips-mti-linux-gnu/4.9.0]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0"
+// CHECK-BE-HF-64R5-64: "-internal-isystem"
+// CHECK-BE-HF-64R5-64: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/mips-mti-linux-gnu/mips64r2/64"
+// CHECK-BE-HF-64R5-64: "-internal-isystem"
+// CHECK-BE-HF-64R5-64: "[[TC]]/../../../../mips-mti-linux-gnu/include/c++/4.9.0/backward"
+// CHECK-BE-HF-64R5-64: "-internal-externc-isystem"
+// CHECK-BE-HF-64R5-64: "[[TC]]/include"
+// CHECK-BE-HF-64R5-64: "-internal-externc-isystem"
+// CHECK-BE-HF-64R5-64: "[[TC]]/../../../../sysroot/usr/include"
+// CHECK-BE-HF-64R5-64: "{{.*}}ld{{(.exe)?}}"
+// CHECK-BE-HF-64R5-64: "--sysroot=[[TC]]/../../../../sysroot/mips64r2/64"
+// CHECK-BE-HF-64R5-64: "-dynamic-linker" "/lib64/ld.so.1"
+// CHECK-BE-HF-64R5-64: "[[TC]]/../../../../sysroot/mips64r2/64/usr/lib{{/|\\\\}}crt1.o"
+// CHECK-BE-HF-64R5-64: "[[TC]]/../../../../sysroot/mips64r2/64/usr/lib{{/|\\\\}}crti.o"
+// CHECK-BE-HF-64R5-64: "[[TC]]/mips64r2/64{{/|\\\\}}crtbegin.o"
+// CHECK-BE-HF-64R5-64: "-L[[TC]]/mips64r2/64"
+// CHECK-BE-HF-64R5-64: "-L[[TC]]/../../../../mips-mti-linux-gnu/lib/mips64r2/64"
+// CHECK-BE-HF-64R5-64: "-L[[TC]]/../../../../sysroot/mips64r2/64/usr/lib"
+// CHECK-BE-HF-64R5-64: "[[TC]]/mips64r2/64{{/|\\\\}}crtend.o"
+// CHECK-BE-HF-64R5-64: "[[TC]]/../../../../sysroot/mips64r2/64/usr/lib{{/|\\\\}}crtn.o"
diff --git a/test/Driver/mips-integrated-as.s b/test/Driver/mips-integrated-as.s
index b648650..08adb20 100644
--- a/test/Driver/mips-integrated-as.s
+++ b/test/Driver/mips-integrated-as.s
@@ -5,24 +5,19 @@
 // RUN: %clang -target mips-linux-gnu -### -fintegrated-as -c %s -mabi=o32 2>&1 | \
 // RUN:   FileCheck -check-prefix=ABI-O32 %s
 // ABI-O32: -cc1as
-// ABI-O32: "-target-feature" "-n64"
-// ABI-O32: "-target-feature" "+o32"
+// ABI-O32: "-target-abi" "o32"
 
 // RUN: %clang -target mips-linux-gnu -### -fintegrated-as -c %s -mabi=eabi 2>&1 | \
 // RUN:   FileCheck -check-prefix=ABI-EABI32 %s
 // ABI-EABI32: -cc1as
-// ABI-EABI32: "-target-feature" "-o32"
-// ABI-EABI32: "-target-feature" "-n64"
-// ABI-EABI32: "-target-feature" "+eabi"
+// ABI-EABI32: "-target-abi" "eabi"
 
 // RUN: %clang -target mips-linux-gnu -### -fintegrated-as -c %s -mips64 -mabi=n32 2>&1 | \
 // RUN:   FileCheck -check-prefix=ABI-N32 %s
 // RUN: %clang -target mips64-linux-gnu -### -fintegrated-as -c %s -mabi=n32 2>&1 | \
 // RUN:   FileCheck -check-prefix=ABI-N32 %s
 // ABI-N32: -cc1as
-// ABI-N32: "-target-feature" "-o32"
-// ABI-N32: "-target-feature" "-n64"
-// ABI-N32: "-target-feature" "+n32"
+// ABI-N32: "-target-abi" "n32"
 
 // FIXME: We should also test '-target mips-linux-gnu -mips64' defaults to the
 //        default 64-bit ABI (N64 but GCC uses N32). It currently selects O32
@@ -39,8 +34,7 @@
 // RUN: %clang -target mips64-linux-gnu -### -fintegrated-as -c %s -mips64 -mabi=n64 2>&1 | \
 // RUN:   FileCheck -check-prefix=ABI-N64 %s
 // ABI-N64: -cc1as
-// ABI-N64: "-target-feature" "-o32"
-// ABI-N64: "-target-feature" "+n64"
+// ABI-N64: "-target-abi" "n64"
 
 // RUN: %clang -target mips-linux-gnu -### -fintegrated-as -c %s -msoft-float 2>&1 | \
 // RUN:   FileCheck -check-prefix=SOFTFLOAT %s
diff --git a/test/Driver/mips-reduced-toolchain.cpp b/test/Driver/mips-reduced-toolchain.cpp
index fe7ed8a..894bdb5 100644
--- a/test/Driver/mips-reduced-toolchain.cpp
+++ b/test/Driver/mips-reduced-toolchain.cpp
@@ -4,6 +4,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mips-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/debian_reduced_mips_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPS %s
 // CHECK-DEBIAN-MIPS: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
 // CHECK-DEBIAN-MIPS: "{{.*}}/usr/lib/gcc/mips-linux-gnu/4.7{{/|\\\\}}crtbegin.o"
@@ -17,6 +18,7 @@
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN:     --target=mipsel-linux-gnu \
 // RUN:     --sysroot=%S/Inputs/debian_reduced_mips_tree \
+// RUN:     --gcc-toolchain="" \
 // RUN:   | FileCheck --check-prefix=CHECK-DEBIAN-MIPSEL %s
 // CHECK-DEBIAN-MIPSEL: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
 // CHECK-DEBIAN-MIPSEL: "{{.*}}/usr/lib/gcc/mipsel-linux-gnu/4.7{{/|\\\\}}crtbegin.o"
diff --git a/test/Driver/modules-cache-path.m b/test/Driver/modules-cache-path.m
new file mode 100644
index 0000000..419d6d4
--- /dev/null
+++ b/test/Driver/modules-cache-path.m
@@ -0,0 +1,5 @@
+// RUN: env USERNAME=asdf LOGNAME=asdf %clang -fmodules -### %s 2>&1 | FileCheck %s -check-prefix=CHECK-SET
+// CHECK-SET: -fmodules-cache-path={{.*}}org.llvm.clang.asdf{{[/\\]+}}ModuleCache
+
+// RUN: %clang -fmodules -### %s 2>&1 | FileCheck %s -check-prefix=CHECK-DEFAULT
+// CHECK-DEFAULT: -fmodules-cache-path={{.*}}org.llvm.clang.{{[A-Za-z0-9_]*[/\\]+}}ModuleCache
diff --git a/test/Driver/ms-inline-asm.c b/test/Driver/ms-inline-asm.c
deleted file mode 100644
index 0383564..0000000
--- a/test/Driver/ms-inline-asm.c
+++ /dev/null
@@ -1,15 +0,0 @@
-// RUN: %clang -target x86_64-apple-darwin10 \
-// RUN:   -### -fsyntax-only -fasm-blocks %s 2> %t
-// RUN: FileCheck --check-prefix=CHECK-BLOCKS < %t %s
-
-// RUN: %clang -target x86_64-apple-darwin10 \
-// RUN:   -### -fsyntax-only -fno-asm-blocks -fasm-blocks %s 2> %t
-// RUN: FileCheck --check-prefix=CHECK-BLOCKS < %t %s
-
-// CHECK-BLOCKS: "-fasm-blocks"
-
-// RUN: %clang -target x86_64-apple-darwin10 \
-// RUN:   -### -fsyntax-only -fasm-blocks -fno-asm-blocks %s 2> %t
-// RUN: FileCheck --check-prefix=CHECK-NO-BLOCKS < %t %s
-
-// CHECK-NO-BLOCKS-NOT: "-fasm-blocks"
diff --git a/test/Driver/msc-version.c b/test/Driver/msc-version.c
index 1a88419..4105eba 100644
--- a/test/Driver/msc-version.c
+++ b/test/Driver/msc-version.c
@@ -5,8 +5,8 @@
 // RUN: %clang -target i686-windows -fms-compatibility -dM -E - </dev/null -o - | FileCheck %s -check-prefix CHECK-NO-MSC-VERSION
 
 // CHECK-NO-MSC-VERSION: _MSC_BUILD 1
-// CHECK-NO-MSC-VERSION: _MSC_FULL_VER 170000000
-// CHECK-NO-MSC-VERSION: _MSC_VER 1700
+// CHECK-NO-MSC-VERSION: _MSC_FULL_VER 180000000
+// CHECK-NO-MSC-VERSION: _MSC_VER 1800
 
 
 //
diff --git a/test/Driver/netbsd.c b/test/Driver/netbsd.c
index eded7f5..612935d 100644
--- a/test/Driver/netbsd.c
+++ b/test/Driver/netbsd.c
@@ -19,6 +19,15 @@
 // RUN: %clang -no-canonical-prefixes -target armeb--netbsd-eabi \
 // RUN: -no-integrated-as --sysroot=%S/Inputs/basic_netbsd_tree %s -### 2>&1 \
 // RUN: | FileCheck -check-prefix=ARMEB %s
+// RUN: %clang -no-canonical-prefixes -target armeb--netbsd-eabi -march=armv7 \
+// RUN: -no-integrated-as --sysroot=%S/Inputs/basic_netbsd_tree %s -### 2>&1 \
+// RUN: | FileCheck -check-prefix=ARMV7EB %s
+// RUN: %clang -no-canonical-prefixes -target armv7eb--netbsd-eabi \
+// RUN: -no-integrated-as --sysroot=%S/Inputs/basic_netbsd_tree %s -### 2>&1 \
+// RUN: | FileCheck -check-prefix=ARMV7EB %s
+// RUN: %clang -r -no-canonical-prefixes -target armeb--netbsd-eabi \
+// RUN: -no-integrated-as --sysroot=%S/Inputs/basic_netbsd_tree %s -### 2>&1 \
+// RUN: | FileCheck -check-prefix=ARMEB-R %s
 // RUN: %clang -no-canonical-prefixes -target arm--netbsd \
 // RUN: -no-integrated-as --sysroot=%S/Inputs/basic_netbsd_tree %s -### 2>&1 \
 // RUN: | FileCheck -check-prefix=ARM-APCS %s
@@ -132,11 +141,17 @@
 // ARMEB: clang{{.*}}" "-cc1" "-triple" "armebv5e--netbsd-eabi"
 // ARMEB: as{{.*}}" "-mcpu=arm926ej-s" "-o"
 // ARMEB: ld{{.*}}" "--eh-frame-hdr" "-dynamic-linker" "/libexec/ld.elf_so"
+// ARMEB-NOT: "--be8"
 // ARMEB: "-m" "armelfb_nbsd_eabi"
 // ARMEB: "-o" "a.out" "{{.*}}/usr/lib{{/|\\\\}}crt0.o"
 // ARMEB: "{{.*}}/usr/lib{{/|\\\\}}eabi{{/|\\\\}}crti.o"
 // ARMEB: "{{.*}}/usr/lib{{/|\\\\}}crtbegin.o" "{{.*}}.o" "-lc"
 // ARMEB: "{{.*}}/usr/lib{{/|\\\\}}crtend.o" "{{.*}}/usr/lib{{/|\\\\}}crtn.o"
+// ARMV7EB: ld{{.*}}" "--eh-frame-hdr" "-dynamic-linker" "/libexec/ld.elf_so"
+// ARMV7EB: "--be8" "-m" "armelfb_nbsd_eabi"
+
+// ARMEB-R: ld{{.*}}"
+// ARMEB-R-NOT: "--be8"
 
 // ARM-APCS: clang{{.*}}" "-cc1" "-triple" "armv4--netbsd"
 // ARM-APCS: as{{.*}}" "-mcpu=strongarm" "-o"
diff --git a/test/Driver/nostdincxx.cpp b/test/Driver/nostdincxx.cpp
index 126828d..f2305ad 100644
--- a/test/Driver/nostdincxx.cpp
+++ b/test/Driver/nostdincxx.cpp
@@ -4,3 +4,4 @@
 
 // MSVC has C++ headers in same directory as C headers.
 // REQUIRES: non-ms-sdk
+// REQUIRES: non-ps4-sdk
diff --git a/test/Driver/openbsd.c b/test/Driver/openbsd.c
index d263f48..74fef50 100644
--- a/test/Driver/openbsd.c
+++ b/test/Driver/openbsd.c
@@ -8,6 +8,14 @@
 // CHECK-PG: clang{{.*}}" "-cc1" "-triple" "i686-pc-openbsd"
 // CHECK-PG: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" "-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}gcrt0.o" "{{.*}}crtbegin.o" "{{.*}}.o" "-lgcc" "-lpthread_p" "-lc_p" "-lgcc" "{{.*}}crtend.o"
 
+// Check CPU type for MIPS64
+// RUN: %clang -target mips64-unknown-openbsd -### -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-MIPS64-CPU %s
+// RUN: %clang -target mips64el-unknown-openbsd -### -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-MIPS64EL-CPU %s
+// CHECK-MIPS64-CPU: "-target-cpu" "mips3"
+// CHECK-MIPS64EL-CPU: "-target-cpu" "mips3"
+
 // Check that the new linker flags are passed to OpenBSD
 // RUN: %clang -no-canonical-prefixes -target i686-pc-openbsd -r %s -### 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-R %s
@@ -59,12 +67,3 @@
 // CHECK-MIPS64-PIC: as{{.*}}" "-mabi" "64" "-EB" "-KPIC"
 // CHECK-MIPS64EL: as{{.*}}" "-mabi" "64" "-EL"
 // CHECK-MIPS64EL-PIC: as{{.*}}" "-mabi" "64" "-EL" "-KPIC"
-
-// Check that the integrated assembler is enabled for PowerPC and SPARC
-// RUN: %clang -target powerpc-unknown-openbsd -### -c %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-IAS %s
-// RUN: %clang -target sparc-unknown-openbsd -### -c %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-IAS %s
-// RUN: %clang -target sparc64-unknown-openbsd -### -c %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-IAS %s
-// CHECK-IAS-NOT: "-no-integrated-as"
diff --git a/test/Driver/phases.c b/test/Driver/phases.c
index 4c480d5..0283800 100644
--- a/test/Driver/phases.c
+++ b/test/Driver/phases.c
@@ -2,47 +2,53 @@
 // RUN: %clang -target i386-unknown-unknown -ccc-print-phases -x c %s -x objective-c %s -x c++ %s -x objective-c++ -x assembler %s -x assembler-with-cpp %s -x none %s 2>&1 | FileCheck -check-prefix=BASIC %s
 // BASIC: 0: input, "{{.*}}phases.c", c
 // BASIC: 1: preprocessor, {0}, cpp-output
-// BASIC: 2: compiler, {1}, assembler
-// BASIC: 3: assembler, {2}, object
-// BASIC: 4: input, "{{.*}}phases.c", objective-c
-// BASIC: 5: preprocessor, {4}, objective-c-cpp-output
-// BASIC: 6: compiler, {5}, assembler
-// BASIC: 7: assembler, {6}, object
-// BASIC: 8: input, "{{.*}}phases.c", c++
-// BASIC: 9: preprocessor, {8}, c++-cpp-output
-// BASIC: 10: compiler, {9}, assembler
-// BASIC: 11: assembler, {10}, object
-// BASIC: 12: input, "{{.*}}phases.c", assembler
-// BASIC: 13: assembler, {12}, object
-// BASIC: 14: input, "{{.*}}phases.c", assembler-with-cpp
-// BASIC: 15: preprocessor, {14}, assembler
+// BASIC: 2: compiler, {1}, ir
+// BASIC: 3: backend, {2}, assembler
+// BASIC: 4: assembler, {3}, object
+// BASIC: 5: input, "{{.*}}phases.c", objective-c
+// BASIC: 6: preprocessor, {5}, objective-c-cpp-output
+// BASIC: 7: compiler, {6}, ir
+// BASIC: 8: backend, {7}, assembler
+// BASIC: 9: assembler, {8}, object
+// BASIC: 10: input, "{{.*}}phases.c", c++
+// BASIC: 11: preprocessor, {10}, c++-cpp-output
+// BASIC: 12: compiler, {11}, ir
+// BASIC: 13: backend, {12}, assembler
+// BASIC: 14: assembler, {13}, object
+// BASIC: 15: input, "{{.*}}phases.c", assembler
 // BASIC: 16: assembler, {15}, object
-// BASIC: 17: input, "{{.*}}phases.c", c
-// BASIC: 18: preprocessor, {17}, cpp-output
-// BASIC: 19: compiler, {18}, assembler
-// BASIC: 20: assembler, {19}, object
-// BASIC: 21: linker, {3, 7, 11, 13, 16, 20}, image
+// BASIC: 17: input, "{{.*}}phases.c", assembler-with-cpp
+// BASIC: 18: preprocessor, {17}, assembler
+// BASIC: 19: assembler, {18}, object
+// BASIC: 20: input, "{{.*}}phases.c", c
+// BASIC: 21: preprocessor, {20}, cpp-output
+// BASIC: 22: compiler, {21}, ir
+// BASIC: 23: backend, {22}, assembler
+// BASIC: 24: assembler, {23}, object
+// BASIC: 25: linker, {4, 9, 14, 16, 19, 24}, image
 
 // Universal linked image.
 // RUN: %clang -target i386-apple-darwin9 -ccc-print-phases -x c %s -arch ppc -arch i386 2>&1 | FileCheck -check-prefix=ULI %s
 // ULI: 0: input, "{{.*}}phases.c", c
 // ULI: 1: preprocessor, {0}, cpp-output
-// ULI: 2: compiler, {1}, assembler
-// ULI: 3: assembler, {2}, object
-// ULI: 4: linker, {3}, image
-// ULI: 5: bind-arch, "ppc", {4}, image
-// ULI: 6: bind-arch, "i386", {4}, image
-// ULI: 7: lipo, {5, 6}, image
+// ULI: 2: compiler, {1}, ir
+// ULI: 3: backend, {2}, assembler
+// ULI: 4: assembler, {3}, object
+// ULI: 5: linker, {4}, image
+// ULI: 6: bind-arch, "ppc", {5}, image
+// ULI: 7: bind-arch, "i386", {5}, image
+// ULI: 8: lipo, {6, 7}, image
 
 // Universal object file.
 // RUN: %clang -target i386-apple-darwin9 -ccc-print-phases -c -x c %s -arch ppc -arch i386 2>&1 | FileCheck -check-prefix=UOF %s
 // UOF: 0: input, "{{.*}}phases.c", c
 // UOF: 1: preprocessor, {0}, cpp-output
-// UOF: 2: compiler, {1}, assembler
-// UOF: 3: assembler, {2}, object
-// UOF: 4: bind-arch, "ppc", {3}, object
-// UOF: 5: bind-arch, "i386", {3}, object
-// UOF: 6: lipo, {4, 5}, object
+// UOF: 2: compiler, {1}, ir
+// UOF: 3: backend, {2}, assembler
+// UOF: 4: assembler, {3}, object
+// UOF: 5: bind-arch, "ppc", {4}, object
+// UOF: 6: bind-arch, "i386", {4}, object
+// UOF: 7: lipo, {5, 6}, object
 
 // Arch defaulting
 // RUN: %clang -target i386-apple-darwin9 -ccc-print-phases -c -x assembler %s 2>&1 | FileCheck -check-prefix=ARCH1 %s
diff --git a/test/Driver/pic.c b/test/Driver/pic.c
index 3629cc4..3a14d61 100644
--- a/test/Driver/pic.c
+++ b/test/Driver/pic.c
@@ -11,6 +11,8 @@
 // CHECK-PIC2: "-mrelocation-model" "pic"
 // CHECK-PIC2: "-pic-level" "2"
 //
+// CHECK-NO-STATIC-NOT: "-static"
+//
 // CHECK-PIE1: "-mrelocation-model" "pic"
 // CHECK-PIE1: "-pic-level" "1"
 // CHECK-PIE1: "-pie-level" "1"
@@ -118,12 +120,15 @@
 // Make sure -pie is passed to along to ld and that the right *crt* files
 // are linked in.
 // RUN: %clang %s -target i386-unknown-freebsd -fPIE -pie -### \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/basic_freebsd_tree 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-PIE-LD
 // RUN: %clang %s -target i386-linux-gnu -fPIE -pie -### \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-PIE-LD
 // RUN: %clang %s -target i386-linux-gnu -fPIC -pie -### \
+// RUN: --gcc-toolchain="" \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-PIE-LD
 //
@@ -195,6 +200,10 @@
 // RUN:   | FileCheck %s --check-prefix=CHECK-PIC2
 // RUN: %clang -c %s -target armv7-apple-ios -mkernel -miphoneos-version-min=6.0.0 -### 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-PIC2
+// RUN: %clang -c %s -target arm64-apple-ios -mkernel -miphoneos-version-min=7.0.0 -### 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-PIC2
+// RUN: %clang -x assembler -c %s -target arm64-apple-ios -mkernel -miphoneos-version-min=7.0.0 -no-integrated-as -### 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-NO-STATIC
 // RUN: %clang -c %s -target armv7-apple-ios -fapple-kext -miphoneos-version-min=5.0.0 -### 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-NO-PIC
 // RUN: %clang -c %s -target armv7-apple-ios -fapple-kext -miphoneos-version-min=6.0.0 -static -### 2>&1 \
diff --git a/test/Driver/ppc-features.cpp b/test/Driver/ppc-features.cpp
index c62f5b9..39d6357 100644
--- a/test/Driver/ppc-features.cpp
+++ b/test/Driver/ppc-features.cpp
@@ -89,6 +89,12 @@
 // RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-fprnd -mfprnd -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-FPRND %s
 // CHECK-FPRND: "-target-feature" "+fprnd"
 
+// RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-cmpb -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-NOCMPB %s
+// CHECK-NOCMPB: "-target-feature" "-cmpb"
+
+// RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-cmpb -mcmpb -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-CMPB %s
+// CHECK-CMPB: "-target-feature" "+cmpb"
+
 // RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-vsx -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-NOVSX %s
 // CHECK-NOVSX: "-target-feature" "-vsx"
 
@@ -107,6 +113,12 @@
 // RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-crbits -mcrbits -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-CRBITS %s
 // CHECK-CRBITS: "-target-feature" "+crbits"
 
+// RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-invariant-function-descriptors -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-NOINVFUNCDESC %s
+// CHECK-NOINVFUNCDESC: "-target-feature" "-invariant-function-descriptors"
+
+// RUN: %clang -target powerpc64-unknown-linux-gnu %s -mno-invariant-function-descriptors -minvariant-function-descriptors -### -o %t.o 2>&1 | FileCheck -check-prefix=CHECK-INVFUNCDESC %s
+// CHECK-INVFUNCDESC: "-target-feature" "+invariant-function-descriptors"
+
 // Assembler features
 // RUN: %clang -target powerpc64-unknown-linux-gnu %s -### -o %t.o -no-integrated-as 2>&1 | FileCheck -check-prefix=CHECK_BE_AS_ARGS %s
 // CHECK_BE_AS_ARGS: "-mppc64"
diff --git a/test/Driver/ps4-cpu-defaults.cpp b/test/Driver/ps4-cpu-defaults.cpp
new file mode 100644
index 0000000..99547d4
--- /dev/null
+++ b/test/Driver/ps4-cpu-defaults.cpp
@@ -0,0 +1,6 @@
+// Check that on the PS4 we default to:
+// -target-cpu btver2 and no exceptions
+
+// RUN: %clang -target x86_64-scei-ps4 -c %s -### 2>&1 | FileCheck %s
+// CHECK: "-target-cpu" "btver2"
+// CHECK-NOT: exceptions
diff --git a/test/Driver/r600-mcpu.cl b/test/Driver/r600-mcpu.cl
index 47c0185..94a7734 100644
--- a/test/Driver/r600-mcpu.cl
+++ b/test/Driver/r600-mcpu.cl
@@ -26,15 +26,15 @@
 // RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=caicos %s -o - 2>&1 | FileCheck --check-prefix=CAICOS-CHECK %s
 // RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=cayman %s -o - 2>&1 | FileCheck --check-prefix=CAYMAN-CHECK %s
 // RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=aruba %s -o - 2>&1 | FileCheck --check-prefix=CAYMAN-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=tahiti %s -o - 2>&1 | FileCheck --check-prefix=TAHITI-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=pitcairn %s -o - 2>&1 | FileCheck --check-prefix=PITCAIRN-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=verde %s -o - 2>&1 | FileCheck --check-prefix=VERDE-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=oland %s -o - 2>&1 | FileCheck --check-prefix=OLAND-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=bonaire %s -o - 2>&1 | FileCheck --check-prefix=BONAIRE-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=kabini %s -o - 2>&1 | FileCheck --check-prefix=KABINI-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=kaveri %s -o - 2>&1 | FileCheck --check-prefix=KAVERI-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=hawaii %s -o - 2>&1 | FileCheck --check-prefix=HAWAII-CHECK %s
-// RUN: %clang -### -target r600 -x cl -S -emit-llvm -mcpu=mullins %s -o - 2>&1 | FileCheck --check-prefix=MULLINS-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=tahiti %s -o - 2>&1 | FileCheck --check-prefix=TAHITI-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=pitcairn %s -o - 2>&1 | FileCheck --check-prefix=PITCAIRN-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=verde %s -o - 2>&1 | FileCheck --check-prefix=VERDE-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=oland %s -o - 2>&1 | FileCheck --check-prefix=OLAND-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=bonaire %s -o - 2>&1 | FileCheck --check-prefix=BONAIRE-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=kabini %s -o - 2>&1 | FileCheck --check-prefix=KABINI-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=kaveri %s -o - 2>&1 | FileCheck --check-prefix=KAVERI-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=hawaii %s -o - 2>&1 | FileCheck --check-prefix=HAWAII-CHECK %s
+// RUN: %clang -### -target amdgcn -x cl -S -emit-llvm -mcpu=mullins %s -o - 2>&1 | FileCheck --check-prefix=MULLINS-CHECK %s
 
 // R600-CHECK:  "-target-cpu" "r600"
 // RS880-CHECK: "-target-cpu" "rs880"
diff --git a/test/Driver/rewrite-map-in-diagnostics.c b/test/Driver/rewrite-map-in-diagnostics.c
new file mode 100644
index 0000000..4aea0ec
--- /dev/null
+++ b/test/Driver/rewrite-map-in-diagnostics.c
@@ -0,0 +1,14 @@
+// RUN: rm -rf "%t"
+// RUN: mkdir -p "%t"
+// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTION=1 \
+// RUN:     %clang -fsyntax-only -frewrite-map-file %p/Inputs/rewrite.map %s 2>&1 \
+// RUN:   | FileCheck %s
+
+#pragma clang __debug parser_crash
+
+// CHECK: note: diagnostic msg: {{.*}}rewrite.map
+
+// REQUIRES: crash-recovery
+
+// FIXME: This doesn't fail on "env clang". Investigating.
+// REQUIRES: shell
diff --git a/test/Driver/rtti-options.cpp b/test/Driver/rtti-options.cpp
new file mode 100644
index 0000000..a14953e
--- /dev/null
+++ b/test/Driver/rtti-options.cpp
@@ -0,0 +1,55 @@
+// Check that we emit warnings/errors for different combinations of
+// exceptions, rtti, and vptr sanitizer flags when targetting the PS4.
+// No warnings/errors should be emitted for unknown, except if combining
+// the vptr sanitizer with -fno-rtti
+
+// RUN: %clang -### -c -fno-rtti -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-RTTI %s
+// RUN: %clang -### -c -frtti -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-NO-RTTI %s
+
+// -fsanitize=vptr
+// Make sure we only error/warn once, when trying to enable vptr and
+// undefined and have -fno-rtti
+// RUN: %clang -### -c -fsanitize=undefined -fsanitize=vptr -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-SAN-ERROR -check-prefix=CHECK-OK %s
+
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fsanitize=vptr %s 2>&1 | FileCheck -check-prefix=CHECK-SAN-WARN %s
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fsanitize=vptr -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fsanitize=vptr -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-SAN-ERROR %s
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fsanitize=undefined -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fsanitize=vptr %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fsanitize=vptr -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fsanitize=vptr -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-SAN-ERROR %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fsanitize=undefined %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fsanitize=undefined -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+
+// Exceptions + no/default rtti
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fcxx-exceptions -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-EXC-ERROR-CXX %s
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fcxx-exceptions %s 2>&1 | FileCheck -check-prefix=CHECK-EXC-WARN %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fcxx-exceptions -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fcxx-exceptions %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// In C++, -fexceptions implies -fcxx-exceptions
+// RUN: %clang -x c++ -### -c -target x86_64-scei-ps4 -fexceptions -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-EXC-ERROR %s
+// RUN: %clang -x c++ -### -c -target x86_64-scei-ps4 -fexceptions %s 2>&1 | FileCheck -check-prefix=CHECK-EXC-WARN %s
+// RUN: %clang -x c++ -### -c -target x86_64-unknown-unknown -fexceptions -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -x c++ -### -c -target x86_64-unknown-unknown -fexceptions %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+
+// -frtti + exceptions
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fcxx-exceptions -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fcxx-exceptions -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-OK %s
+
+// -f{no-,}rtti/default
+// RUN: %clang -### -c -target x86_64-scei-ps4 -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-RTTI %s
+// RUN: %clang -### -c -target x86_64-scei-ps4 -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-NO-RTTI %s
+// RUN: %clang -### -c -target x86_64-scei-ps4 %s 2>&1 | FileCheck -check-prefix=CHECK-NO-RTTI %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -frtti %s 2>&1 | FileCheck -check-prefix=CHECK-RTTI %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown -fno-rtti %s 2>&1 | FileCheck -check-prefix=CHECK-NO-RTTI %s
+// RUN: %clang -### -c -target x86_64-unknown-unknown %s 2>&1 | FileCheck -check-prefix=CHECK-RTTI %s
+
+// CHECK-SAN-WARN: implicitly disabling vptr sanitizer because rtti wasn't enabled
+// CHECK-SAN-ERROR: invalid argument '-fsanitize=vptr' not allowed with '-fno-rtti'
+// CHECK-EXC-WARN: implicitly enabling rtti for exception handling
+// CHECK-EXC-ERROR: invalid argument '-fno-rtti' not allowed with '-fexceptions'
+// CHECK-EXC-ERROR-CXX: invalid argument '-fno-rtti' not allowed with '-fcxx-exceptions'
+// CHECK-RTTI-NOT: "-fno-rtti"
+// CHECK-NO-RTTI-NOT: "-frtti"
+
+// CHECK-OK-NOT: {{warning:|error:}}
diff --git a/test/Driver/save-temps.c b/test/Driver/save-temps.c
index a4ca3b2..438d748 100644
--- a/test/Driver/save-temps.c
+++ b/test/Driver/save-temps.c
@@ -1,19 +1,77 @@
 // RUN: %clang -target x86_64-apple-darwin -save-temps -arch x86_64 %s -### 2>&1 \
 // RUN:   | FileCheck %s
 // CHECK: "-o" "save-temps.i"
+// CHECK: "-disable-llvm-optzns"
+// CHECK: "-o" "save-temps.bc"
 // CHECK: "-o" "save-temps.s"
 // CHECK: "-o" "save-temps.o"
-// CHECK: "-o" "a.out" 
+// CHECK: "-o" "a.out"
+
+// Check -save-temps=cwd which should work the same as -save-temps above
+//
+// RUN: %clang -target x86_64-apple-darwin -save-temps=cwd -arch x86_64 %s -### 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=CWD
+// CWD: "-o" "save-temps.i"
+// CWD: "-disable-llvm-optzns"
+// CWD: "-o" "save-temps.bc"
+// CWD: "-o" "save-temps.s"
+// CWD: "-o" "save-temps.o"
+// CWD: "-o" "a.out"
+
+// Check for a single clang cc1 invocation when NOT using -save-temps.
+// RUN: %clang -target x86_64-apple-darwin -arch x86_64 -S %s -### 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=NO-TEMPS
+// NO-TEMPS: "-cc1"
+// NO-TEMPS: "-S"
+// NO-TEMPS: "-x" "c"
 
 // RUN: %clang -target x86_64-apple-darwin -save-temps -arch i386 -arch x86_64 %s -### 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=MULT-ARCH
 // MULT-ARCH: "-o" "save-temps-i386.i"
+// MULT-ARCH: "-o" "save-temps-i386.bc"
 // MULT-ARCH: "-o" "save-temps-i386.s"
 // MULT-ARCH: "-o" "save-temps-i386.o"
-// MULT-ARCH: "-o" "a.out-i386" 
+// MULT-ARCH: "-o" "a.out-i386"
 // MULT-ARCH: "-o" "save-temps-x86_64.i"
+// MULT-ARCH: "-o" "save-temps-x86_64.bc"
 // MULT-ARCH: "-o" "save-temps-x86_64.s"
 // MULT-ARCH: "-o" "save-temps-x86_64.o"
-// MULT-ARCH: "-o" "a.out-x86_64" 
+// MULT-ARCH: "-o" "a.out-x86_64"
 // MULT-ARCH: lipo
 // MULT-ARCH: "-create" "-output" "a.out" "a.out-i386" "a.out-x86_64"
+
+// RUN: %clang -target x86_64-apple-darwin -save-temps=cwd -arch i386 -arch x86_64 %s -### 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=MULT-ARCH-CWD
+// MULT-ARCH-CWD: "-o" "save-temps-i386.i"
+// MULT-ARCH-CWD: "-o" "save-temps-i386.bc"
+// MULT-ARCH-CWD: "-o" "save-temps-i386.s"
+// MULT-ARCH-CWD: "-o" "save-temps-i386.o"
+// MULT-ARCH-CWD: "-o" "a.out-i386"
+// MULT-ARCH-CWD: "-o" "save-temps-x86_64.i"
+// MULT-ARCH-CWD: "-o" "save-temps-x86_64.bc"
+// MULT-ARCH-CWD: "-o" "save-temps-x86_64.s"
+// MULT-ARCH-CWD: "-o" "save-temps-x86_64.o"
+// MULT-ARCH-CWD: "-o" "a.out-x86_64"
+// MULT-ARCH-CWD: lipo
+// MULT-ARCH-CWD: "-create" "-output" "a.out" "a.out-i386" "a.out-x86_64"
+
+// Check that temp files are saved in the same directory as the output file
+// regardless of whether -o is specified.
+//
+// RUN: %clang -target x86_64-apple-darwin -save-temps=obj -o obj/dir/a.out -arch x86_64 %s -### 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=CHECK-OBJ
+// CHECK-OBJ: "-o" "obj/dir{{/|\\\\}}save-temps.i"
+// CHECK-OBJ: "-disable-llvm-optzns"
+// CHECK-OBJ: "-o" "obj/dir{{/|\\\\}}save-temps.bc"
+// CHECK-OBJ: "-o" "obj/dir{{/|\\\\}}save-temps.s"
+// CHECK-OBJ: "-o" "obj/dir{{/|\\\\}}save-temps.o"
+// CHECK-OBJ: "-o" "obj/dir{{/|\\\\}}a.out"
+//
+// RUN: %clang -target x86_64-apple-darwin -save-temps=obj -arch x86_64 %s -### 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=CHECK-OBJ-NOO
+// CHECK-OBJ-NOO: "-o" "save-temps.i"
+// CHECK-OBJ-NOO: "-disable-llvm-optzns"
+// CHECK-OBJ-NOO: "-o" "save-temps.bc"
+// CHECK-OBJ-NOO: "-o" "save-temps.s"
+// CHECK-OBJ-NOO: "-o" "save-temps.o"
+// CHECK-OBJ-NOO: "-o" "a.out"
diff --git a/test/Driver/std.c b/test/Driver/std.c
index c82e9f1..02dca66 100644
--- a/test/Driver/std.c
+++ b/test/Driver/std.c
@@ -1,8 +1,18 @@
-// RUN: %clang -std=c99 -trigraphs -std=gnu99 %s -E -o - | FileCheck -check-prefix=OVERRIDE %s
+// RUN: %clang -w -std=c99 -trigraphs -std=gnu99 %s -E -o - | FileCheck -check-prefix=OVERRIDE %s
 // OVERRIDE: ??(??)
-// RUN: %clang -ansi %s -E -o - | FileCheck -check-prefix=ANSI %s
+// RUN: %clang -w -std=c99 -trigraphs -std=gnu99 %s -E -o - | FileCheck -check-prefix=FOVERRIDE %s
+// FOVERRIDE: ??(??)
+// RUN: %clang -w -ansi %s -E -o - | FileCheck -check-prefix=ANSI %s
 // ANSI: []
-// RUN: %clang -std=gnu99 -trigraphs %s -E -o - | FileCheck -check-prefix=EXPLICIT %s
+// RUN: %clang -w -ansi %s -fno-trigraphs -E -o - | FileCheck -check-prefix=ANSI-OVERRIDE %s
+// ANSI-OVERRIDE: ??(??)
+// RUN: %clang -w -std=gnu99 -trigraphs %s -E -o - | FileCheck -check-prefix=EXPLICIT %s
 // EXPLICIT: []
+// RUN: %clang -w -std=gnu99 -ftrigraphs %s -E -o - | FileCheck -check-prefix=FEXPLICIT %s
+// FEXPLICIT: []
+// RUN: %clang -w -ftrigraphs -fno-trigraphs %s -E -o - | FileCheck -check-prefix=ONOFF %s
+// ONOFF: ??(??)
+// RUN: %clang -w -fno-trigraphs -trigraphs %s -E -o - | FileCheck -check-prefix=OFFFON %s
+// OFFFON: []
 
 ??(??)
diff --git a/test/Driver/symbol-rewriter.c b/test/Driver/symbol-rewriter.c
new file mode 100644
index 0000000..3cfdb9d
--- /dev/null
+++ b/test/Driver/symbol-rewriter.c
@@ -0,0 +1,21 @@
+// RUN: %clang -frewrite-map-file %S/Inputs/rewrite.map -### %s 2>&1 | FileCheck %s -check-prefix CHECK-SINGLE
+
+// CHECK-SINGLE: "-frewrite-map-file" "{{.*[\\/]}}rewrite.map"
+
+// RUN: %clang -frewrite-map-file %S/Inputs/rewrite-1.map -frewrite-map-file %S/Inputs/rewrite-2.map -### %s 2>&1 | FileCheck %s -check-prefix CHECK-MULTIPLE
+
+// CHECK-MULTIPLE: "-frewrite-map-file" "{{.*[\\/]}}rewrite-1.map" "-frewrite-map-file" "{{.*[\\/]}}rewrite-2.map"
+
+// RUN: %clang -frewrite-map-file=%S/Inputs/rewrite.map -### %s 2>&1 | FileCheck %s -check-prefix CHECK-SINGLE-EQ
+
+// CHECK-SINGLE-EQ: "-frewrite-map-file" "{{.*[\\/]}}rewrite.map"
+
+// RUN: %clang -frewrite-map-file=%S/Inputs/rewrite-1.map -frewrite-map-file=%S/Inputs/rewrite-2.map -### %s 2>&1 | FileCheck %s -check-prefix CHECK-MULTIPLE-EQ
+
+// CHECK-MULTIPLE-EQ: "-frewrite-map-file" "{{.*[\\/]}}rewrite-1.map"
+// CHECK-MULTIPLE-EQ: "-frewrite-map-file" "{{.*[\\/]}}rewrite-2.map"
+
+// RUN: %clang -frewrite-map-file %S/Inputs/rewrite-1.map -frewrite-map-file=%S/Inputs/rewrite-2.map -### %s 2>&1 | FileCheck %s -check-prefix CHECK-MIXED
+
+// CHECK-MIXED: "-frewrite-map-file" "{{.*[\\/]}}rewrite-1.map" "-frewrite-map-file" "{{.*[\\/]}}rewrite-2.map"
+
diff --git a/test/Driver/unknown-gcc-arch.c b/test/Driver/unknown-gcc-arch.c
index 9e687b7..2aba50d 100644
--- a/test/Driver/unknown-gcc-arch.c
+++ b/test/Driver/unknown-gcc-arch.c
@@ -24,11 +24,11 @@
 
 
 // RUN: %clang -target powerpc64-unknown-unknown -c -x assembler %s -### -m32 \
-// RUN: 2>&1 | FileCheck -check-prefix=PPC64-M32 %s
+// RUN: -no-integrated-as 2>&1 | FileCheck -check-prefix=PPC64-M32 %s
 // PPC64-M32: {{.*as.*-a32}}
 
 // RUN: %clang -target powerpc-unknown-unknown -c -x assembler %s -### 2>&1 \
-// RUN:   | FileCheck -check-prefix=PPC %s
+// RUN: -no-integrated-as | FileCheck -check-prefix=PPC %s
 // PPC: {{.*as.*-a32}}
 
 // RUN: %clang -target sparc64-unknown-unknown -no-integrated-as -c -x assembler %s -### -m32 2>&1 \
diff --git a/test/Driver/warning-options.cpp b/test/Driver/warning-options.cpp
index f1a335d..4d9e1f7 100644
--- a/test/Driver/warning-options.cpp
+++ b/test/Driver/warning-options.cpp
@@ -3,11 +3,6 @@
 // RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s
 // LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128
 
-// FIXME: Remove this together with -Warc-abi once an Xcode is released that doesn't pass this flag.
-// RUN: %clang -### -Warc-abi -Wno-arc-abi %s 2>&1 | FileCheck -check-prefix=ARCABI %s
-// ARCABI-NOT: unknown warning option '-Warc-abi'
-// ARCABI-NOT: unknown warning option '-Wno-arc-abi'
-
 // Check that -isysroot warns on nonexistent paths.
 // RUN: %clang -### -c -target i386-apple-darwin10 -isysroot /FOO %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
 // CHECK-ISYSROOT: warning: no such sysroot directory: '{{([A-Za-z]:.*)?}}/FOO'
diff --git a/test/Driver/warning-options_pedantic.cpp b/test/Driver/warning-options_pedantic.cpp
index e40f771..4dbf92d 100644
--- a/test/Driver/warning-options_pedantic.cpp
+++ b/test/Driver/warning-options_pedantic.cpp
@@ -1,7 +1,13 @@
-// RUN: %clang -### -pedantic -no-pedantic %s 2>&1 | FileCheck -check-prefix=NO_PEDANTIC %s
-// RUN: %clang -### -pedantic -Wno-pedantic %s 2>&1 | FileCheck -check-prefix=PEDANTIC %s
+// Make sure we don't match the -NOT lines with the linker invocation.
+// Delimiters match the start of the cc1 and the start of the linker lines
+// DELIMITERS: {{^ *"}}
+
+// RUN: %clang -### -pedantic -no-pedantic %s 2>&1 | FileCheck -check-prefix=NO_PEDANTIC -check-prefix=DELIMITERS %s
+// RUN: %clang -### -pedantic -Wno-pedantic %s 2>&1 | FileCheck -check-prefix=PEDANTIC -check-prefix=DELIMITERS %s
 // NO_PEDANTIC-NOT: -pedantic
-// RUN: %clang -### -pedantic -pedantic -no-pedantic -pedantic %s 2>&1 | FileCheck -check-prefix=PEDANTIC %s
-// RUN: %clang -### -pedantic -pedantic -no-pedantic -Wpedantic %s 2>&1 | FileCheck -check-prefix=NO_PEDANTIC %s
+// RUN: %clang -### -pedantic -pedantic -no-pedantic -pedantic %s 2>&1 | FileCheck -check-prefix=PEDANTIC -check-prefix=DELIMITERS %s
+// RUN: %clang -### -pedantic -pedantic -no-pedantic -Wpedantic %s 2>&1 | FileCheck -check-prefix=NO_PEDANTIC -check-prefix=DELIMITERS %s
 // PEDANTIC: -pedantic
 // REQUIRES: clang-driver
+
+// DELIMITERS: {{^ *"}}
diff --git a/test/Driver/windows-cross.c b/test/Driver/windows-cross.c
index c8dbfdb..979f685 100644
--- a/test/Driver/windows-cross.c
+++ b/test/Driver/windows-cross.c
@@ -6,27 +6,27 @@
 // RUN: %clang -### -target armv7-windows-itanium --sysroot %s/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -rtlib=compiler-rt -o /dev/null %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-RTLIB
 
-// CHECK-RTLIB: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" "mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbegin.obj" "-L{{.*}}/Inputs/Windows/ARM/8.1/usr/lib" "-L{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/gcc" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}libclang_rt.builtins-arm.lib"
+// CHECK-RTLIB: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" "mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbegin.obj" "-L{{.*}}/Inputs/Windows/ARM/8.1/usr/lib" "-L{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/gcc" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}clang_rt.builtins-arm.lib"
 
 // RUN: %clang -### -target armv7-windows-itanium --sysroot %S/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -rtlib=compiler-rt -stdlib=libc++ -o /dev/null %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-C-LIBCXX
 
-// CHECK-C-LIBCXX: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" "mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbegin.obj" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}libclang_rt.builtins-arm.lib"
+// CHECK-C-LIBCXX: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" "mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbegin.obj" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}clang_rt.builtins-arm.lib"
 
 // RUN: %clangxx -### -target armv7-windows-itanium --sysroot %S/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -rtlib=compiler-rt -stdlib=libc++ -o /dev/null %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-LIBCXX
 
-// CHECK-LIBCXX: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" "mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbegin.obj" "{{.*}}.o" "-lc++" "-lmsvcrt" "{{.*[\\/]}}libclang_rt.builtins-arm.lib"
+// CHECK-LIBCXX: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" "mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbegin.obj" "{{.*}}.o" "-lc++" "-lmsvcrt" "{{.*[\\/]}}clang_rt.builtins-arm.lib"
 
 // RUN: %clang -### -target armv7-windows-itanium --sysroot %S/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -shared -rtlib=compiler-rt -stdlib=libc++ -o shared.dll %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-SHARED
 
-// CHECK-SHARED: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-shared" "-Bdynamic" "--enable-auto-image-base" "--entry" "_DllMainCRTStartup" "--allow-multiple-definition" "-o" "shared.dll" "--out-implib" "shared.lib" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbeginS.obj" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}libclang_rt.builtins-arm.lib"
+// CHECK-SHARED: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-shared" "-Bdynamic" "--enable-auto-image-base" "--entry" "_DllMainCRTStartup" "--allow-multiple-definition" "-o" "shared.dll" "--out-implib" "shared.lib" "{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/crtbeginS.obj" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}clang_rt.builtins-arm.lib"
 
 // RUN: %clang -### -target armv7-windows-itanium --sysroot %s/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -shared -rtlib=compiler-rt -stdlib=libc++ -nostartfiles -o shared.dll %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-NOSTARTFILES
 
-// CHECK-NOSTARTFILES: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-shared" "-Bdynamic" "--enable-auto-image-base" "--entry" "_DllMainCRTStartup" "--allow-multiple-definition" "-o" "shared.dll" "--out-implib" "shared.lib" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}libclang_rt.builtins-arm.lib"
+// CHECK-NOSTARTFILES: armv7-windows-itanium-ld" "--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-shared" "-Bdynamic" "--enable-auto-image-base" "--entry" "_DllMainCRTStartup" "--allow-multiple-definition" "-o" "shared.dll" "--out-implib" "shared.lib" "{{.*}}.o" "-lmsvcrt" "{{.*[\\/]}}clang_rt.builtins-arm.lib"
 
 // RUN: %clang -### -target armv7-windows-itanium --sysroot %S/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -shared -rtlib=compiler-rt -stdlib=libc++ -nostartfiles -nodefaultlibs -o shared.dll %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-STANDALONE
diff --git a/test/Driver/x86-march.c b/test/Driver/x86-march.c
new file mode 100644
index 0000000..fd6e30b
--- /dev/null
+++ b/test/Driver/x86-march.c
@@ -0,0 +1,105 @@
+// Ensure we support the various CPU architecture names.
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=nocona 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=nocona
+// nocona: "-target-cpu" "nocona"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=core2 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=core2
+// core2: "-target-cpu" "core2"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=penryn 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=penryn
+// penryn: "-target-cpu" "penryn"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=nehalem 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=nehalem
+// nehalem: "-target-cpu" "nehalem"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=westmere 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=westmere
+// westmere: "-target-cpu" "westmere"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=sandybridge 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=sandybridge
+// sandybridge: "-target-cpu" "sandybridge"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=ivybridge 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=ivybridge
+// ivybridge: "-target-cpu" "ivybridge"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=haswell 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=haswell
+// haswell: "-target-cpu" "haswell"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=broadwell 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=broadwell
+// broadwell: "-target-cpu" "broadwell"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=bonnell 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=bonnell
+// bonnell: "-target-cpu" "bonnell"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=silvermont 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=silvermont
+// silvermont: "-target-cpu" "silvermont"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=k8 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=k8
+// k8: "-target-cpu" "k8"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=opteron 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=opteron
+// opteron: "-target-cpu" "opteron"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=athlon64 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=athlon64
+// athlon64: "-target-cpu" "athlon64"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=athlon-fx 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=athlon-fx
+// athlon-fx: "-target-cpu" "athlon-fx"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=k8-sse3 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=k8-sse3
+// k8-sse3: "-target-cpu" "k8-sse3"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=opteron-sse3 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=opteron-sse3
+// opteron-sse3: "-target-cpu" "opteron-sse3"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=athlon64-sse3 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=athlon64-sse3
+// athlon64-sse3: "-target-cpu" "athlon64-sse3"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=amdfam10 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=amdfam10
+// amdfam10: "-target-cpu" "amdfam10"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=barcelona 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=barcelona
+// barcelona: "-target-cpu" "barcelona"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=bdver1 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=bdver1
+// bdver1: "-target-cpu" "bdver1"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=bdver2 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=bdver2
+// bdver2: "-target-cpu" "bdver2"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=bdver3 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=bdver3
+// bdver3: "-target-cpu" "bdver3"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=bdver4 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=bdver4
+// bdver4: "-target-cpu" "bdver4"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=btver1 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=btver1
+// btver1: "-target-cpu" "btver1"
+//
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=btver2 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=btver2
+// btver2: "-target-cpu" "btver2"
diff --git a/test/Driver/xcore-opts.c b/test/Driver/xcore-opts.c
index 161756d..9300085 100644
--- a/test/Driver/xcore-opts.c
+++ b/test/Driver/xcore-opts.c
@@ -12,10 +12,10 @@
 // CHECK-NOT: "-fexceptions"
 // CHECK: "-fno-common"
 // CHECK: xcc" "-o"
-// CHECK-EXCEP-NOT: "-fexceptions"
+// CHECK-NOT: "-fexceptions"
 // CHECK: "-c" "-v" "-g" "-fverbose-asm" "A1Arg" "A2Arg"
 // CHECK: xcc" "-o"
-// CHECK-EXCEP-NOT: "-fexceptions"
+// CHECK-NOT: "-fexceptions"
 // CHECK: "-v"
 // CHECK: "L1Arg" "L2Arg"
 
diff --git a/test/FixIt/fixit.cpp b/test/FixIt/fixit.cpp
index 20b5b52..585c216 100644
--- a/test/FixIt/fixit.cpp
+++ b/test/FixIt/fixit.cpp
@@ -381,3 +381,9 @@
 };
 #endif
 }
+
+struct conversion_operator {
+  conversion_operator::* const operator int(); // expected-error {{put the complete type after 'operator'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:32}:""
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:44-[[@LINE-2]]:44}:" conversion_operator::* const"
+};
diff --git a/test/FixIt/typo-location-bugs.cpp b/test/FixIt/typo-location-bugs.cpp
index e44664d..c7111a8 100644
--- a/test/FixIt/typo-location-bugs.cpp
+++ b/test/FixIt/typo-location-bugs.cpp
@@ -34,3 +34,16 @@
   b.f(1);  // expected-error{{too many arguments to function call, expected 0, have 1; did you mean 'A::f'?}}
 }
 }
+
+namespace PR20626 {
+class A {
+public:
+  void Foo(){};  // expected-note{{'Foo' declared here}}
+};
+class B {};
+class C : public A, public B {
+  void Run() {
+    B::Foo();  // expected-error{{no member named 'Foo' in 'PR20626::B'; did you mean simply 'Foo'?}}
+  }
+};
+}
diff --git a/test/Frontend/darwin-version.c b/test/Frontend/darwin-version.c
index 2e0804b..2da0c4c 100644
--- a/test/Frontend/darwin-version.c
+++ b/test/Frontend/darwin-version.c
@@ -1,27 +1,27 @@
-// RUN: %clang -target armv6-apple-darwin9 -dM -E -o %t %s
-// RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
-// RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1050' | count 1
-// RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=3.0 -dM -E -o %t %s
+// RUN: %clang_cc1 -triple armv6-apple-ios3.0.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '30000' | count 1
 // RUN: not grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t
-// RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=2.0 -dM -E -o %t %s
+// RUN: %clang_cc1 -triple armv6-apple-ios2.0.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '20000' | count 1
 // RUN: not grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t
-// RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=2.2 -dM -E -o %t %s
+// RUN: %clang_cc1 -triple armv6-apple-ios2.2.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '20200' | count 1
-// RUN: %clang -target i686-apple-darwin8 -dM -E -o %t %s
-// RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
+// RUN: not grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t
+// RUN: %clang_cc1 -triple armv6-apple-ios2.3.1 -dM -E -o %t %s
+// RUN: grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t | grep '20301' | count 1
+// RUN: not grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t
+// RUN: %clang_cc1 -triple i386-apple-macosx10.4.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1040' | count 1
-// RUN: %clang -target i686-apple-darwin9 -dM -E -o %t %s
-// RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1050' | count 1
-// RUN: %clang -target i686-apple-darwin10 -dM -E -o %t %s
-// RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1060' | count 1
-// RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.4 -dM -E -o %t %s
 // RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
-// RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1040' | count 1
-// RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.5 -dM -E -o %t %s
+// RUN: %clang_cc1 -triple i386-apple-macosx10.4.10 -dM -E -o %t %s
+// RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1049' | count 1
+// RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
+// RUN: %clang_cc1 -triple i386-apple-macosx10.5.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1050' | count 1
-// RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.6 -dM -E -o %t %s
+// RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
+// RUN: %clang_cc1 -triple i386-apple-macosx10.6.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '1060' | count 1
-// RUN: %clang -target x86_64-apple-macosx -mmacosx-version-min=10.10 -dM -E -o %t %s
+// RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.10.0 -dM -E -o %t %s
 // RUN: grep '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' %t | grep '101000' | count 1
+// RUN: not grep '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' %t
diff --git a/test/Frontend/dependency-generation-crash.c b/test/Frontend/dependency-generation-crash.c
index 181bb71..63a6a77 100644
--- a/test/Frontend/dependency-generation-crash.c
+++ b/test/Frontend/dependency-generation-crash.c
@@ -1,4 +1,8 @@
 // RUN: touch %t
 // RUN: chmod 0 %t
-// %clang -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null
+// RUN: not %clang_cc1 -E -dependency-file bla -MT %t -MP -o %t -x c /dev/null 2>&1 | FileCheck %s
+// RUN: rm -f %t
+
+// CHECK: error: unable to open output file
+
 // rdar://9286457
diff --git a/test/Frontend/invalid-o-level.c b/test/Frontend/invalid-o-level.c
index 73be9b1..0314448 100644
--- a/test/Frontend/invalid-o-level.c
+++ b/test/Frontend/invalid-o-level.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 %s -O900 -o /dev/null 2> %t.log
-// RUN: FileCheck %s -input-file=%t.log
+// RUN: %clang_cc1 %s -O900 -o /dev/null 2>&1 | FileCheck %s
 
-// CHECK: warning: optimization level '-O900' is not supported; using '-O3' instead
+// RUN: %clang_cc1 %s -O8 -o /dev/null 2>&1 | FileCheck %s
+
+// CHECK: warning: optimization level '-O{{.*}}' is not supported; using '-O3' instead
diff --git a/test/Frontend/rewrite-includes-line-markers.c b/test/Frontend/rewrite-includes-line-markers.c
new file mode 100644
index 0000000..14692a1
--- /dev/null
+++ b/test/Frontend/rewrite-includes-line-markers.c
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -E -frewrite-includes -I %S/Inputs %s | FileCheck %s --check-prefix=GNU
+// RUN: %clang_cc1 -E -frewrite-includes -fuse-line-directives -I %S/Inputs %s | FileCheck %s --check-prefix=LINE
+#include "test.h"
+int f() { return x; }
+
+// GNU: {{^}}# 1 "{{.*}}rewrite-includes-line-markers.c"
+// GNU: {{^}}#include "test.h"
+// GNU: {{^}}# 1 "{{.*}}test.h"
+// GNU: {{^}}#include "test2.h"
+// GNU: {{^}}# 1 "{{.*}}test2.h"
+// GNU: {{^}}int x;
+// GNU: {{^}}# 4 "{{.*}}rewrite-includes-line-markers.c" 2
+// GNU: {{^}}int f() { return x; }
+
+// LINE: {{^}}#line 1 "{{.*}}rewrite-includes-line-markers.c"
+// LINE: {{^}}#include "test.h"
+// LINE: {{^}}#line 1 "{{.*}}test.h"
+// LINE: {{^}}#include "test2.h"
+// LINE: {{^}}#line 1 "{{.*}}test2.h"
+// LINE: {{^}}int x;
+// LINE: {{^}}#line 4 "{{.*}}rewrite-includes-line-markers.c"
+// LINE: {{^}}int f() { return x; }
diff --git a/test/Frontend/source-col-map.c b/test/Frontend/source-col-map.c
new file mode 100644
index 0000000..a14023b
--- /dev/null
+++ b/test/Frontend/source-col-map.c
@@ -0,0 +1,37 @@
+// RUN: not %clang_cc1 %s -fsyntax-only -fmessage-length 75 -o /dev/null 2>&1 | FileCheck %s -strict-whitespace
+
+// Test case for the text diagnostics source column conversion crash.
+
+// This test case tries to check the error diagnostic message printer, which is
+// responsible to create the code snippet shorter than the message-length (in
+// number of columns.)
+//
+// The error diagnostic message printer should be able to handle the non-ascii
+// characters without any segmentation fault or assertion failure.  If your
+// changes to clang frontend crashes this case, it is likely that you are mixing
+// column index with byte index which are two totally different concepts.
+
+// NOTE: This file is encoded in UTF-8 and intentionally contains some
+// non-ASCII characters.
+
+__attribute__((format(printf, 1, 2)))
+extern int printf(const char *fmt, ...);
+
+void test1(Unknown* b);  // αααα αααα αααα αααα αααα αααα αααα αααα αααα αααα αααα
+// CHECK: unknown type name 'Unknown'
+// CHECK-NEXT: void test1(Unknown* b);  // αααα αααα αααα αααα αααα αααα αααα ααα...
+// CHECK-NEXT: {{^           \^$}}
+
+void test2(Unknown* b);  // αααα αααα αααα αααα αααα αααα αααα αααα αααα
+
+// CHECK: unknown type name 'Unknown'
+// CHECK-NEXT: void test2(Unknown* b);  // αααα αααα αααα αααα αααα αααα αααα αααα αααα
+// CHECK-NEXT: {{^           \^$}}
+
+void test3() {
+   /* αααα αααα αααα αααα αααα αααα αααα αααα αααα αααα */ printf("%d", "s");
+}
+// CHECK:       format specifies type 'int' but the argument has type 'char *'
+// CHECK-NEXT:   ...αααα αααα αααα αααα αααα αααα αααα αααα αααα */ printf("%d", "s");
+// CHECK-NEXT: {{^                                                             ~~   \^~~$}}
+// CHECK-NEXT: {{^                                                             %s$}}
diff --git a/test/Frontend/trigraphs.cpp b/test/Frontend/trigraphs.cpp
new file mode 100644
index 0000000..5520789
--- /dev/null
+++ b/test/Frontend/trigraphs.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -DSTDCPP11 -std=c++11 -verify -fsyntax-only %s
+// RUN: %clang_cc1 -DSTDGNU11 -std=gnu++11 -verify -fsyntax-only %s
+// RUN: %clang_cc1 -DSTDGNU11TRI -ftrigraphs -std=gnu++11 -verify -fsyntax-only %s
+// RUN: %clang_cc1 -DSTDCPP17 -std=c++1z -verify -fsyntax-only %s
+// RUN: %clang_cc1 -DSTDCPP17TRI -ftrigraphs -std=c++1z -verify -fsyntax-only %s
+// RUN: %clang_cc1 -DMSCOMPAT -fms-compatibility -std=c++11 -verify -fsyntax-only %s
+
+void foo() {
+#if defined(NOFLAGS) || defined(STDCPP11) || defined(STDGNU11TRI) || \
+    defined(STDCPP17TRI)
+  const char c[] = "??/n"; // expected-warning{{trigraph converted to '\' character}}
+#elif defined(STDGNU11) || defined(STDCPP17) || defined(MSCOMPAT)
+  const char c[] = "??/n"; // expected-warning{{trigraph ignored}}
+#else
+#error Not handled.
+#endif
+}
diff --git a/test/Frontend/verify-unknown-arg.c b/test/Frontend/verify-unknown-arg.c
new file mode 100644
index 0000000..5767dae
--- /dev/null
+++ b/test/Frontend/verify-unknown-arg.c
@@ -0,0 +1,6 @@
+// RUN: not %clang_cc1 -asdf -verify %s 2>&1 | FileCheck %s
+
+// expected-no-diagnostics
+
+//      CHECK: error: 'error' diagnostics seen but not expected:
+// CHECK-NEXT: (frontend): unknown argument: '-asdf'
diff --git a/test/Frontend/x86-target-cpu.c b/test/Frontend/x86-target-cpu.c
new file mode 100644
index 0000000..769c40a
--- /dev/null
+++ b/test/Frontend/x86-target-cpu.c
@@ -0,0 +1,30 @@
+// Ensure we support the various CPU names.
+//
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu nocona -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu core2 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu penryn -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu nehalem -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu westmere -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu sandybridge -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu ivybridge -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu haswell -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu broadwell -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu bonnell -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu silvermont -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu k8 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu opteron -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu athlon64 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu athlon-fx -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu k8-sse3 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu opteron-sse3 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu athlon64-sse3 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu amdfam10 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu barcelona -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu bdver1 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu bdver2 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu bdver3 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu bdver4 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu btver1 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -target-cpu btver2 -verify %s
+//
+// expected-no-diagnostics
diff --git a/test/Frontend/x86_64-nacl-types.cpp b/test/Frontend/x86_64-nacl-types.cpp
index a994cb7..ca20014 100644
--- a/test/Frontend/x86_64-nacl-types.cpp
+++ b/test/Frontend/x86_64-nacl-types.cpp
@@ -6,14 +6,14 @@
 
 static_assert(alignof(char) == 1, "alignof char is wrong");
 
-static_assert(alignof(short) == 2, "sizeof short is wrong");
+static_assert(sizeof(short) == 2, "sizeof short is wrong");
 static_assert(alignof(short) == 2, "alignof short is wrong");
 
-static_assert(alignof(int) == 4, "sizeof int is wrong");
+static_assert(sizeof(int) == 4, "sizeof int is wrong");
 static_assert(alignof(int) == 4, "alignof int is wrong");
 
 static_assert(sizeof(long) == 4, "sizeof long is wrong");
-static_assert(sizeof(long) == 4, "alignof long is wrong");
+static_assert(alignof(long) == 4, "alignof long is wrong");
 
 static_assert(sizeof(long long) == 8, "sizeof long long is wrong wrong");
 static_assert(alignof(long long) == 8, "alignof long long is wrong wrong");
diff --git a/test/Headers/arm64-apple-ios-types.cpp b/test/Headers/arm64-apple-ios-types.cpp
new file mode 100644
index 0000000..7e7bc8b
--- /dev/null
+++ b/test/Headers/arm64-apple-ios-types.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -triple arm64-apple-ios7.0 -std=c++11 -verify %s
+// expected-no-diagnostics
+
+struct true_type {
+  static constexpr const bool value = true;
+};
+
+struct false_type {
+  static constexpr const bool value = false;
+};
+
+template <class _Tp, class _Up> struct is_same           : public false_type {};
+template <class _Tp>            struct is_same<_Tp, _Tp> : public true_type {};
+
+// Check that our 'is_same' works.
+static_assert(is_same<char, char>::value, "is_same is broken");
+static_assert(!is_same<char, char *>::value, "is_same is broken");
+
+template <class _Tp, unsigned _AlignOf, unsigned _SizeOf>
+struct check_type {
+  static constexpr const bool value =
+    (alignof(_Tp) == _AlignOf) && (sizeof(_Tp) == _SizeOf);
+};
+
+//===----------------------------------------------------------------------===//
+// Fundamental types
+//===----------------------------------------------------------------------===//
+
+static_assert(check_type<bool, 1, 1>::value, "bool is wrong");
+
+static_assert(check_type<char, 1, 1>::value, "char is wrong");
+static_assert(check_type<signed char, 1, 1>::value, "signed char is wrong");
+static_assert(check_type<unsigned char, 1, 1>::value, "unsigned char is wrong");
+
+static_assert(check_type<char16_t, 2, 2>::value, "char16_t is wrong");
+static_assert(check_type<char32_t, 4, 4>::value, "char32_t is wrong");
+static_assert(check_type<wchar_t, 4, 4>::value, "wchar_t is wrong");
+
+static_assert(check_type<short, 2, 2>::value, "short is wrong");
+static_assert(check_type<unsigned short, 2, 2>::value, "unsigned short is wrong");
+
+static_assert(check_type<int, 4, 4>::value, "int is wrong");
+static_assert(check_type<unsigned int, 4, 4>::value, "unsigned int is wrong");
+
+static_assert(check_type<long, 8, 8>::value, "long is wrong");
+static_assert(check_type<unsigned long, 8, 8>::value, "unsigned long is wrong");
+
+static_assert(check_type<long long, 8, 8>::value, "long long is wrong");
+static_assert(check_type<unsigned long long, 8, 8>::value, "unsigned long long is wrong");
+
+static_assert(check_type<float, 4, 4>::value, "float is wrong");
+static_assert(check_type<double, 8, 8>::value, "double is wrong");
+static_assert(check_type<long double, 8, 8>::value, "long double is wrong");
+
+static_assert(check_type<void *, 8, 8>::value, "'void *' is wrong");
+static_assert(check_type<int (*)(int), 8, 8>::value, "function pointer is wrong");
+
+//===----------------------------------------------------------------------===//
+// stdarg.h
+//===----------------------------------------------------------------------===//
+
+#include <stdarg.h>
+
+static_assert(check_type<va_list, 8, 8>::value, "va_list is wrong");
+
+//===----------------------------------------------------------------------===//
+// stddef.h
+//===----------------------------------------------------------------------===//
+
+#define __STDC_WANT_LIB_EXT1__ 1
+#include <stddef.h>
+
+static_assert(is_same<long int, ::ptrdiff_t>::value, "::ptrdiff_t is wrong");
+static_assert(is_same<decltype(sizeof(char)), ::size_t>::value, "::size_t is wrong");
+static_assert(is_same<long unsigned int, ::size_t>::value, "::size_t is wrong");
+static_assert(is_same<long unsigned int, ::rsize_t>::value, "::rsize_t is wrong");
+static_assert(is_same<long double, ::max_align_t>::value, "::max_align_t is wrong");
+
+#define __need_wint_t
+#include <stddef.h>
+
+static_assert(is_same<int, ::wint_t>::value, "::wint_t is wrong");
+
diff --git a/test/Headers/thumbv7-apple-ios-types.cpp b/test/Headers/thumbv7-apple-ios-types.cpp
new file mode 100644
index 0000000..e0f77c3
--- /dev/null
+++ b/test/Headers/thumbv7-apple-ios-types.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -triple thumbv7-apple-ios7.0 -target-abi apcs-gnu -std=c++11 -verify %s
+// expected-no-diagnostics
+
+struct true_type {
+  static constexpr const bool value = true;
+};
+
+struct false_type {
+  static constexpr const bool value = false;
+};
+
+template <class _Tp, class _Up> struct is_same           : public false_type {};
+template <class _Tp>            struct is_same<_Tp, _Tp> : public true_type {};
+
+// Check that our 'is_same' works.
+static_assert(is_same<char, char>::value, "is_same is broken");
+static_assert(!is_same<char, char *>::value, "is_same is broken");
+
+template <class _Tp, unsigned _AlignOf, unsigned _SizeOf>
+struct check_type {
+  static constexpr const bool value =
+    (alignof(_Tp) == _AlignOf) && (sizeof(_Tp) == _SizeOf);
+};
+
+//===----------------------------------------------------------------------===//
+// Fundamental types
+//===----------------------------------------------------------------------===//
+
+static_assert(check_type<bool, 1, 1>::value, "bool is wrong");
+
+static_assert(check_type<char, 1, 1>::value, "char is wrong");
+static_assert(check_type<signed char, 1, 1>::value, "signed char is wrong");
+static_assert(check_type<unsigned char, 1, 1>::value, "unsigned char is wrong");
+
+static_assert(check_type<char16_t, 2, 2>::value, "char16_t is wrong");
+static_assert(check_type<char32_t, 4, 4>::value, "char32_t is wrong");
+static_assert(check_type<wchar_t, 4, 4>::value, "wchar_t is wrong");
+
+static_assert(check_type<short, 2, 2>::value, "short is wrong");
+static_assert(check_type<unsigned short, 2, 2>::value, "unsigned short is wrong");
+
+static_assert(check_type<int, 4, 4>::value, "int is wrong");
+static_assert(check_type<unsigned int, 4, 4>::value, "unsigned int is wrong");
+
+static_assert(check_type<long, 4, 4>::value, "long is wrong");
+static_assert(check_type<unsigned long, 4, 4>::value, "unsigned long is wrong");
+
+static_assert(check_type<long long, 8, 8>::value, "long long is wrong");
+static_assert(check_type<unsigned long long, 8, 8>::value, "unsigned long long is wrong");
+
+static_assert(check_type<float, 4, 4>::value, "float is wrong");
+static_assert(check_type<double, 8, 8>::value, "double is wrong");
+static_assert(check_type<long double, 4, 8>::value, "long double is wrong");
+
+static_assert(check_type<void *, 4, 4>::value, "'void *' is wrong");
+static_assert(check_type<int (*)(int), 4, 4>::value, "function pointer is wrong");
+
+//===----------------------------------------------------------------------===//
+// stdarg.h
+//===----------------------------------------------------------------------===//
+
+#include <stdarg.h>
+
+static_assert(check_type<va_list, 4, 4>::value, "va_list is wrong");
+
+//===----------------------------------------------------------------------===//
+// stddef.h
+//===----------------------------------------------------------------------===//
+
+#define __STDC_WANT_LIB_EXT1__ 1
+#include <stddef.h>
+
+static_assert(is_same<int, ::ptrdiff_t>::value, "::ptrdiff_t is wrong");
+static_assert(is_same<decltype(sizeof(char)), ::size_t>::value, "::size_t is wrong");
+static_assert(is_same<long unsigned int, ::size_t>::value, "::size_t is wrong");
+static_assert(is_same<long unsigned int, ::rsize_t>::value, "::rsize_t is wrong");
+static_assert(is_same<long double, ::max_align_t>::value, "::max_align_t is wrong");
+
+#define __need_wint_t
+#include <stddef.h>
+
+static_assert(is_same<int, ::wint_t>::value, "::wint_t is wrong");
+
diff --git a/test/Headers/x86_64-apple-macosx-types.cpp b/test/Headers/x86_64-apple-macosx-types.cpp
new file mode 100644
index 0000000..7cbff6e
--- /dev/null
+++ b/test/Headers/x86_64-apple-macosx-types.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -std=c++11 -verify %s
+// expected-no-diagnostics
+
+struct true_type {
+  static constexpr const bool value = true;
+};
+
+struct false_type {
+  static constexpr const bool value = false;
+};
+
+template <class _Tp, class _Up> struct is_same           : public false_type {};
+template <class _Tp>            struct is_same<_Tp, _Tp> : public true_type {};
+
+// Check that our 'is_same' works.
+static_assert(is_same<char, char>::value, "is_same is broken");
+static_assert(!is_same<char, char *>::value, "is_same is broken");
+
+template <class _Tp, unsigned _AlignOf, unsigned _SizeOf>
+struct check_type {
+  static constexpr const bool value =
+    (alignof(_Tp) == _AlignOf) && (sizeof(_Tp) == _SizeOf);
+};
+
+//===----------------------------------------------------------------------===//
+// Fundamental types
+//===----------------------------------------------------------------------===//
+
+static_assert(check_type<bool, 1, 1>::value, "bool is wrong");
+
+static_assert(check_type<char, 1, 1>::value, "char is wrong");
+static_assert(check_type<signed char, 1, 1>::value, "signed char is wrong");
+static_assert(check_type<unsigned char, 1, 1>::value, "unsigned char is wrong");
+
+static_assert(check_type<char16_t, 2, 2>::value, "char16_t is wrong");
+static_assert(check_type<char32_t, 4, 4>::value, "char32_t is wrong");
+static_assert(check_type<wchar_t, 4, 4>::value, "wchar_t is wrong");
+
+static_assert(check_type<short, 2, 2>::value, "short is wrong");
+static_assert(check_type<unsigned short, 2, 2>::value, "unsigned short is wrong");
+
+static_assert(check_type<int, 4, 4>::value, "int is wrong");
+static_assert(check_type<unsigned int, 4, 4>::value, "unsigned int is wrong");
+
+static_assert(check_type<long, 8, 8>::value, "long is wrong");
+static_assert(check_type<unsigned long, 8, 8>::value, "unsigned long is wrong");
+
+static_assert(check_type<long long, 8, 8>::value, "long long is wrong");
+static_assert(check_type<unsigned long long, 8, 8>::value, "unsigned long long is wrong");
+
+static_assert(check_type<float, 4, 4>::value, "float is wrong");
+static_assert(check_type<double, 8, 8>::value, "double is wrong");
+static_assert(check_type<long double, 16, 16>::value, "long double is wrong");
+
+static_assert(check_type<void *, 8, 8>::value, "'void *' is wrong");
+static_assert(check_type<int (*)(int), 8, 8>::value, "function pointer is wrong");
+
+//===----------------------------------------------------------------------===//
+// stdarg.h
+//===----------------------------------------------------------------------===//
+
+#include <stdarg.h>
+
+static_assert(check_type<va_list, 8, 24>::value, "va_list is wrong");
+
+//===----------------------------------------------------------------------===//
+// stddef.h
+//===----------------------------------------------------------------------===//
+
+#define __STDC_WANT_LIB_EXT1__ 1
+#include <stddef.h>
+
+static_assert(is_same<long int, ::ptrdiff_t>::value, "::ptrdiff_t is wrong");
+static_assert(is_same<decltype(sizeof(char)), ::size_t>::value, "::size_t is wrong");
+static_assert(is_same<long unsigned int, ::size_t>::value, "::size_t is wrong");
+static_assert(is_same<long unsigned int, ::rsize_t>::value, "::rsize_t is wrong");
+static_assert(is_same<long double, ::max_align_t>::value, "::max_align_t is wrong");
+
+#define __need_wint_t
+#include <stddef.h>
+
+static_assert(is_same<int, ::wint_t>::value, "::wint_t is wrong");
+
diff --git a/test/Headers/x86intrin.c b/test/Headers/x86intrin.c
index 4c9665b..6a1608b 100644
--- a/test/Headers/x86intrin.c
+++ b/test/Headers/x86intrin.c
@@ -84,6 +84,24 @@
 #ifndef __RDRND__
 #define __RDRND__
 #endif
+#ifndef __SHA__
+#define __SHA__
+#endif
+#ifndef __ADX__
+#define __ADX__
+#endif
+#ifndef __TBM__
+#define __TBM__
+#endif
+#ifndef __RTM__
+#define __RTM__
+#endif
+#ifndef __PCLMUL__
+#define __PCLMUL__
+#endif
+#ifndef __FSGSBASE__
+#define __FSGSBASE__
+#endif
 #ifndef __AVX512F__
 #define __AVX512F__
 #endif
@@ -96,6 +114,15 @@
 #ifndef __AVX512ER__
 #define __AVX512ER__
 #endif
+#ifndef __AVX512PF__
+#define __AVX512PF__
+#endif
+#ifndef __AVX512DQ__
+#define __AVX512DQ__
+#endif
+#ifndef __AVX512CD__
+#define __AVX512CD__
+#endif
 
 // Now include the metaheader that includes all x86 intrinsic headers.
 #include <x86intrin.h>
diff --git a/test/Index/code-completion.cpp b/test/Index/code-completion.cpp
index 5789d3b..83aa943 100644
--- a/test/Index/code-completion.cpp
+++ b/test/Index/code-completion.cpp
@@ -58,9 +58,9 @@
 // CHECK-MEMBER-NEXT: Container is complete
 // CHECK-MEMBER-NEXT: Container USR: c:@S@Z
 
-// CHECK-OVERLOAD: NotImplemented:{ResultType int &}{Text overloaded}{LeftParen (}{Text Z z}{Comma , }{CurrentParameter int second}{RightParen )}
-// CHECK-OVERLOAD: NotImplemented:{ResultType float &}{Text overloaded}{LeftParen (}{Text int i}{Comma , }{CurrentParameter long second}{RightParen )}
-// CHECK-OVERLOAD: NotImplemented:{ResultType double &}{Text overloaded}{LeftParen (}{Text float f}{Comma , }{CurrentParameter int second}{RightParen )}
+// CHECK-OVERLOAD: OverloadCandidate:{ResultType int &}{Text overloaded}{LeftParen (}{Placeholder Z z}{Comma , }{CurrentParameter int second}{RightParen )}
+// CHECK-OVERLOAD: OverloadCandidate:{ResultType float &}{Text overloaded}{LeftParen (}{Placeholder int i}{Comma , }{CurrentParameter long second}{RightParen )}
+// CHECK-OVERLOAD: OverloadCandidate:{ResultType double &}{Text overloaded}{LeftParen (}{Placeholder float f}{Comma , }{CurrentParameter int second}{RightParen )}
 // CHECK-OVERLOAD: Completion contexts:
 // CHECK-OVERLOAD-NEXT: Any type
 // CHECK-OVERLOAD-NEXT: Any value
diff --git a/test/Index/comment-to-html-xml-conversion.cpp b/test/Index/comment-to-html-xml-conversion.cpp
index 95e11c3..f31061a 100644
--- a/test/Index/comment-to-html-xml-conversion.cpp
+++ b/test/Index/comment-to-html-xml-conversion.cpp
@@ -325,7 +325,7 @@
 template<typename T>
 void test_cmd_tparam_1(T aaa);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_1:{{.*}} FullCommentAsHTML=[<dl><dt class="param-name-index-0">aaa</dt><dd class="param-descr-index-0"> Blah blah</dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_1</Name><USR>c:@FT@&gt;1#Ttest_cmd_tparam_1#t0.0#</USR><Declaration>template &lt;typename T&gt; void test_cmd_tparam_1(T aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_1:{{.*}} FullCommentAsHTML=[<dl><dt class="param-name-index-0">aaa</dt><dd class="param-descr-index-0"> Blah blah</dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_1</Name><USR>c:@FT@&gt;1#Ttest_cmd_tparam_1#t0.0#v#</USR><Declaration>template &lt;typename T&gt; void test_cmd_tparam_1(T aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
 // CHECK-NEXT:  CommentAST=[
 // CHECK-NEXT:    (CXComment_FullComment
 // CHECK-NEXT:       (CXComment_Paragraph IsWhitespace
@@ -342,7 +342,7 @@
 template<typename T>
 void test_cmd_tparam_2(T aaa);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_2:{{.*}} FullCommentAsHTML=[<dl><dt class="param-name-index-0">aaa</dt><dd class="param-descr-index-0"> Blah blah</dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_2</Name><USR>c:@FT@&gt;1#Ttest_cmd_tparam_2#t0.0#</USR><Declaration>template &lt;typename T&gt; void test_cmd_tparam_2(T aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_2:{{.*}} FullCommentAsHTML=[<dl><dt class="param-name-index-0">aaa</dt><dd class="param-descr-index-0"> Blah blah</dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_2</Name><USR>c:@FT@&gt;1#Ttest_cmd_tparam_2#t0.0#v#</USR><Declaration>template &lt;typename T&gt; void test_cmd_tparam_2(T aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
 // CHECK-NEXT:  CommentAST=[
 // CHECK-NEXT:    (CXComment_FullComment
 // CHECK-NEXT:       (CXComment_Paragraph IsWhitespace
@@ -359,7 +359,7 @@
 template<typename T1, typename T2>
 void test_cmd_tparam_3(T1 aaa, T2 bbb);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_3:{{.*}} FullCommentAsHTML=[<dl><dt class="tparam-name-index-0">T1</dt><dd class="tparam-descr-index-0"> Aaa</dd><dt class="tparam-name-index-1">T2</dt><dd class="tparam-descr-index-1"> Bbb </dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_3</Name><USR>c:@FT@&gt;2#T#Ttest_cmd_tparam_3#t0.0#t0.1#</USR><Declaration>template &lt;typename T1, typename T2&gt; void test_cmd_tparam_3(T1 aaa, T2 bbb)</Declaration><TemplateParameters><Parameter><Name>T1</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>T2</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_3:{{.*}} FullCommentAsHTML=[<dl><dt class="tparam-name-index-0">T1</dt><dd class="tparam-descr-index-0"> Aaa</dd><dt class="tparam-name-index-1">T2</dt><dd class="tparam-descr-index-1"> Bbb </dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_3</Name><USR>c:@FT@&gt;2#T#Ttest_cmd_tparam_3#t0.0#t0.1#v#</USR><Declaration>template &lt;typename T1, typename T2&gt; void test_cmd_tparam_3(T1 aaa, T2 bbb)</Declaration><TemplateParameters><Parameter><Name>T1</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>T2</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter></TemplateParameters></Function>]
 // CHECK-NEXT:  CommentAST=[
 // CHECK-NEXT:    (CXComment_FullComment
 // CHECK-NEXT:       (CXComment_Paragraph IsWhitespace
@@ -379,7 +379,7 @@
 template<typename T1, typename T2, int V>
 void test_cmd_tparam_4(T1 aaa, T2 bbb);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_4:{{.*}} FullCommentAsHTML=[<dl><dt class="tparam-name-index-0">T1</dt><dd class="tparam-descr-index-0"> Aaa</dd><dt class="tparam-name-index-1">T2</dt><dd class="tparam-descr-index-1"> Bbb </dd><dt class="tparam-name-index-2">V</dt><dd class="tparam-descr-index-2"> Ccc </dd><dt class="tparam-name-index-invalid">U</dt><dd class="tparam-descr-index-invalid"> Zzz </dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_4</Name><USR>c:@FT@&gt;3#T#T#NItest_cmd_tparam_4#t0.0#t0.1#</USR><Declaration>template &lt;typename T1, typename T2, int V&gt;\nvoid test_cmd_tparam_4(T1 aaa, T2 bbb)</Declaration><TemplateParameters><Parameter><Name>T1</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>T2</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>V</Name><Index>2</Index><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>U</Name><Discussion><Para> Zzz </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_4:{{.*}} FullCommentAsHTML=[<dl><dt class="tparam-name-index-0">T1</dt><dd class="tparam-descr-index-0"> Aaa</dd><dt class="tparam-name-index-1">T2</dt><dd class="tparam-descr-index-1"> Bbb </dd><dt class="tparam-name-index-2">V</dt><dd class="tparam-descr-index-2"> Ccc </dd><dt class="tparam-name-index-invalid">U</dt><dd class="tparam-descr-index-invalid"> Zzz </dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_4</Name><USR>c:@FT@&gt;3#T#T#NItest_cmd_tparam_4#t0.0#t0.1#v#</USR><Declaration>template &lt;typename T1, typename T2, int V&gt;\nvoid test_cmd_tparam_4(T1 aaa, T2 bbb)</Declaration><TemplateParameters><Parameter><Name>T1</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>T2</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>V</Name><Index>2</Index><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>U</Name><Discussion><Para> Zzz </Para></Discussion></Parameter></TemplateParameters></Function>]
 // CHECK-NEXT:  CommentAST=[
 // CHECK-NEXT:    (CXComment_FullComment
 // CHECK-NEXT:       (CXComment_Paragraph IsWhitespace
@@ -407,7 +407,7 @@
 template<template<template<typename T> class TT, class C> class TTT>
 void test_cmd_tparam_5();
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_5:{{.*}} FullCommentAsHTML=[<dl><dt class="tparam-name-index-0">TTT</dt><dd class="tparam-descr-index-0"> Ddd </dd><dt class="tparam-name-index-other">C</dt><dd class="tparam-descr-index-other"> Ccc </dd><dt class="tparam-name-index-other">T</dt><dd class="tparam-descr-index-other"> Aaa </dd><dt class="tparam-name-index-other">TT</dt><dd class="tparam-descr-index-other"> Bbb</dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_5</Name><USR>c:@FT@&gt;1#t&gt;2#t&gt;1#T#Ttest_cmd_tparam_5#</USR><Declaration>template &lt;template &lt;template &lt;typename T&gt; class TT, class C&gt; class TTT&gt;\nvoid test_cmd_tparam_5()</Declaration><TemplateParameters><Parameter><Name>TTT</Name><Index>0</Index><Discussion><Para> Ddd </Para></Discussion></Parameter><Parameter><Name>C</Name><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>T</Name><Discussion><Para> Aaa </Para></Discussion></Parameter><Parameter><Name>TT</Name><Discussion><Para> Bbb</Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=test_cmd_tparam_5:{{.*}} FullCommentAsHTML=[<dl><dt class="tparam-name-index-0">TTT</dt><dd class="tparam-descr-index-0"> Ddd </dd><dt class="tparam-name-index-other">C</dt><dd class="tparam-descr-index-other"> Ccc </dd><dt class="tparam-name-index-other">T</dt><dd class="tparam-descr-index-other"> Aaa </dd><dt class="tparam-name-index-other">TT</dt><dd class="tparam-descr-index-other"> Bbb</dd></dl>] FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>test_cmd_tparam_5</Name><USR>c:@FT@&gt;1#t&gt;2#t&gt;1#T#Ttest_cmd_tparam_5#v#</USR><Declaration>template &lt;template &lt;template &lt;typename T&gt; class TT, class C&gt; class TTT&gt;\nvoid test_cmd_tparam_5()</Declaration><TemplateParameters><Parameter><Name>TTT</Name><Index>0</Index><Discussion><Para> Ddd </Para></Discussion></Parameter><Parameter><Name>C</Name><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>T</Name><Discussion><Para> Aaa </Para></Discussion></Parameter><Parameter><Name>TT</Name><Discussion><Para> Bbb</Para></Discussion></Parameter></TemplateParameters></Function>]
 // CHECK-NEXT:  CommentAST=[
 // CHECK-NEXT:    (CXComment_FullComment
 // CHECK-NEXT:       (CXComment_Paragraph IsWhitespace
@@ -736,47 +736,47 @@
 
 /// Aaa.
 class comment_to_xml_conversion_01 {
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>comment_to_xml_conversion_01</Name><USR>c:@C@comment_to_xml_conversion_01</USR><Declaration>class comment_to_xml_conversion_01 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>comment_to_xml_conversion_01</Name><USR>c:@S@comment_to_xml_conversion_01</USR><Declaration>class comment_to_xml_conversion_01 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
 
   /// \param aaa Blah blah.
   comment_to_xml_conversion_01(int aaa);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: CXXConstructor=comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>comment_to_xml_conversion_01</Name><USR>c:@C@comment_to_xml_conversion_01@F@comment_to_xml_conversion_01#I#</USR><Declaration>comment_to_xml_conversion_01(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: CXXConstructor=comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>comment_to_xml_conversion_01</Name><USR>c:@S@comment_to_xml_conversion_01@F@comment_to_xml_conversion_01#I#</USR><Declaration>comment_to_xml_conversion_01(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
 
   /// Aaa.
   ~comment_to_xml_conversion_01();
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: CXXDestructor=~comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>~comment_to_xml_conversion_01</Name><USR>c:@C@comment_to_xml_conversion_01@F@~comment_to_xml_conversion_01#</USR><Declaration>~comment_to_xml_conversion_01()</Declaration><Abstract><Para> Aaa.</Para></Abstract></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: CXXDestructor=~comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>~comment_to_xml_conversion_01</Name><USR>c:@S@comment_to_xml_conversion_01@F@~comment_to_xml_conversion_01#</USR><Declaration>~comment_to_xml_conversion_01()</Declaration><Abstract><Para> Aaa.</Para></Abstract></Function>]
 
   /// \param aaa Blah blah.
   int comment_to_xml_conversion_02(int aaa);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: CXXMethod=comment_to_xml_conversion_02:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_02</Name><USR>c:@C@comment_to_xml_conversion_01@F@comment_to_xml_conversion_02#I#</USR><Declaration>int comment_to_xml_conversion_02(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: CXXMethod=comment_to_xml_conversion_02:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_02</Name><USR>c:@S@comment_to_xml_conversion_01@F@comment_to_xml_conversion_02#I#</USR><Declaration>int comment_to_xml_conversion_02(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
 
   /// \param aaa Blah blah.
   static int comment_to_xml_conversion_03(int aaa);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:14: CXXMethod=comment_to_xml_conversion_03:{{.*}} FullCommentAsXML=[<Function isClassMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="14"><Name>comment_to_xml_conversion_03</Name><USR>c:@C@comment_to_xml_conversion_01@F@comment_to_xml_conversion_03#I#S</USR><Declaration>static int comment_to_xml_conversion_03(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:14: CXXMethod=comment_to_xml_conversion_03:{{.*}} FullCommentAsXML=[<Function isClassMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="14"><Name>comment_to_xml_conversion_03</Name><USR>c:@S@comment_to_xml_conversion_01@F@comment_to_xml_conversion_03#I#S</USR><Declaration>static int comment_to_xml_conversion_03(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
 
   /// Aaa.
   int comment_to_xml_conversion_04;
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: FieldDecl=comment_to_xml_conversion_04:{{.*}} FullCommentAsXML=[<Variable file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_04</Name><USR>c:@C@comment_to_xml_conversion_01@FI@comment_to_xml_conversion_04</USR><Declaration>int comment_to_xml_conversion_04</Declaration><Abstract><Para> Aaa.</Para></Abstract></Variable>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: FieldDecl=comment_to_xml_conversion_04:{{.*}} FullCommentAsXML=[<Variable file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_04</Name><USR>c:@S@comment_to_xml_conversion_01@FI@comment_to_xml_conversion_04</USR><Declaration>int comment_to_xml_conversion_04</Declaration><Abstract><Para> Aaa.</Para></Abstract></Variable>]
 
   /// Aaa.
   static int comment_to_xml_conversion_05;
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:14: VarDecl=comment_to_xml_conversion_05:{{.*}} FullCommentAsXML=[<Variable file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="14"><Name>comment_to_xml_conversion_05</Name><USR>c:@C@comment_to_xml_conversion_01@comment_to_xml_conversion_05</USR><Declaration>static int comment_to_xml_conversion_05</Declaration><Abstract><Para> Aaa.</Para></Abstract></Variable>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:14: VarDecl=comment_to_xml_conversion_05:{{.*}} FullCommentAsXML=[<Variable file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="14"><Name>comment_to_xml_conversion_05</Name><USR>c:@S@comment_to_xml_conversion_01@comment_to_xml_conversion_05</USR><Declaration>static int comment_to_xml_conversion_05</Declaration><Abstract><Para> Aaa.</Para></Abstract></Variable>]
 
   /// \param aaa Blah blah.
   void operator()(int aaa);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:8: CXXMethod=operator():{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="8"><Name>operator()</Name><USR>c:@C@comment_to_xml_conversion_01@F@operator()#I#</USR><Declaration>void operator()(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:8: CXXMethod=operator():{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="8"><Name>operator()</Name><USR>c:@S@comment_to_xml_conversion_01@F@operator()#I#</USR><Declaration>void operator()(int aaa)</Declaration><Parameters><Parameter><Name>aaa</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah.</Para></Discussion></Parameter></Parameters></Function>]
 
   /// Aaa.
   operator bool();
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: CXXConversion=operator bool:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>operator bool</Name><USR>c:@C@comment_to_xml_conversion_01@F@operator bool#</USR><Declaration>operator bool()</Declaration><Abstract><Para> Aaa.</Para></Abstract></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: CXXConversion=operator bool:{{.*}} FullCommentAsXML=[<Function isInstanceMethod="1" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>operator bool</Name><USR>c:@S@comment_to_xml_conversion_01@F@operator bool#</USR><Declaration>operator bool()</Declaration><Abstract><Para> Aaa.</Para></Abstract></Function>]
 
   /// Aaa.
   typedef int comment_to_xml_conversion_06;
@@ -787,26 +787,26 @@
   /// Aaa.
   using comment_to_xml_conversion_07 = int;
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:9: TypeAliasDecl=comment_to_xml_conversion_07:{{.*}} FullCommentAsXML=[<Typedef file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="9"><Name>comment_to_xml_conversion_07</Name><USR>c:@C@comment_to_xml_conversion_01@comment_to_xml_conversion_07</USR><Declaration>using comment_to_xml_conversion_07 = int</Declaration><Abstract><Para> Aaa.</Para></Abstract></Typedef>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:9: TypeAliasDecl=comment_to_xml_conversion_07:{{.*}} FullCommentAsXML=[<Typedef file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="9"><Name>comment_to_xml_conversion_07</Name><USR>c:@S@comment_to_xml_conversion_01@comment_to_xml_conversion_07</USR><Declaration>using comment_to_xml_conversion_07 = int</Declaration><Abstract><Para> Aaa.</Para></Abstract></Typedef>]
 
   /// Aaa.
   template<typename T, typename U>
   class comment_to_xml_conversion_08 { };
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:9: ClassTemplate=comment_to_xml_conversion_08:{{.*}} FullCommentAsXML=[<Class templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="9"><Name>comment_to_xml_conversion_08</Name><USR>c:@C@comment_to_xml_conversion_01@CT&gt;2#T#T@comment_to_xml_conversion_08</USR><Declaration>template &lt;typename T, typename U&gt; class comment_to_xml_conversion_08 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:9: ClassTemplate=comment_to_xml_conversion_08:{{.*}} FullCommentAsXML=[<Class templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="9"><Name>comment_to_xml_conversion_08</Name><USR>c:@S@comment_to_xml_conversion_01@ST&gt;2#T#T@comment_to_xml_conversion_08</USR><Declaration>template &lt;typename T, typename U&gt; class comment_to_xml_conversion_08 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
 
   /// Aaa.
   template<typename T>
   using comment_to_xml_conversion_09 = comment_to_xml_conversion_08<T, int>;
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: UnexposedDecl=comment_to_xml_conversion_09:{{.*}} FullCommentAsXML=[<Typedef file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>comment_to_xml_conversion_09</Name><USR>c:@C@comment_to_xml_conversion_01@comment_to_xml_conversion_09</USR><Declaration>template &lt;typename T&gt;\nusing comment_to_xml_conversion_09 = comment_to_xml_conversion_08&lt;T, int&gt;</Declaration><Abstract><Para> Aaa.</Para></Abstract></Typedef>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:3: UnexposedDecl=comment_to_xml_conversion_09:{{.*}} FullCommentAsXML=[<Typedef file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="3"><Name>comment_to_xml_conversion_09</Name><USR>c:@S@comment_to_xml_conversion_01@comment_to_xml_conversion_09</USR><Declaration>template &lt;typename T&gt;\nusing comment_to_xml_conversion_09 = comment_to_xml_conversion_08&lt;T, int&gt;</Declaration><Abstract><Para> Aaa.</Para></Abstract></Typedef>]
 };
 
 /// Aaa.
 template<typename T, typename U>
 void comment_to_xml_conversion_10(T aaa, U bbb);
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=comment_to_xml_conversion_10:{{.*}} FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_xml_conversion_10</Name><USR>c:@FT@&gt;2#T#Tcomment_to_xml_conversion_10#t0.0#t0.1#</USR><Declaration>template &lt;typename T, typename U&gt;\nvoid comment_to_xml_conversion_10(T aaa, U bbb)</Declaration><Abstract><Para> Aaa.</Para></Abstract></Function>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionTemplate=comment_to_xml_conversion_10:{{.*}} FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_xml_conversion_10</Name><USR>c:@FT@&gt;2#T#Tcomment_to_xml_conversion_10#t0.0#t0.1#v#</USR><Declaration>template &lt;typename T, typename U&gt;\nvoid comment_to_xml_conversion_10(T aaa, U bbb)</Declaration><Abstract><Para> Aaa.</Para></Abstract></Function>]
 
 /// Aaa.
 template<>
@@ -818,19 +818,19 @@
 template<typename T, typename U>
 class comment_to_xml_conversion_11 { };
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: ClassTemplate=comment_to_xml_conversion_11:{{.*}} FullCommentAsXML=[<Class templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_11</Name><USR>c:@CT&gt;2#T#T@comment_to_xml_conversion_11</USR><Declaration>template &lt;typename T, typename U&gt; class comment_to_xml_conversion_11 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: ClassTemplate=comment_to_xml_conversion_11:{{.*}} FullCommentAsXML=[<Class templateKind="template" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_11</Name><USR>c:@ST&gt;2#T#T@comment_to_xml_conversion_11</USR><Declaration>template &lt;typename T, typename U&gt; class comment_to_xml_conversion_11 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
 
 /// Aaa.
 template<typename T>
 class comment_to_xml_conversion_11<T, int> { };
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: ClassTemplatePartialSpecialization=comment_to_xml_conversion_11:{{.*}} FullCommentAsXML=[<Class templateKind="partialSpecialization" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_11</Name><USR>c:@CP&gt;1#T@comment_to_xml_conversion_11&gt;#t0.0#I</USR><Declaration>class comment_to_xml_conversion_11 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: ClassTemplatePartialSpecialization=comment_to_xml_conversion_11:{{.*}} FullCommentAsXML=[<Class templateKind="partialSpecialization" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_11</Name><USR>c:@SP&gt;1#T@comment_to_xml_conversion_11&gt;#t0.0#I</USR><Declaration>class comment_to_xml_conversion_11 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
 
 /// Aaa.
 template<>
 class comment_to_xml_conversion_11<int, int> { };
 
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: ClassDecl=comment_to_xml_conversion_11:{{.*}} FullCommentAsXML=[<Class templateKind="specialization" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_11</Name><USR>c:@C@comment_to_xml_conversion_11&gt;#I#I</USR><Declaration>class comment_to_xml_conversion_11 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:7: ClassDecl=comment_to_xml_conversion_11:{{.*}} FullCommentAsXML=[<Class templateKind="specialization" file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-2]]" column="7"><Name>comment_to_xml_conversion_11</Name><USR>c:@S@comment_to_xml_conversion_11&gt;#I#I</USR><Declaration>class comment_to_xml_conversion_11 {}</Declaration><Abstract><Para> Aaa.</Para></Abstract></Class>]
 
 /// Aaa.
 int comment_to_xml_conversion_12;
@@ -902,7 +902,7 @@
 class BaseToSuper1_Base {};
 
 class BaseToSuper1_Derived : public BaseToSuper1_Base {};
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper1_Derived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper1_Base</Name><USR>c:@C@BaseToSuper1_Base</USR><Declaration>class BaseToSuper1_Derived : public BaseToSuper1_Base {}</Declaration><Abstract><Para> BaseToSuper1_Base</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper1_Derived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper1_Base</Name><USR>c:@S@BaseToSuper1_Base</USR><Declaration>class BaseToSuper1_Derived : public BaseToSuper1_Base {}</Declaration><Abstract><Para> BaseToSuper1_Base</Para></Abstract></Class>]
 
 
 /// BaseToSuper2_Base
@@ -910,10 +910,10 @@
 
 /// BaseToSuper2_Derived
 class BaseToSuper2_Derived : public BaseToSuper2_Base {};
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper2_Derived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper2_Derived</Name><USR>c:@C@BaseToSuper2_Derived</USR><Declaration>class BaseToSuper2_Derived : public BaseToSuper2_Base {}</Declaration><Abstract><Para> BaseToSuper2_Derived</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper2_Derived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper2_Derived</Name><USR>c:@S@BaseToSuper2_Derived</USR><Declaration>class BaseToSuper2_Derived : public BaseToSuper2_Base {}</Declaration><Abstract><Para> BaseToSuper2_Derived</Para></Abstract></Class>]
 
 class BaseToSuper2_MoreDerived : public BaseToSuper2_Derived {};
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper2_MoreDerived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper2_Derived</Name><USR>c:@C@BaseToSuper2_Derived</USR><Declaration>class BaseToSuper2_MoreDerived : public BaseToSuper2_Derived {}</Declaration><Abstract><Para> BaseToSuper2_Derived</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper2_MoreDerived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper2_Derived</Name><USR>c:@S@BaseToSuper2_Derived</USR><Declaration>class BaseToSuper2_MoreDerived : public BaseToSuper2_Derived {}</Declaration><Abstract><Para> BaseToSuper2_Derived</Para></Abstract></Class>]
 
 
 /// BaseToSuper3_Base
@@ -924,7 +924,7 @@
 class BaseToSuper3_DerivedB : public virtual BaseToSuper3_Base {};
 
 class BaseToSuper3_MoreDerived : public BaseToSuper3_DerivedA, public BaseToSuper3_DerivedB {};
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper3_MoreDerived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper3_Base</Name><USR>c:@C@BaseToSuper3_Base</USR><Declaration>class BaseToSuper3_MoreDerived : public BaseToSuper3_DerivedA,\n                                 public BaseToSuper3_DerivedB {}</Declaration><Abstract><Para> BaseToSuper3_Base</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper3_MoreDerived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper3_Base</Name><USR>c:@S@BaseToSuper3_Base</USR><Declaration>class BaseToSuper3_MoreDerived : public BaseToSuper3_DerivedA,\n                                 public BaseToSuper3_DerivedB {}</Declaration><Abstract><Para> BaseToSuper3_Base</Para></Abstract></Class>]
 
 
 // Check that we propagate comments only through public inheritance.
@@ -938,7 +938,7 @@
 class BaseToSuper4_DerivedB : public virtual BaseToSuper4_Base {};
 
 class BaseToSuper4_MoreDerived : BaseToSuper4_DerivedA, public BaseToSuper4_DerivedB {};
-// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper4_MoreDerived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper4_Base</Name><USR>c:@C@BaseToSuper4_Base</USR><Declaration>class BaseToSuper4_MoreDerived : BaseToSuper4_DerivedA,\n                                 public BaseToSuper4_DerivedB {}</Declaration><Abstract><Para> BaseToSuper4_Base</Para></Abstract></Class>]
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=BaseToSuper4_MoreDerived:{{.*}} FullCommentAsXML=[<Class file="{{[^"]+}}comment-to-html-xml-conversion.cpp" line="[[@LINE-1]]" column="7"><Name>BaseToSuper4_Base</Name><USR>c:@S@BaseToSuper4_Base</USR><Declaration>class BaseToSuper4_MoreDerived : BaseToSuper4_DerivedA,\n                                 public BaseToSuper4_DerivedB {}</Declaration><Abstract><Para> BaseToSuper4_Base</Para></Abstract></Class>]
 
 //===---
 // Check the representation of \todo in XML.
diff --git a/test/Index/complete-call.cpp b/test/Index/complete-call.cpp
new file mode 100644
index 0000000..9750bd6
--- /dev/null
+++ b/test/Index/complete-call.cpp
@@ -0,0 +1,805 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+void foo_1();
+void foo_2(int);
+void foo_2(void *);
+void foo_3(int, int);
+void foo_3(void *, void *);
+void foo_4(int, int);
+void foo_4(void *, int);
+void foo_5(int, int);
+void foo_5(int, void *);
+template<class T> void foo_6();
+template<class T> void foo_7(T);
+template<class T> void foo_8(T, T);
+template<class T> void foo_9(int, T);
+template<class T> void foo_9(void *, T);
+template<class T> void foo_10(T, int, int);
+template<class U> void foo_10(U, void *, void *);
+template<class T, class U> void foo_11(T, U);
+template<class T = int> void foo_12(T, T);
+template<class V>
+struct S {
+  void foo_1();
+  void foo_2(int);
+  void foo_2(void *);
+  void foo_3(int, int);
+  void foo_3(void *, void *);
+  void foo_4(int, int);
+  void foo_4(void *, int);
+  void foo_5(int, int);
+  void foo_5(int, void *);
+  template<class T> void foo_6();
+  template<class T> void foo_7(T);
+  template<class T> void foo_8(T, T);
+  template<class T> void foo_9(int, T);
+  template<class T> void foo_9(void *, T);
+  template<class T> void foo_10(T, int, int);
+  template<class U> void foo_10(U, void *, void *);
+  template<class T, class U> void foo_11(T, U);
+  template<class T = int> void foo_12(T, T);
+  template<class T> void foo_13(V, T, T);
+};
+
+int main() {
+  void *p = 0;
+  foo_1();
+  foo_2(42);
+  foo_3(42, 42);
+  foo_3(p, p);
+  foo_4(42, 42);
+  foo_4(p, 42);
+  foo_5(42, 42);
+  foo_6<int>();
+  foo_7(42);
+  foo_7<int>(42);
+  foo_8(42, 42);
+  foo_9(42, 42);
+  foo_9(p, 42);
+  foo_10(42, 42, 42);
+  foo_11(42, 42);
+  foo_11<int>(42, 42);
+  foo_11<int, void *>(42, p);
+  foo_12(p, p);
+
+  S<int> s;
+  s.foo_1();
+  s.foo_2(42);
+  s.foo_3(42, 42);
+  s.foo_3(p, p);
+  s.foo_4(42, 42);
+  s.foo_4(p, 42);
+  s.foo_5(42, 42);
+  s.foo_6<int>();
+  s.foo_7(42);
+  s.foo_7<int>(42);
+  s.foo_8(42, 42);
+  s.foo_9(42, 42);
+  s.foo_9(p, 42);
+  s.foo_10(42, 42, 42);
+  s.foo_11(42, 42);
+  s.foo_11<int>(42, 42);
+  s.foo_11<int, void *>(42, p);
+  s.foo_12(p, p);
+  s.foo_13(42, 42, 42);
+
+  foo_1(42,);
+  foo_2(42,);
+  foo_6<int>(42,);
+  foo_7(42,);
+  s.foo_1(42,);
+  s.foo_2(42,);
+  s.foo_6<int>(42,);
+  s.foo_7(42,);
+}
+
+// RUN: c-index-test -code-completion-at=%s:47:9 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OverloadCandidate:{ResultType void}{Text foo_1}{LeftParen (}{RightParen )} (1)
+// CHECK-CC1: Completion contexts:
+// CHECK-CC1-NEXT: Any type
+// CHECK-CC1-NEXT: Any value
+// CHECK-CC1-NEXT: Enum tag
+// CHECK-CC1-NEXT: Union tag
+// CHECK-CC1-NEXT: Struct tag
+// CHECK-CC1-NEXT: Class name
+// CHECK-CC1-NEXT: Nested name specifier
+// CHECK-CC1-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:48:9 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text foo_2}{LeftParen (}{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text foo_2}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC2: Completion contexts:
+// CHECK-CC2-NEXT: Any type
+// CHECK-CC2-NEXT: Any value
+// CHECK-CC2-NEXT: Enum tag
+// CHECK-CC2-NEXT: Union tag
+// CHECK-CC2-NEXT: Struct tag
+// CHECK-CC2-NEXT: Class name
+// CHECK-CC2-NEXT: Nested name specifier
+// CHECK-CC2-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:49:9 %s | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder void *}{RightParen )} (1)
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC3: Completion contexts:
+// CHECK-CC3-NEXT: Any type
+// CHECK-CC3-NEXT: Any value
+// CHECK-CC3-NEXT: Enum tag
+// CHECK-CC3-NEXT: Union tag
+// CHECK-CC3-NEXT: Struct tag
+// CHECK-CC3-NEXT: Class name
+// CHECK-CC3-NEXT: Nested name specifier
+// CHECK-CC3-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:49:12 %s | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC4: Completion contexts:
+// CHECK-CC4-NEXT: Any type
+// CHECK-CC4-NEXT: Any value
+// CHECK-CC4-NEXT: Enum tag
+// CHECK-CC4-NEXT: Union tag
+// CHECK-CC4-NEXT: Struct tag
+// CHECK-CC4-NEXT: Class name
+// CHECK-CC4-NEXT: Nested name specifier
+// CHECK-CC4-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:50:11 %s | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC5: Completion contexts:
+// CHECK-CC5-NEXT: Any type
+// CHECK-CC5-NEXT: Any value
+// CHECK-CC5-NEXT: Enum tag
+// CHECK-CC5-NEXT: Union tag
+// CHECK-CC5-NEXT: Struct tag
+// CHECK-CC5-NEXT: Class name
+// CHECK-CC5-NEXT: Nested name specifier
+// CHECK-CC5-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:51:12 %s | FileCheck -check-prefix=CHECK-CC6 %s
+// CHECK-CC6: OverloadCandidate:{ResultType void}{Text foo_4}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC6: Completion contexts:
+// CHECK-CC6-NEXT: Any type
+// CHECK-CC6-NEXT: Any value
+// CHECK-CC6-NEXT: Enum tag
+// CHECK-CC6-NEXT: Union tag
+// CHECK-CC6-NEXT: Struct tag
+// CHECK-CC6-NEXT: Class name
+// CHECK-CC6-NEXT: Nested name specifier
+// CHECK-CC6-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:52:11 %s | FileCheck -check-prefix=CHECK-CC7 %s
+// CHECK-CC7: OverloadCandidate:{ResultType void}{Text foo_4}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC7: Completion contexts:
+// CHECK-CC7-NEXT: Any type
+// CHECK-CC7-NEXT: Any value
+// CHECK-CC7-NEXT: Enum tag
+// CHECK-CC7-NEXT: Union tag
+// CHECK-CC7-NEXT: Struct tag
+// CHECK-CC7-NEXT: Class name
+// CHECK-CC7-NEXT: Nested name specifier
+// CHECK-CC7-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:53:12 %s | FileCheck -check-prefix=CHECK-CC8 %s
+// CHECK-CC8: OverloadCandidate:{ResultType void}{Text foo_5}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC8: OverloadCandidate:{ResultType void}{Text foo_5}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC8: Completion contexts:
+// CHECK-CC8-NEXT: Any type
+// CHECK-CC8-NEXT: Any value
+// CHECK-CC8-NEXT: Enum tag
+// CHECK-CC8-NEXT: Union tag
+// CHECK-CC8-NEXT: Struct tag
+// CHECK-CC8-NEXT: Class name
+// CHECK-CC8-NEXT: Nested name specifier
+// CHECK-CC8-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:54:14 %s | FileCheck -check-prefix=CHECK-CC9 %s
+// CHECK-CC9: OverloadCandidate:{ResultType void}{Text foo_6}{LeftParen (}{RightParen )} (1)
+// CHECK-CC9: Completion contexts:
+// CHECK-CC9-NEXT: Any type
+// CHECK-CC9-NEXT: Any value
+// CHECK-CC9-NEXT: Enum tag
+// CHECK-CC9-NEXT: Union tag
+// CHECK-CC9-NEXT: Struct tag
+// CHECK-CC9-NEXT: Class name
+// CHECK-CC9-NEXT: Nested name specifier
+// CHECK-CC9-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:55:9 %s | FileCheck -check-prefix=CHECK-CC10 %s
+// CHECK-CC10: OverloadCandidate:{ResultType void}{Text foo_7}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC10: Completion contexts:
+// CHECK-CC10-NEXT: Any type
+// CHECK-CC10-NEXT: Any value
+// CHECK-CC10-NEXT: Enum tag
+// CHECK-CC10-NEXT: Union tag
+// CHECK-CC10-NEXT: Struct tag
+// CHECK-CC10-NEXT: Class name
+// CHECK-CC10-NEXT: Nested name specifier
+// CHECK-CC10-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:56:14 %s | FileCheck -check-prefix=CHECK-CC11 %s
+// CHECK-CC11: OverloadCandidate:{ResultType void}{Text foo_7}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC11: Completion contexts:
+// CHECK-CC11-NEXT: Any type
+// CHECK-CC11-NEXT: Any value
+// CHECK-CC11-NEXT: Enum tag
+// CHECK-CC11-NEXT: Union tag
+// CHECK-CC11-NEXT: Struct tag
+// CHECK-CC11-NEXT: Class name
+// CHECK-CC11-NEXT: Nested name specifier
+// CHECK-CC11-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:57:12 %s | FileCheck -check-prefix=CHECK-CC12 %s
+// CHECK-CC12: OverloadCandidate:{ResultType void}{Text foo_8}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC12: Completion contexts:
+// CHECK-CC12-NEXT: Any type
+// CHECK-CC12-NEXT: Any value
+// CHECK-CC12-NEXT: Enum tag
+// CHECK-CC12-NEXT: Union tag
+// CHECK-CC12-NEXT: Struct tag
+// CHECK-CC12-NEXT: Class name
+// CHECK-CC12-NEXT: Nested name specifier
+// CHECK-CC12-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:58:12 %s | FileCheck -check-prefix=CHECK-CC13 %s
+// CHECK-CC13: OverloadCandidate:{ResultType void}{Text foo_9}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC13: Completion contexts:
+// CHECK-CC13-NEXT: Any type
+// CHECK-CC13-NEXT: Any value
+// CHECK-CC13-NEXT: Enum tag
+// CHECK-CC13-NEXT: Union tag
+// CHECK-CC13-NEXT: Struct tag
+// CHECK-CC13-NEXT: Class name
+// CHECK-CC13-NEXT: Nested name specifier
+// CHECK-CC13-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:59:11 %s | FileCheck -check-prefix=CHECK-CC14 %s
+// CHECK-CC14: OverloadCandidate:{ResultType void}{Text foo_9}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC14: Completion contexts:
+// CHECK-CC14-NEXT: Any type
+// CHECK-CC14-NEXT: Any value
+// CHECK-CC14-NEXT: Enum tag
+// CHECK-CC14-NEXT: Union tag
+// CHECK-CC14-NEXT: Struct tag
+// CHECK-CC14-NEXT: Class name
+// CHECK-CC14-NEXT: Nested name specifier
+// CHECK-CC14-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:60:10 %s | FileCheck -check-prefix=CHECK-CC15 %s
+// CHECK-CC15: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{CurrentParameter U}{Comma , }{Placeholder void *}{Comma , }{Placeholder void *}{RightParen )} (1)
+// CHECK-CC15: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{CurrentParameter T}{Comma , }{Placeholder int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC15: Completion contexts:
+// CHECK-CC15-NEXT: Any type
+// CHECK-CC15-NEXT: Any value
+// CHECK-CC15-NEXT: Enum tag
+// CHECK-CC15-NEXT: Union tag
+// CHECK-CC15-NEXT: Struct tag
+// CHECK-CC15-NEXT: Class name
+// CHECK-CC15-NEXT: Nested name specifier
+// CHECK-CC15-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:60:13 %s | FileCheck -check-prefix=CHECK-CC16 %s
+// CHECK-CC16: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter void *}{Comma , }{Placeholder void *}{RightParen )} (1)
+// CHECK-CC16: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC16: Completion contexts:
+// CHECK-CC16-NEXT: Any type
+// CHECK-CC16-NEXT: Any value
+// CHECK-CC16-NEXT: Enum tag
+// CHECK-CC16-NEXT: Union tag
+// CHECK-CC16-NEXT: Struct tag
+// CHECK-CC16-NEXT: Class name
+// CHECK-CC16-NEXT: Nested name specifier
+// CHECK-CC16-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:60:17 %s | FileCheck -check-prefix=CHECK-CC17 %s
+// CHECK-CC17: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{Placeholder int}{Comma , }{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC17: Completion contexts:
+// CHECK-CC17-NEXT: Any type
+// CHECK-CC17-NEXT: Any value
+// CHECK-CC17-NEXT: Enum tag
+// CHECK-CC17-NEXT: Union tag
+// CHECK-CC17-NEXT: Struct tag
+// CHECK-CC17-NEXT: Class name
+// CHECK-CC17-NEXT: Nested name specifier
+// CHECK-CC17-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:61:10 %s | FileCheck -check-prefix=CHECK-CC18 %s
+// CHECK-CC18: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{CurrentParameter T}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC18: Completion contexts:
+// CHECK-CC18-NEXT: Any type
+// CHECK-CC18-NEXT: Any value
+// CHECK-CC18-NEXT: Enum tag
+// CHECK-CC18-NEXT: Union tag
+// CHECK-CC18-NEXT: Struct tag
+// CHECK-CC18-NEXT: Class name
+// CHECK-CC18-NEXT: Nested name specifier
+// CHECK-CC18-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:61:13 %s | FileCheck -check-prefix=CHECK-CC19 %s
+// CHECK-CC19: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter U}{RightParen )} (1)
+// CHECK-CC19: Completion contexts:
+// CHECK-CC19-NEXT: Any type
+// CHECK-CC19-NEXT: Any value
+// CHECK-CC19-NEXT: Enum tag
+// CHECK-CC19-NEXT: Union tag
+// CHECK-CC19-NEXT: Struct tag
+// CHECK-CC19-NEXT: Class name
+// CHECK-CC19-NEXT: Nested name specifier
+// CHECK-CC19-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:62:15 %s | FileCheck -check-prefix=CHECK-CC20 %s
+// CHECK-CC20: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC20: Completion contexts:
+// CHECK-CC20-NEXT: Any type
+// CHECK-CC20-NEXT: Any value
+// CHECK-CC20-NEXT: Enum tag
+// CHECK-CC20-NEXT: Union tag
+// CHECK-CC20-NEXT: Struct tag
+// CHECK-CC20-NEXT: Class name
+// CHECK-CC20-NEXT: Nested name specifier
+// CHECK-CC20-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:62:18 %s | FileCheck -check-prefix=CHECK-CC21 %s
+// CHECK-CC21: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter U}{RightParen )} (1)
+// CHECK-CC21: Completion contexts:
+// CHECK-CC21-NEXT: Any type
+// CHECK-CC21-NEXT: Any value
+// CHECK-CC21-NEXT: Enum tag
+// CHECK-CC21-NEXT: Union tag
+// CHECK-CC21-NEXT: Struct tag
+// CHECK-CC21-NEXT: Class name
+// CHECK-CC21-NEXT: Nested name specifier
+// CHECK-CC21-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:63:26 %s | FileCheck -check-prefix=CHECK-CC22 %s
+// CHECK-CC22: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC22: Completion contexts:
+// CHECK-CC22-NEXT: Any type
+// CHECK-CC22-NEXT: Any value
+// CHECK-CC22-NEXT: Enum tag
+// CHECK-CC22-NEXT: Union tag
+// CHECK-CC22-NEXT: Struct tag
+// CHECK-CC22-NEXT: Class name
+// CHECK-CC22-NEXT: Nested name specifier
+// CHECK-CC22-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:64:10 %s | FileCheck -check-prefix=CHECK-CC23 %s
+// CHECK-CC23: OverloadCandidate:{ResultType void}{Text foo_12}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC23: Completion contexts:
+// CHECK-CC23-NEXT: Any type
+// CHECK-CC23-NEXT: Any value
+// CHECK-CC23-NEXT: Enum tag
+// CHECK-CC23-NEXT: Union tag
+// CHECK-CC23-NEXT: Struct tag
+// CHECK-CC23-NEXT: Class name
+// CHECK-CC23-NEXT: Nested name specifier
+// CHECK-CC23-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:64:12 %s | FileCheck -check-prefix=CHECK-CC24 %s
+// CHECK-CC24: OverloadCandidate:{ResultType void}{Text foo_12}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC24: Completion contexts:
+// CHECK-CC24-NEXT: Any type
+// CHECK-CC24-NEXT: Any value
+// CHECK-CC24-NEXT: Enum tag
+// CHECK-CC24-NEXT: Union tag
+// CHECK-CC24-NEXT: Struct tag
+// CHECK-CC24-NEXT: Class name
+// CHECK-CC24-NEXT: Nested name specifier
+// CHECK-CC24-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:67:11 %s | FileCheck -check-prefix=CHECK-CC25 %s
+// CHECK-CC25: OverloadCandidate:{ResultType void}{Text foo_1}{LeftParen (}{RightParen )} (1)
+// CHECK-CC25: Completion contexts:
+// CHECK-CC25-NEXT: Any type
+// CHECK-CC25-NEXT: Any value
+// CHECK-CC25-NEXT: Enum tag
+// CHECK-CC25-NEXT: Union tag
+// CHECK-CC25-NEXT: Struct tag
+// CHECK-CC25-NEXT: Class name
+// CHECK-CC25-NEXT: Nested name specifier
+// CHECK-CC25-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:68:11 %s | FileCheck -check-prefix=CHECK-CC26 %s
+// CHECK-CC26: OverloadCandidate:{ResultType void}{Text foo_2}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC26: OverloadCandidate:{ResultType void}{Text foo_2}{LeftParen (}{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC26: Completion contexts:
+// CHECK-CC26-NEXT: Any type
+// CHECK-CC26-NEXT: Any value
+// CHECK-CC26-NEXT: Enum tag
+// CHECK-CC26-NEXT: Union tag
+// CHECK-CC26-NEXT: Struct tag
+// CHECK-CC26-NEXT: Class name
+// CHECK-CC26-NEXT: Nested name specifier
+// CHECK-CC26-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:69:11 %s | FileCheck -check-prefix=CHECK-CC27 %s
+// CHECK-CC27: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC27: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder void *}{RightParen )} (1)
+// CHECK-CC27: Completion contexts:
+// CHECK-CC27-NEXT: Any type
+// CHECK-CC27-NEXT: Any value
+// CHECK-CC27-NEXT: Enum tag
+// CHECK-CC27-NEXT: Union tag
+// CHECK-CC27-NEXT: Struct tag
+// CHECK-CC27-NEXT: Class name
+// CHECK-CC27-NEXT: Nested name specifier
+// CHECK-CC27-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:69:14 %s | FileCheck -check-prefix=CHECK-CC28 %s
+// CHECK-CC28: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC28: Completion contexts:
+// CHECK-CC28-NEXT: Any type
+// CHECK-CC28-NEXT: Any value
+// CHECK-CC28-NEXT: Enum tag
+// CHECK-CC28-NEXT: Union tag
+// CHECK-CC28-NEXT: Struct tag
+// CHECK-CC28-NEXT: Class name
+// CHECK-CC28-NEXT: Nested name specifier
+// CHECK-CC28-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:70:13 %s | FileCheck -check-prefix=CHECK-CC29 %s
+// CHECK-CC29: OverloadCandidate:{ResultType void}{Text foo_3}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC29: Completion contexts:
+// CHECK-CC29-NEXT: Any type
+// CHECK-CC29-NEXT: Any value
+// CHECK-CC29-NEXT: Enum tag
+// CHECK-CC29-NEXT: Union tag
+// CHECK-CC29-NEXT: Struct tag
+// CHECK-CC29-NEXT: Class name
+// CHECK-CC29-NEXT: Nested name specifier
+// CHECK-CC29-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:71:14 %s | FileCheck -check-prefix=CHECK-CC30 %s
+// CHECK-CC30: OverloadCandidate:{ResultType void}{Text foo_4}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC30: Completion contexts:
+// CHECK-CC30-NEXT: Any type
+// CHECK-CC30-NEXT: Any value
+// CHECK-CC30-NEXT: Enum tag
+// CHECK-CC30-NEXT: Union tag
+// CHECK-CC30-NEXT: Struct tag
+// CHECK-CC30-NEXT: Class name
+// CHECK-CC30-NEXT: Nested name specifier
+// CHECK-CC30-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:72:13 %s | FileCheck -check-prefix=CHECK-CC31 %s
+// CHECK-CC31: OverloadCandidate:{ResultType void}{Text foo_4}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC31: Completion contexts:
+// CHECK-CC31-NEXT: Any type
+// CHECK-CC31-NEXT: Any value
+// CHECK-CC31-NEXT: Enum tag
+// CHECK-CC31-NEXT: Union tag
+// CHECK-CC31-NEXT: Struct tag
+// CHECK-CC31-NEXT: Class name
+// CHECK-CC31-NEXT: Nested name specifier
+// CHECK-CC31-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:73:14 %s | FileCheck -check-prefix=CHECK-CC32 %s
+// CHECK-CC32: OverloadCandidate:{ResultType void}{Text foo_5}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC32: OverloadCandidate:{ResultType void}{Text foo_5}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC32: Completion contexts:
+// CHECK-CC32-NEXT: Any type
+// CHECK-CC32-NEXT: Any value
+// CHECK-CC32-NEXT: Enum tag
+// CHECK-CC32-NEXT: Union tag
+// CHECK-CC32-NEXT: Struct tag
+// CHECK-CC32-NEXT: Class name
+// CHECK-CC32-NEXT: Nested name specifier
+// CHECK-CC32-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:74:16 %s | FileCheck -check-prefix=CHECK-CC33 %s
+// CHECK-CC33: OverloadCandidate:{ResultType void}{Text foo_6}{LeftParen (}{RightParen )} (1)
+// CHECK-CC33: Completion contexts:
+// CHECK-CC33-NEXT: Any type
+// CHECK-CC33-NEXT: Any value
+// CHECK-CC33-NEXT: Enum tag
+// CHECK-CC33-NEXT: Union tag
+// CHECK-CC33-NEXT: Struct tag
+// CHECK-CC33-NEXT: Class name
+// CHECK-CC33-NEXT: Nested name specifier
+// CHECK-CC33-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:75:11 %s | FileCheck -check-prefix=CHECK-CC34 %s
+// CHECK-CC34: OverloadCandidate:{ResultType void}{Text foo_7}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC34: Completion contexts:
+// CHECK-CC34-NEXT: Any type
+// CHECK-CC34-NEXT: Any value
+// CHECK-CC34-NEXT: Enum tag
+// CHECK-CC34-NEXT: Union tag
+// CHECK-CC34-NEXT: Struct tag
+// CHECK-CC34-NEXT: Class name
+// CHECK-CC34-NEXT: Nested name specifier
+// CHECK-CC34-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:76:16 %s | FileCheck -check-prefix=CHECK-CC35 %s
+// CHECK-CC35: OverloadCandidate:{ResultType void}{Text foo_7}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC35: Completion contexts:
+// CHECK-CC35-NEXT: Any type
+// CHECK-CC35-NEXT: Any value
+// CHECK-CC35-NEXT: Enum tag
+// CHECK-CC35-NEXT: Union tag
+// CHECK-CC35-NEXT: Struct tag
+// CHECK-CC35-NEXT: Class name
+// CHECK-CC35-NEXT: Nested name specifier
+// CHECK-CC35-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:77:14 %s | FileCheck -check-prefix=CHECK-CC36 %s
+// CHECK-CC36: OverloadCandidate:{ResultType void}{Text foo_8}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC36: Completion contexts:
+// CHECK-CC36-NEXT: Any type
+// CHECK-CC36-NEXT: Any value
+// CHECK-CC36-NEXT: Enum tag
+// CHECK-CC36-NEXT: Union tag
+// CHECK-CC36-NEXT: Struct tag
+// CHECK-CC36-NEXT: Class name
+// CHECK-CC36-NEXT: Nested name specifier
+// CHECK-CC36-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:78:14 %s | FileCheck -check-prefix=CHECK-CC37 %s
+// CHECK-CC37: OverloadCandidate:{ResultType void}{Text foo_9}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC37: Completion contexts:
+// CHECK-CC37-NEXT: Any type
+// CHECK-CC37-NEXT: Any value
+// CHECK-CC37-NEXT: Enum tag
+// CHECK-CC37-NEXT: Union tag
+// CHECK-CC37-NEXT: Struct tag
+// CHECK-CC37-NEXT: Class name
+// CHECK-CC37-NEXT: Nested name specifier
+// CHECK-CC37-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:79:13 %s | FileCheck -check-prefix=CHECK-CC38 %s
+// CHECK-CC38: OverloadCandidate:{ResultType void}{Text foo_9}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC38: Completion contexts:
+// CHECK-CC38-NEXT: Any type
+// CHECK-CC38-NEXT: Any value
+// CHECK-CC38-NEXT: Enum tag
+// CHECK-CC38-NEXT: Union tag
+// CHECK-CC38-NEXT: Struct tag
+// CHECK-CC38-NEXT: Class name
+// CHECK-CC38-NEXT: Nested name specifier
+// CHECK-CC38-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:80:12 %s | FileCheck -check-prefix=CHECK-CC39 %s
+// CHECK-CC39: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{CurrentParameter T}{Comma , }{Placeholder int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC39: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{CurrentParameter U}{Comma , }{Placeholder void *}{Comma , }{Placeholder void *}{RightParen )} (1)
+// CHECK-CC39: Completion contexts:
+// CHECK-CC39-NEXT: Any type
+// CHECK-CC39-NEXT: Any value
+// CHECK-CC39-NEXT: Enum tag
+// CHECK-CC39-NEXT: Union tag
+// CHECK-CC39-NEXT: Struct tag
+// CHECK-CC39-NEXT: Class name
+// CHECK-CC39-NEXT: Nested name specifier
+// CHECK-CC39-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:80:15 %s | FileCheck -check-prefix=CHECK-CC40 %s
+// CHECK-CC40: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC40: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter void *}{Comma , }{Placeholder void *}{RightParen )} (1)
+// CHECK-CC40: Completion contexts:
+// CHECK-CC40-NEXT: Any type
+// CHECK-CC40-NEXT: Any value
+// CHECK-CC40-NEXT: Enum tag
+// CHECK-CC40-NEXT: Union tag
+// CHECK-CC40-NEXT: Struct tag
+// CHECK-CC40-NEXT: Class name
+// CHECK-CC40-NEXT: Nested name specifier
+// CHECK-CC40-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:80:19 %s | FileCheck -check-prefix=CHECK-CC41 %s
+// CHECK-CC41: OverloadCandidate:{ResultType void}{Text foo_10}{LeftParen (}{Placeholder int}{Comma , }{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC41: Completion contexts:
+// CHECK-CC41-NEXT: Any type
+// CHECK-CC41-NEXT: Any value
+// CHECK-CC41-NEXT: Enum tag
+// CHECK-CC41-NEXT: Union tag
+// CHECK-CC41-NEXT: Struct tag
+// CHECK-CC41-NEXT: Class name
+// CHECK-CC41-NEXT: Nested name specifier
+// CHECK-CC41-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:81:12 %s | FileCheck -check-prefix=CHECK-CC42 %s
+// CHECK-CC42: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{CurrentParameter T}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC42: Completion contexts:
+// CHECK-CC42-NEXT: Any type
+// CHECK-CC42-NEXT: Any value
+// CHECK-CC42-NEXT: Enum tag
+// CHECK-CC42-NEXT: Union tag
+// CHECK-CC42-NEXT: Struct tag
+// CHECK-CC42-NEXT: Class name
+// CHECK-CC42-NEXT: Nested name specifier
+// CHECK-CC42-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:81:15 %s | FileCheck -check-prefix=CHECK-CC43 %s
+// CHECK-CC43: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter U}{RightParen )} (1)
+// CHECK-CC43: Completion contexts:
+// CHECK-CC43-NEXT: Any type
+// CHECK-CC43-NEXT: Any value
+// CHECK-CC43-NEXT: Enum tag
+// CHECK-CC43-NEXT: Union tag
+// CHECK-CC43-NEXT: Struct tag
+// CHECK-CC43-NEXT: Class name
+// CHECK-CC43-NEXT: Nested name specifier
+// CHECK-CC43-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:82:17 %s | FileCheck -check-prefix=CHECK-CC44 %s
+// CHECK-CC44: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC44: Completion contexts:
+// CHECK-CC44-NEXT: Any type
+// CHECK-CC44-NEXT: Any value
+// CHECK-CC44-NEXT: Enum tag
+// CHECK-CC44-NEXT: Union tag
+// CHECK-CC44-NEXT: Struct tag
+// CHECK-CC44-NEXT: Class name
+// CHECK-CC44-NEXT: Nested name specifier
+// CHECK-CC44-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:82:20 %s | FileCheck -check-prefix=CHECK-CC45 %s
+// CHECK-CC45: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter U}{RightParen )} (1)
+// CHECK-CC45: Completion contexts:
+// CHECK-CC45-NEXT: Any type
+// CHECK-CC45-NEXT: Any value
+// CHECK-CC45-NEXT: Enum tag
+// CHECK-CC45-NEXT: Union tag
+// CHECK-CC45-NEXT: Struct tag
+// CHECK-CC45-NEXT: Class name
+// CHECK-CC45-NEXT: Nested name specifier
+// CHECK-CC45-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:83:28 %s | FileCheck -check-prefix=CHECK-CC46 %s
+// CHECK-CC46: OverloadCandidate:{ResultType void}{Text foo_11}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC46: Completion contexts:
+// CHECK-CC46-NEXT: Any type
+// CHECK-CC46-NEXT: Any value
+// CHECK-CC46-NEXT: Enum tag
+// CHECK-CC46-NEXT: Union tag
+// CHECK-CC46-NEXT: Struct tag
+// CHECK-CC46-NEXT: Class name
+// CHECK-CC46-NEXT: Nested name specifier
+// CHECK-CC46-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:84:12 %s | FileCheck -check-prefix=CHECK-CC47 %s
+// CHECK-CC47: OverloadCandidate:{ResultType void}{Text foo_12}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder int}{RightParen )} (1)
+// CHECK-CC47: Completion contexts:
+// CHECK-CC47-NEXT: Any type
+// CHECK-CC47-NEXT: Any value
+// CHECK-CC47-NEXT: Enum tag
+// CHECK-CC47-NEXT: Union tag
+// CHECK-CC47-NEXT: Struct tag
+// CHECK-CC47-NEXT: Class name
+// CHECK-CC47-NEXT: Nested name specifier
+// CHECK-CC47-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:84:14 %s | FileCheck -check-prefix=CHECK-CC48 %s
+// CHECK-CC48: OverloadCandidate:{ResultType void}{Text foo_12}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter void *}{RightParen )} (1)
+// CHECK-CC48: Completion contexts:
+// CHECK-CC48-NEXT: Any type
+// CHECK-CC48-NEXT: Any value
+// CHECK-CC48-NEXT: Enum tag
+// CHECK-CC48-NEXT: Union tag
+// CHECK-CC48-NEXT: Struct tag
+// CHECK-CC48-NEXT: Class name
+// CHECK-CC48-NEXT: Nested name specifier
+// CHECK-CC48-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:85:12 %s | FileCheck -check-prefix=CHECK-CC49 %s
+// CHECK-CC49: OverloadCandidate:{ResultType void}{Text foo_13}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC49: Completion contexts:
+// CHECK-CC49-NEXT: Any type
+// CHECK-CC49-NEXT: Any value
+// CHECK-CC49-NEXT: Enum tag
+// CHECK-CC49-NEXT: Union tag
+// CHECK-CC49-NEXT: Struct tag
+// CHECK-CC49-NEXT: Class name
+// CHECK-CC49-NEXT: Nested name specifier
+// CHECK-CC49-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:85:15 %s | FileCheck -check-prefix=CHECK-CC50 %s
+// CHECK-CC50: OverloadCandidate:{ResultType void}{Text foo_13}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC50: Completion contexts:
+// CHECK-CC50-NEXT: Any type
+// CHECK-CC50-NEXT: Any value
+// CHECK-CC50-NEXT: Enum tag
+// CHECK-CC50-NEXT: Union tag
+// CHECK-CC50-NEXT: Struct tag
+// CHECK-CC50-NEXT: Class name
+// CHECK-CC50-NEXT: Nested name specifier
+// CHECK-CC50-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:85:19 %s | FileCheck -check-prefix=CHECK-CC51 %s
+// CHECK-CC51: OverloadCandidate:{ResultType void}{Text foo_13}{LeftParen (}{Placeholder int}{Comma , }{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC51: Completion contexts:
+// CHECK-CC51-NEXT: Any type
+// CHECK-CC51-NEXT: Any value
+// CHECK-CC51-NEXT: Enum tag
+// CHECK-CC51-NEXT: Union tag
+// CHECK-CC51-NEXT: Struct tag
+// CHECK-CC51-NEXT: Class name
+// CHECK-CC51-NEXT: Nested name specifier
+// CHECK-CC51-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:87:12 %s | FileCheck -check-prefix=CHECK-CC52 %s
+// CHECK-CC52: Completion contexts:
+// CHECK-CC52-NEXT: Any type
+// CHECK-CC52-NEXT: Any value
+// CHECK-CC52-NEXT: Enum tag
+// CHECK-CC52-NEXT: Union tag
+// CHECK-CC52-NEXT: Struct tag
+// CHECK-CC52-NEXT: Class name
+// CHECK-CC52-NEXT: Nested name specifier
+// CHECK-CC52-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:88:12 %s | FileCheck -check-prefix=CHECK-CC53 %s
+// CHECK-CC53: Completion contexts:
+// CHECK-CC53-NEXT: Any type
+// CHECK-CC53-NEXT: Any value
+// CHECK-CC53-NEXT: Enum tag
+// CHECK-CC53-NEXT: Union tag
+// CHECK-CC53-NEXT: Struct tag
+// CHECK-CC53-NEXT: Class name
+// CHECK-CC53-NEXT: Nested name specifier
+// CHECK-CC53-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:89:17 %s | FileCheck -check-prefix=CHECK-CC54 %s
+// CHECK-CC54: Completion contexts:
+// CHECK-CC54-NEXT: Any type
+// CHECK-CC54-NEXT: Any value
+// CHECK-CC54-NEXT: Enum tag
+// CHECK-CC54-NEXT: Union tag
+// CHECK-CC54-NEXT: Struct tag
+// CHECK-CC54-NEXT: Class name
+// CHECK-CC54-NEXT: Nested name specifier
+// CHECK-CC54-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:90:12 %s | FileCheck -check-prefix=CHECK-CC55 %s
+// CHECK-CC55: Completion contexts:
+// CHECK-CC55-NEXT: Any type
+// CHECK-CC55-NEXT: Any value
+// CHECK-CC55-NEXT: Enum tag
+// CHECK-CC55-NEXT: Union tag
+// CHECK-CC55-NEXT: Struct tag
+// CHECK-CC55-NEXT: Class name
+// CHECK-CC55-NEXT: Nested name specifier
+// CHECK-CC55-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:91:14 %s | FileCheck -check-prefix=CHECK-CC56 %s
+// CHECK-CC56: Completion contexts:
+// CHECK-CC56-NEXT: Any type
+// CHECK-CC56-NEXT: Any value
+// CHECK-CC56-NEXT: Enum tag
+// CHECK-CC56-NEXT: Union tag
+// CHECK-CC56-NEXT: Struct tag
+// CHECK-CC56-NEXT: Class name
+// CHECK-CC56-NEXT: Nested name specifier
+// CHECK-CC56-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:92:14 %s | FileCheck -check-prefix=CHECK-CC57 %s
+// CHECK-CC57: Completion contexts:
+// CHECK-CC57-NEXT: Any type
+// CHECK-CC57-NEXT: Any value
+// CHECK-CC57-NEXT: Enum tag
+// CHECK-CC57-NEXT: Union tag
+// CHECK-CC57-NEXT: Struct tag
+// CHECK-CC57-NEXT: Class name
+// CHECK-CC57-NEXT: Nested name specifier
+// CHECK-CC57-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:93:19 %s | FileCheck -check-prefix=CHECK-CC58 %s
+// CHECK-CC58: Completion contexts:
+// CHECK-CC58-NEXT: Any type
+// CHECK-CC58-NEXT: Any value
+// CHECK-CC58-NEXT: Enum tag
+// CHECK-CC58-NEXT: Union tag
+// CHECK-CC58-NEXT: Struct tag
+// CHECK-CC58-NEXT: Class name
+// CHECK-CC58-NEXT: Nested name specifier
+// CHECK-CC58-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:94:14 %s | FileCheck -check-prefix=CHECK-CC59 %s
+// CHECK-CC59: Completion contexts:
+// CHECK-CC59-NEXT: Any type
+// CHECK-CC59-NEXT: Any value
+// CHECK-CC59-NEXT: Enum tag
+// CHECK-CC59-NEXT: Union tag
+// CHECK-CC59-NEXT: Struct tag
+// CHECK-CC59-NEXT: Class name
+// CHECK-CC59-NEXT: Nested name specifier
+// CHECK-CC59-NEXT: Objective-C interface
diff --git a/test/Index/complete-constructor-params.cpp b/test/Index/complete-constructor-params.cpp
new file mode 100644
index 0000000..e5c01df
--- /dev/null
+++ b/test/Index/complete-constructor-params.cpp
@@ -0,0 +1,126 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+template<class T>
+struct S {
+  template<class U>
+  S(T, U, U) {}
+};
+
+int main() {
+  S<int>(42, 42, 42);
+  S<int>(42, 42, 42);
+  S<int> s(42, 42, 42);
+
+  S<int>(42, 42, 42,);
+  S<int> z(42, 42, 42,);
+}
+
+// RUN: c-index-test -code-completion-at=%s:11:10 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter const S<int> &}{RightParen )} (1)
+// CHECK-CC1: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder U}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC1: Completion contexts:
+// CHECK-CC1-NEXT: Any type
+// CHECK-CC1-NEXT: Any value
+// CHECK-CC1-NEXT: Enum tag
+// CHECK-CC1-NEXT: Union tag
+// CHECK-CC1-NEXT: Struct tag
+// CHECK-CC1-NEXT: Class name
+// CHECK-CC1-NEXT: Nested name specifier
+// CHECK-CC1-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:12:10 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter const S<int> &}{RightParen )} (1)
+// CHECK-CC2: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder U}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC2: Completion contexts:
+// CHECK-CC2-NEXT: Any type
+// CHECK-CC2-NEXT: Any value
+// CHECK-CC2-NEXT: Enum tag
+// CHECK-CC2-NEXT: Union tag
+// CHECK-CC2-NEXT: Struct tag
+// CHECK-CC2-NEXT: Class name
+// CHECK-CC2-NEXT: Nested name specifier
+// CHECK-CC2-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:12:13 %s | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OverloadCandidate:{Text S}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter U}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC3: Completion contexts:
+// CHECK-CC3-NEXT: Any type
+// CHECK-CC3-NEXT: Any value
+// CHECK-CC3-NEXT: Enum tag
+// CHECK-CC3-NEXT: Union tag
+// CHECK-CC3-NEXT: Struct tag
+// CHECK-CC3-NEXT: Class name
+// CHECK-CC3-NEXT: Nested name specifier
+// CHECK-CC3-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:12:17 %s | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OverloadCandidate:{Text S}{LeftParen (}{Placeholder int}{Comma , }{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC4: Completion contexts:
+// CHECK-CC4-NEXT: Any type
+// CHECK-CC4-NEXT: Any value
+// CHECK-CC4-NEXT: Enum tag
+// CHECK-CC4-NEXT: Union tag
+// CHECK-CC4-NEXT: Struct tag
+// CHECK-CC4-NEXT: Class name
+// CHECK-CC4-NEXT: Nested name specifier
+// CHECK-CC4-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:13:12 %s | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter const S<int> &}{RightParen )} (1)
+// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder U}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC5: Completion contexts:
+// CHECK-CC5-NEXT: Any type
+// CHECK-CC5-NEXT: Any value
+// CHECK-CC5-NEXT: Enum tag
+// CHECK-CC5-NEXT: Union tag
+// CHECK-CC5-NEXT: Struct tag
+// CHECK-CC5-NEXT: Class name
+// CHECK-CC5-NEXT: Nested name specifier
+// CHECK-CC5-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:13:15 %s | FileCheck -check-prefix=CHECK-CC6 %s
+// CHECK-CC6: OverloadCandidate:{Text S}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter U}{Comma , }{Placeholder U}{RightParen )} (1)
+// CHECK-CC6: Completion contexts:
+// CHECK-CC6-NEXT: Any type
+// CHECK-CC6-NEXT: Any value
+// CHECK-CC6-NEXT: Enum tag
+// CHECK-CC6-NEXT: Union tag
+// CHECK-CC6-NEXT: Struct tag
+// CHECK-CC6-NEXT: Class name
+// CHECK-CC6-NEXT: Nested name specifier
+// CHECK-CC6-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:13:19 %s | FileCheck -check-prefix=CHECK-CC7 %s
+// CHECK-CC7: OverloadCandidate:{Text S}{LeftParen (}{Placeholder int}{Comma , }{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC7: Completion contexts:
+// CHECK-CC7-NEXT: Any type
+// CHECK-CC7-NEXT: Any value
+// CHECK-CC7-NEXT: Enum tag
+// CHECK-CC7-NEXT: Union tag
+// CHECK-CC7-NEXT: Struct tag
+// CHECK-CC7-NEXT: Class name
+// CHECK-CC7-NEXT: Nested name specifier
+// CHECK-CC7-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:15:21 %s | FileCheck -check-prefix=CHECK-CC8 %s
+// CHECK-CC8: Completion contexts:
+// CHECK-CC8-NEXT: Any type
+// CHECK-CC8-NEXT: Any value
+// CHECK-CC8-NEXT: Enum tag
+// CHECK-CC8-NEXT: Union tag
+// CHECK-CC8-NEXT: Struct tag
+// CHECK-CC8-NEXT: Class name
+// CHECK-CC8-NEXT: Nested name specifier
+// CHECK-CC8-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:16:23 %s | FileCheck -check-prefix=CHECK-CC9 %s
+// CHECK-CC9: Completion contexts:
+// CHECK-CC9-NEXT: Any type
+// CHECK-CC9-NEXT: Any value
+// CHECK-CC9-NEXT: Enum tag
+// CHECK-CC9-NEXT: Union tag
+// CHECK-CC9-NEXT: Struct tag
+// CHECK-CC9-NEXT: Class name
+// CHECK-CC9-NEXT: Nested name specifier
+// CHECK-CC9-NEXT: Objective-C interface
diff --git a/test/Index/complete-functor-call.cpp b/test/Index/complete-functor-call.cpp
new file mode 100644
index 0000000..b6aed7e
--- /dev/null
+++ b/test/Index/complete-functor-call.cpp
@@ -0,0 +1,191 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+template<class V>
+struct S {
+  void operator()(int) const {}
+  template<class T> void operator()(T) const {}
+  template<class T> void operator()(V, T, T) const {}
+  template<class T> const S<T> *operator()(const S<T> &s) const { return &s; }
+};
+
+void foo(S<void *> &s) { s(42); }
+
+int main() {
+  S<void *> s;
+  s(42);
+  s(s);
+  s(0, s, s);
+  (*S<void *>()(S<int>()))(42, 42, 42);
+
+  s(42,);
+  s(s,);
+  s(0, 42, 42,);
+}
+
+// RUN: c-index-test -code-completion-at=%s:16:5 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC1: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC1: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC1: Completion contexts:
+// CHECK-CC1-NEXT: Any type
+// CHECK-CC1-NEXT: Any value
+// CHECK-CC1-NEXT: Enum tag
+// CHECK-CC1-NEXT: Union tag
+// CHECK-CC1-NEXT: Struct tag
+// CHECK-CC1-NEXT: Class name
+// CHECK-CC1-NEXT: Nested name specifier
+// CHECK-CC1-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:17:5 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC2: Completion contexts:
+// CHECK-CC2-NEXT: Any type
+// CHECK-CC2-NEXT: Any value
+// CHECK-CC2-NEXT: Enum tag
+// CHECK-CC2-NEXT: Union tag
+// CHECK-CC2-NEXT: Struct tag
+// CHECK-CC2-NEXT: Class name
+// CHECK-CC2-NEXT: Nested name specifier
+// CHECK-CC2-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:18:5 %s | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC3: Completion contexts:
+// CHECK-CC3-NEXT: Any type
+// CHECK-CC3-NEXT: Any value
+// CHECK-CC3-NEXT: Enum tag
+// CHECK-CC3-NEXT: Union tag
+// CHECK-CC3-NEXT: Struct tag
+// CHECK-CC3-NEXT: Class name
+// CHECK-CC3-NEXT: Nested name specifier
+// CHECK-CC3-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:18:7 %s | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{Placeholder void *}{Comma , }{CurrentParameter T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC4: Completion contexts:
+// CHECK-CC4-NEXT: Any type
+// CHECK-CC4-NEXT: Any value
+// CHECK-CC4-NEXT: Enum tag
+// CHECK-CC4-NEXT: Union tag
+// CHECK-CC4-NEXT: Struct tag
+// CHECK-CC4-NEXT: Class name
+// CHECK-CC4-NEXT: Nested name specifier
+// CHECK-CC4-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:18:10 %s | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{Placeholder void *}{Comma , }{Placeholder S<void *>}{Comma , }{CurrentParameter S<void *>}{RightParen )} (1)
+// CHECK-CC5: Completion contexts:
+// CHECK-CC5-NEXT: Any type
+// CHECK-CC5-NEXT: Any value
+// CHECK-CC5-NEXT: Enum tag
+// CHECK-CC5-NEXT: Union tag
+// CHECK-CC5-NEXT: Struct tag
+// CHECK-CC5-NEXT: Class name
+// CHECK-CC5-NEXT: Nested name specifier
+// CHECK-CC5-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:19:17 %s | FileCheck -check-prefix=CHECK-CC6 %s
+// CHECK-CC6: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC6: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC6: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC6: OverloadCandidate:{ResultType const S<T> *}{Text operator()}{LeftParen (}{CurrentParameter const S<T> &s}{RightParen )} (1)
+// CHECK-CC6: Completion contexts:
+// CHECK-CC6-NEXT: Any type
+// CHECK-CC6-NEXT: Any value
+// CHECK-CC6-NEXT: Enum tag
+// CHECK-CC6-NEXT: Union tag
+// CHECK-CC6-NEXT: Struct tag
+// CHECK-CC6-NEXT: Class name
+// CHECK-CC6-NEXT: Nested name specifier
+// CHECK-CC6-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:19:28 %s | FileCheck -check-prefix=CHECK-CC7 %s
+// CHECK-CC7: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC7: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC7: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC7: OverloadCandidate:{ResultType const S<T> *}{Text operator()}{LeftParen (}{CurrentParameter const S<T> &s}{RightParen )} (1)
+// CHECK-CC7: Completion contexts:
+// CHECK-CC7-NEXT: Any type
+// CHECK-CC7-NEXT: Any value
+// CHECK-CC7-NEXT: Enum tag
+// CHECK-CC7-NEXT: Union tag
+// CHECK-CC7-NEXT: Struct tag
+// CHECK-CC7-NEXT: Class name
+// CHECK-CC7-NEXT: Nested name specifier
+// CHECK-CC7-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:19:31 %s | FileCheck -check-prefix=CHECK-CC8 %s
+// CHECK-CC8: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{Placeholder int}{Comma , }{CurrentParameter T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC8: Completion contexts:
+// CHECK-CC8-NEXT: Any type
+// CHECK-CC8-NEXT: Any value
+// CHECK-CC8-NEXT: Enum tag
+// CHECK-CC8-NEXT: Union tag
+// CHECK-CC8-NEXT: Struct tag
+// CHECK-CC8-NEXT: Class name
+// CHECK-CC8-NEXT: Nested name specifier
+// CHECK-CC8-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:19:35 %s | FileCheck -check-prefix=CHECK-CC9 %s
+// CHECK-CC9: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{Placeholder int}{Comma , }{Placeholder int}{Comma , }{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC9: Completion contexts:
+// CHECK-CC9-NEXT: Any type
+// CHECK-CC9-NEXT: Any value
+// CHECK-CC9-NEXT: Enum tag
+// CHECK-CC9-NEXT: Union tag
+// CHECK-CC9-NEXT: Struct tag
+// CHECK-CC9-NEXT: Class name
+// CHECK-CC9-NEXT: Nested name specifier
+// CHECK-CC9-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:21:8 %s | FileCheck -check-prefix=CHECK-CC10 %s
+// CHECK-CC10: Completion contexts:
+// CHECK-CC10-NEXT: Any type
+// CHECK-CC10-NEXT: Any value
+// CHECK-CC10-NEXT: Enum tag
+// CHECK-CC10-NEXT: Union tag
+// CHECK-CC10-NEXT: Struct tag
+// CHECK-CC10-NEXT: Class name
+// CHECK-CC10-NEXT: Nested name specifier
+// CHECK-CC10-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:22:7 %s | FileCheck -check-prefix=CHECK-CC11 %s
+// CHECK-CC11: Completion contexts:
+// CHECK-CC11-NEXT: Any type
+// CHECK-CC11-NEXT: Any value
+// CHECK-CC11-NEXT: Enum tag
+// CHECK-CC11-NEXT: Union tag
+// CHECK-CC11-NEXT: Struct tag
+// CHECK-CC11-NEXT: Class name
+// CHECK-CC11-NEXT: Nested name specifier
+// CHECK-CC11-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:23:15 %s | FileCheck -check-prefix=CHECK-CC12 %s
+// CHECK-CC12: Completion contexts:
+// CHECK-CC12-NEXT: Any type
+// CHECK-CC12-NEXT: Any value
+// CHECK-CC12-NEXT: Enum tag
+// CHECK-CC12-NEXT: Union tag
+// CHECK-CC12-NEXT: Struct tag
+// CHECK-CC12-NEXT: Class name
+// CHECK-CC12-NEXT: Nested name specifier
+// CHECK-CC12-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:12:28 %s | FileCheck -check-prefix=CHECK-CC13 %s
+// CHECK-CC13: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC13: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter T}{RightParen )} (1)
+// CHECK-CC13: OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter void *}{Comma , }{Placeholder T}{Comma , }{Placeholder T}{RightParen )} (1)
+// CHECK-CC13: Completion contexts:
+// CHECK-CC13-NEXT: Any type
+// CHECK-CC13-NEXT: Any value
+// CHECK-CC13-NEXT: Enum tag
+// CHECK-CC13-NEXT: Union tag
+// CHECK-CC13-NEXT: Struct tag
+// CHECK-CC13-NEXT: Class name
+// CHECK-CC13-NEXT: Nested name specifier
+// CHECK-CC13-NEXT: Objective-C interface
diff --git a/test/Index/complete-optional-params.cpp b/test/Index/complete-optional-params.cpp
new file mode 100644
index 0000000..88d8105
--- /dev/null
+++ b/test/Index/complete-optional-params.cpp
@@ -0,0 +1,75 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+void foo(int a = 42, int = 42);
+void bar(int a, int b = 42, int c = 42);
+void baz(int a = 42, ...);
+struct S{ S(int a = 42, int = 42) {} };
+
+int main() {
+    foo(42, 42);
+    bar(42, 42, 42);
+    baz(42, 42, 42);
+    S s(42, 42);
+}
+
+// RUN: c-index-test -code-completion-at=%s:10:9 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OverloadCandidate:{ResultType void}{Text foo}{LeftParen (}{Optional {CurrentParameter int a}{Optional {Comma , }{Placeholder int}}}{RightParen )} (1)
+// CHECK-CC1: Completion contexts:
+// CHECK-CC1-NEXT: Any type
+// CHECK-CC1-NEXT: Any value
+// CHECK-CC1-NEXT: Enum tag
+// CHECK-CC1-NEXT: Union tag
+// CHECK-CC1-NEXT: Struct tag
+// CHECK-CC1-NEXT: Class name
+// CHECK-CC1-NEXT: Nested name specifier
+// CHECK-CC1-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:11:9 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{CurrentParameter int a}{Optional {Comma , }{Placeholder int b}{Optional {Comma , }{Placeholder int c}}}{RightParen )} (1)
+// CHECK-CC2: Completion contexts:
+// CHECK-CC2-NEXT: Any type
+// CHECK-CC2-NEXT: Any value
+// CHECK-CC2-NEXT: Enum tag
+// CHECK-CC2-NEXT: Union tag
+// CHECK-CC2-NEXT: Struct tag
+// CHECK-CC2-NEXT: Class name
+// CHECK-CC2-NEXT: Nested name specifier
+// CHECK-CC2-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:11:16 %s | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{Placeholder int a}{Optional {Comma , }{Placeholder int b}{Optional {Comma , }{CurrentParameter int c}}}{RightParen )} (1)
+// CHECK-CC3: Completion contexts:
+// CHECK-CC3-NEXT: Any type
+// CHECK-CC3-NEXT: Any value
+// CHECK-CC3-NEXT: Enum tag
+// CHECK-CC3-NEXT: Union tag
+// CHECK-CC3-NEXT: Struct tag
+// CHECK-CC3-NEXT: Class name
+// CHECK-CC3-NEXT: Nested name specifier
+// CHECK-CC3-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:12:16 %s | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OverloadCandidate:{ResultType void}{Text baz}{LeftParen (}{Optional {Placeholder int a}{Optional {Comma , }{CurrentParameter ...}}}{RightParen )} (1)
+// CHECK-CC4: Completion contexts:
+// CHECK-CC4-NEXT: Any type
+// CHECK-CC4-NEXT: Any value
+// CHECK-CC4-NEXT: Enum tag
+// CHECK-CC4-NEXT: Union tag
+// CHECK-CC4-NEXT: Struct tag
+// CHECK-CC4-NEXT: Class name
+// CHECK-CC4-NEXT: Nested name specifier
+// CHECK-CC4-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:13:9 %s | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{Optional {CurrentParameter int a}{Optional {Comma , }{Placeholder int}}}{RightParen )} (1)
+// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter const S &}{RightParen )} (1)
+// CHECK-CC5: Completion contexts:
+// CHECK-CC5-NEXT: Any type
+// CHECK-CC5-NEXT: Any value
+// CHECK-CC5-NEXT: Enum tag
+// CHECK-CC5-NEXT: Union tag
+// CHECK-CC5-NEXT: Struct tag
+// CHECK-CC5-NEXT: Class name
+// CHECK-CC5-NEXT: Nested name specifier
+// CHECK-CC5-NEXT: Objective-C interface
diff --git a/test/Index/complete-pointer-and-reference-to-functions.cpp b/test/Index/complete-pointer-and-reference-to-functions.cpp
new file mode 100644
index 0000000..12e6cb9
--- /dev/null
+++ b/test/Index/complete-pointer-and-reference-to-functions.cpp
@@ -0,0 +1,62 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+template<class T> void (&foo(T))(T);
+template<class T> void (*bar(T))(T);
+template<class T> void (&baz(T))(T, ...);
+template<class T> void (*fiz(T))(T, ...);
+
+int main() {
+  foo(42)(42);
+  bar(42)(42);
+  baz(42)(42, 42, 42);
+  fiz(42)(42, 42, 42);
+}
+
+// RUN: c-index-test -code-completion-at=%s:10:11 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OverloadCandidate:{ResultType void}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC1: Completion contexts:
+// CHECK-CC1-NEXT: Any type
+// CHECK-CC1-NEXT: Any value
+// CHECK-CC1-NEXT: Enum tag
+// CHECK-CC1-NEXT: Union tag
+// CHECK-CC1-NEXT: Struct tag
+// CHECK-CC1-NEXT: Class name
+// CHECK-CC1-NEXT: Nested name specifier
+// CHECK-CC1-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:11:11 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OverloadCandidate:{ResultType void}{LeftParen (}{CurrentParameter int}{RightParen )} (1)
+// CHECK-CC2: Completion contexts:
+// CHECK-CC2-NEXT: Any type
+// CHECK-CC2-NEXT: Any value
+// CHECK-CC2-NEXT: Enum tag
+// CHECK-CC2-NEXT: Union tag
+// CHECK-CC2-NEXT: Struct tag
+// CHECK-CC2-NEXT: Class name
+// CHECK-CC2-NEXT: Nested name specifier
+// CHECK-CC2-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:12:18 %s | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OverloadCandidate:{ResultType void}{LeftParen (}{Placeholder int}{Optional {Comma , }{CurrentParameter ...}}{RightParen )} (1)
+// CHECK-CC3: Completion contexts:
+// CHECK-CC3-NEXT: Any type
+// CHECK-CC3-NEXT: Any value
+// CHECK-CC3-NEXT: Enum tag
+// CHECK-CC3-NEXT: Union tag
+// CHECK-CC3-NEXT: Struct tag
+// CHECK-CC3-NEXT: Class name
+// CHECK-CC3-NEXT: Nested name specifier
+// CHECK-CC3-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:13:18 %s | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OverloadCandidate:{ResultType void}{LeftParen (}{Placeholder int}{Optional {Comma , }{CurrentParameter ...}}{RightParen )} (1)
+// CHECK-CC4: Completion contexts:
+// CHECK-CC4-NEXT: Any type
+// CHECK-CC4-NEXT: Any value
+// CHECK-CC4-NEXT: Enum tag
+// CHECK-CC4-NEXT: Union tag
+// CHECK-CC4-NEXT: Struct tag
+// CHECK-CC4-NEXT: Class name
+// CHECK-CC4-NEXT: Nested name specifier
+// CHECK-CC4-NEXT: Objective-C interface
diff --git a/test/Index/complete-template-friends-defined.cpp b/test/Index/complete-template-friends-defined.cpp
new file mode 100644
index 0000000..f1d09c1
--- /dev/null
+++ b/test/Index/complete-template-friends-defined.cpp
@@ -0,0 +1,33 @@
+// The run lines are below, because this test is line- and
+// column-number sensitive.
+
+namespace N {
+  template<typename T> struct A {
+    template<typename U> friend class B;
+  };
+
+  template<typename T> struct B { };
+}
+
+void foo() {
+  N::A<int> a1;
+  N::A<int> a2;
+}
+
+namespace M {
+  template<typename T> struct C {
+    template<typename U> friend struct C;
+  };
+}
+
+void bar() {
+  M::C<int> c1;
+  M::C<int> c2;
+}
+
+// RUN: c-index-test -code-completion-at=%s:14:6 %s | FileCheck -check-prefix=CHECK-ACCESS-1 %s
+// CHECK-ACCESS-1: ClassTemplate:{TypedText A}{LeftAngle <}{Placeholder typename T}{RightAngle >} (50)
+// CHECK-ACCESS-1: ClassTemplate:{TypedText B}{LeftAngle <}{Placeholder typename T}{RightAngle >} (50)
+
+// RUN: c-index-test -code-completion-at=%s:25:6 %s | FileCheck -check-prefix=CHECK-ACCESS-2 %s
+// CHECK-ACCESS-2: ClassTemplate:{TypedText C}{LeftAngle <}{Placeholder typename T}{RightAngle >} (50)
diff --git a/test/Index/complete-type-factors.m b/test/Index/complete-type-factors.m
index e5aa893..f2588e6 100644
--- a/test/Index/complete-type-factors.m
+++ b/test/Index/complete-type-factors.m
@@ -78,19 +78,19 @@
 // CHECK-CC3: NotImplemented:{ResultType size_t}{TypedText sizeof}{LeftParen (}{Placeholder expression-or-type}{RightParen )} (40)
 // CHECK-CC3: FunctionDecl:{ResultType enum Priority}{TypedText test1}{LeftParen (}{Placeholder enum Priority priority}{Comma , }{Placeholder enum Color color}{Comma , }{Placeholder int integer}{RightParen )} (12)
 // RUN: c-index-test -code-completion-at=%s:19:9 -Xclang -code-completion-patterns %s | FileCheck -check-prefix=CHECK-CC4 %s
-// CHECK-CC4: EnumConstantDecl:{ResultType enum Color}{TypedText Blue} (16)
-// CHECK-CC4: VarDecl:{ResultType enum Color}{TypedText c} (8)
-// CHECK-CC4: ParmDecl:{ResultType enum Color}{TypedText color} (8)
-// CHECK-CC4: FunctionDecl:{ResultType int}{TypedText func1}{LeftParen (}{Placeholder enum Color}{RightParen )} (25)
+// CHECK-CC4: EnumConstantDecl:{ResultType enum Color}{TypedText Blue} (65)
+// CHECK-CC4: VarDecl:{ResultType enum Color}{TypedText c} (34)
+// CHECK-CC4: ParmDecl:{ResultType enum Color}{TypedText color} (34)
+// CHECK-CC4: FunctionDecl:{ResultType int}{TypedText func1}{LeftParen (}{Placeholder enum Color}{RightParen )} (50)
 // CHECK-CC4: FunctionDecl:{ResultType enum Priority}{TypedText func2}{LeftParen (}{Placeholder int}{RightParen )} (50)
 // CHECK-CC4: FunctionDecl:{ResultType void}{TypedText func3}{LeftParen (}{Placeholder float}{RightParen )} (50)
-// CHECK-CC4: EnumConstantDecl:{ResultType enum Color}{TypedText Green} (16)
+// CHECK-CC4: EnumConstantDecl:{ResultType enum Color}{TypedText Green} (65)
 // CHECK-CC4: EnumConstantDecl:{ResultType enum Priority}{TypedText High} (65)
-// CHECK-CC4: VarDecl:{ResultType int}{TypedText i} (17)
-// CHECK-CC4: ParmDecl:{ResultType int}{TypedText integer} (17)
+// CHECK-CC4: VarDecl:{ResultType int}{TypedText i} (34)
+// CHECK-CC4: ParmDecl:{ResultType int}{TypedText integer} (34)
 // CHECK-CC4: EnumConstantDecl:{ResultType enum Priority}{TypedText Low} (65)
 // CHECK-CC4: ParmDecl:{ResultType enum Priority}{TypedText priority} (34)
-// CHECK-CC4: EnumConstantDecl:{ResultType enum Color}{TypedText Red} (16)
+// CHECK-CC4: EnumConstantDecl:{ResultType enum Color}{TypedText Red} (65)
 // CHECK-CC4: NotImplemented:{ResultType size_t}{TypedText sizeof}{LeftParen (}{Placeholder expression-or-type}{RightParen )} (40)
 // CHECK-CC4: FunctionDecl:{ResultType enum Priority}{TypedText test1}{LeftParen (}{Placeholder enum Priority priority}{Comma , }{Placeholder enum Color color}{Comma , }{Placeholder int integer}{RightParen )} (50)
 // RUN: c-index-test -code-completion-at=%s:21:9 -Xclang -code-completion-patterns %s | FileCheck -check-prefix=CHECK-CC4 %s
diff --git a/test/Index/cxx11-lambdas.cpp b/test/Index/cxx11-lambdas.cpp
index afb540a..d0ee908 100644
--- a/test/Index/cxx11-lambdas.cpp
+++ b/test/Index/cxx11-lambdas.cpp
@@ -30,4 +30,4 @@
 // CHECK-INDEX: [indexEntityReference]: kind: typedef | name: Integer | USR: c:cxx11-lambdas.cpp@T@Integer | lang: C | cursor: TypeRef=Integer:3:13 | loc: 7:38
 // CHECK-INDEX: [indexEntityReference]: kind: variable | name: localA | USR: c:cxx11-lambdas.cpp@100@S@X@F@f#@localA | lang: C | cursor: DeclRefExpr=localA:6:9 | loc: 8:14
 // CHECK-INDEX: [indexEntityReference]: kind: variable | name: localB | USR: c:cxx11-lambdas.cpp@100@S@X@F@f#@localB | lang: C | cursor: DeclRefExpr=localB:6:17 | loc: 8:23
-// CHECK-INDEX: [indexEntityReference]: kind: variable | name: x | USR: c:cxx11-lambdas.cpp@157@S@X@F@f#@Ca@F@operator()#I#1@x | lang: C | cursor: DeclRefExpr=x:7:46 | loc: 8:32
+// CHECK-INDEX: [indexEntityReference]: kind: variable | name: x | USR: c:cxx11-lambdas.cpp@157@S@X@F@f#@Sa@F@operator()#I#1@x | lang: C | cursor: DeclRefExpr=x:7:46 | loc: 8:32
diff --git a/test/Index/index-templates.cpp b/test/Index/index-templates.cpp
index 1552235..570d7cf 100644
--- a/test/Index/index-templates.cpp
+++ b/test/Index/index-templates.cpp
@@ -191,27 +191,27 @@
 // CHECK-LOAD: index-templates.cpp:111:6: FunctionDecl=foo:111:6 [Specialization of foo:107:6] [Template arg 0: kind: 1, type: float] [Template arg 1: kind: 4, intval: 9] [Template arg 2: kind: 4, intval: 1] [Template arg 3: kind: 4, intval: 14] Extent=[110:1 - 111:64]
 
 // RUN: c-index-test -test-load-source-usrs all -fno-delayed-template-parsing %s | FileCheck -check-prefix=CHECK-USRS %s
-// CHECK-USRS: index-templates.cpp c:@FT@>3#T#Nt0.0#t>2#T#Nt1.0f#>t0.22S0_# Extent=[3:1 - 4:22]
+// CHECK-USRS: index-templates.cpp c:@FT@>3#T#Nt0.0#t>2#T#Nt1.0f#>t0.22S0_#v# Extent=[3:1 - 4:22]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@70 Extent=[3:10 - 3:20]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@82 Extent=[3:22 - 3:29]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@91 Extent=[3:31 - 3:67]
-// CHECK-USRS: index-templates.cpp c:index-templates.cpp@136@FT@>3#T#Nt0.0#t>2#T#Nt1.0f#>t0.22S0_#@x Extent=[4:8 - 4:21]
-// CHECK-USRS: index-templates.cpp c:@CT>1#T@allocator Extent=[6:1 - 6:37]
+// CHECK-USRS: index-templates.cpp c:index-templates.cpp@136@FT@>3#T#Nt0.0#t>2#T#Nt1.0f#>t0.22S0_#v#@x Extent=[4:8 - 4:21]
+// CHECK-USRS: index-templates.cpp c:@ST>1#T@allocator Extent=[6:1 - 6:37]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@162 Extent=[6:10 - 6:20]
-// CHECK-USRS: index-templates.cpp c:@CT>2#T#T@vector Extent=[8:1 - 11:2]
+// CHECK-USRS: index-templates.cpp c:@ST>2#T#T@vector Extent=[8:1 - 11:2]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@201 Extent=[8:10 - 8:20]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@213 Extent=[8:22 - 8:51]
-// CHECK-USRS: index-templates.cpp c:@CT>2#T#T@vector@F@clear# Extent=[10:3 - 10:15]
-// CHECK-USRS: index-templates.cpp c:@CP>1#T@vector>#*t0.0#>@CT>1#T@allocator1S0_ Extent=[13:1 - 14:21]
+// CHECK-USRS: index-templates.cpp c:@ST>2#T#T@vector@F@clear# Extent=[10:3 - 10:15]
+// CHECK-USRS: index-templates.cpp c:@SP>1#T@vector>#*t0.0#>@ST>1#T@allocator1S0_ Extent=[13:1 - 14:21]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@289 Extent=[13:10 - 13:20]
 // CHECK-USRS: index-templates.cpp c:@S@Z1 Extent=[16:1 - 16:14]
-// CHECK-USRS: index-templates.cpp c:@C@vector>#$@S@Z1#$@C@allocator>#S0_ Extent=[18:1 - 18:26]
+// CHECK-USRS: index-templates.cpp c:@S@vector>#$@S@Z1#$@S@allocator>#S0_ Extent=[18:1 - 18:26]
 // CHECK-USRS: index-templates.cpp c:@S@Z2 Extent=[20:1 - 20:14]
-// CHECK-USRS: index-templates.cpp c:@C@vector>#$@S@Z2#$@C@allocator>#S0_ Extent=[22:1 - 25:2]
-// CHECK-USRS: index-templates.cpp c:@C@vector>#$@S@Z2#$@C@allocator>#S0_@F@clear# Extent=[24:3 - 24:15]
+// CHECK-USRS: index-templates.cpp c:@S@vector>#$@S@Z2#$@S@allocator>#S0_ Extent=[22:1 - 25:2]
+// CHECK-USRS: index-templates.cpp c:@S@vector>#$@S@Z2#$@S@allocator>#S0_@F@clear# Extent=[24:3 - 24:15]
 // CHECK-USRS: index-templates.cpp c:@ST>2#T#T@Y Extent=[27:1 - 31:2]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@443 Extent=[27:10 - 27:20]
 // CHECK-USRS: index-templates.cpp c:index-templates.cpp@455 Extent=[27:22 - 27:32]
 // CHECK-USRS-NOT: type
 // CHECK-USRS: index-templates.cpp c:@S@Z3 Extent=[33:1 - 33:14]
-// CHECK-USRS: index-templates.cpp c:@F@f#$@S@map>#$@S@Z4#$@S@Pair>#I#S1_#$@S@compare>#$@S@Pair>#S1_#S2_#$@C@allocator>#S4_#
+// CHECK-USRS: index-templates.cpp c:@F@f#$@S@map>#$@S@Z4#$@S@Pair>#I#S1_#$@S@compare>#$@S@Pair>#S1_#S2_#$@S@allocator>#S4_#
diff --git a/test/Index/load-stmts.cpp b/test/Index/load-stmts.cpp
index ed0debd..4a44c66 100644
--- a/test/Index/load-stmts.cpp
+++ b/test/Index/load-stmts.cpp
@@ -117,7 +117,7 @@
   (void)reinterpret_cast<float *>(ip);
 }
 
-// RUN: c-index-test -test-load-source all -fno-delayed-template-parsing %s | FileCheck %s
+// RUN: c-index-test -test-load-source all -fno-delayed-template-parsing -frtti %s | FileCheck %s
 // CHECK: load-stmts.cpp:1:13: TypedefDecl=T:1:13 (Definition) Extent=[1:1 - 1:14]
 // CHECK: load-stmts.cpp:2:8: StructDecl=X:2:8 (Definition) Extent=[2:1 - 2:23]
 // CHECK: load-stmts.cpp:2:16: FieldDecl=a:2:16 (Definition) Extent=[2:12 - 2:17]
diff --git a/test/Index/overriding-ftemplate-comments.cpp b/test/Index/overriding-ftemplate-comments.cpp
index 0bc3c2f..7fc15f0 100644
--- a/test/Index/overriding-ftemplate-comments.cpp
+++ b/test/Index/overriding-ftemplate-comments.cpp
@@ -13,12 +13,12 @@
 template<typename T>
 void comment_to_html_conversion_17(T AAA);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_17</Name><USR>c:@FT@&gt;1#Tcomment_to_html_conversion_17#t0.0#</USR><Declaration>template &lt;typename T&gt; void comment_to_html_conversion_17(T AAA)</Declaration><Parameters><Parameter><Name>AAA</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_17</Name><USR>c:@FT@&gt;1#Tcomment_to_html_conversion_17#t0.0#v#</USR><Declaration>template &lt;typename T&gt; void comment_to_html_conversion_17(T AAA)</Declaration><Parameters><Parameter><Name>AAA</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
 
 template<typename T>
 void comment_to_html_conversion_17(T PPP);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_17</Name><USR>c:@FT@&gt;1#Tcomment_to_html_conversion_17#t0.0#</USR><Declaration>template &lt;typename T&gt; void comment_to_html_conversion_17(T PPP)</Declaration><Parameters><Parameter><Name>PPP</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_17</Name><USR>c:@FT@&gt;1#Tcomment_to_html_conversion_17#t0.0#v#</USR><Declaration>template &lt;typename T&gt; void comment_to_html_conversion_17(T PPP)</Declaration><Parameters><Parameter><Name>PPP</Name><Index>0</Index><Direction isExplicit="0">in</Direction><Discussion><Para> Blah blah</Para></Discussion></Parameter></Parameters></Function>]
 
 //===----------------------------------------------------------------------===//
 
@@ -27,12 +27,12 @@
 template<typename AAA, typename BBB>
 void comment_to_html_conversion_19(AAA aaa, BBB bbb);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_19</Name><USR>c:@FT@&gt;2#T#Tcomment_to_html_conversion_19#t0.0#t0.1#</USR><Declaration>template &lt;typename AAA, typename BBB&gt;\nvoid comment_to_html_conversion_19(AAA aaa, BBB bbb)</Declaration><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>BBB</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_19</Name><USR>c:@FT@&gt;2#T#Tcomment_to_html_conversion_19#t0.0#t0.1#v#</USR><Declaration>template &lt;typename AAA, typename BBB&gt;\nvoid comment_to_html_conversion_19(AAA aaa, BBB bbb)</Declaration><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>BBB</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter></TemplateParameters></Function>]
 
 template<typename PPP, typename QQQ>
 void comment_to_html_conversion_19(PPP aaa, QQQ bbb);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_19</Name><USR>c:@FT@&gt;2#T#Tcomment_to_html_conversion_19#t0.0#t0.1#</USR><Declaration>template &lt;typename PPP, typename QQQ&gt;\nvoid comment_to_html_conversion_19(PPP aaa, QQQ bbb)</Declaration><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_19</Name><USR>c:@FT@&gt;2#T#Tcomment_to_html_conversion_19#t0.0#t0.1#v#</USR><Declaration>template &lt;typename PPP, typename QQQ&gt;\nvoid comment_to_html_conversion_19(PPP aaa, QQQ bbb)</Declaration><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter></TemplateParameters></Function>]
 
 //===----------------------------------------------------------------------===//
 
@@ -43,12 +43,12 @@
 template<typename AAA, typename BBB, int CCC>
 void comment_to_html_conversion_20(AAA aaa, BBB bbb);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_20</Name><USR>c:@FT@&gt;3#T#T#NIcomment_to_html_conversion_20#t0.0#t0.1#</USR><Declaration>template &lt;typename AAA, typename BBB, int CCC&gt;\nvoid comment_to_html_conversion_20(AAA aaa, BBB bbb)</Declaration><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>BBB</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>CCC</Name><Index>2</Index><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>UUU</Name><Discussion><Para> Zzz </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_20</Name><USR>c:@FT@&gt;3#T#T#NIcomment_to_html_conversion_20#t0.0#t0.1#v#</USR><Declaration>template &lt;typename AAA, typename BBB, int CCC&gt;\nvoid comment_to_html_conversion_20(AAA aaa, BBB bbb)</Declaration><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>BBB</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>CCC</Name><Index>2</Index><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>UUU</Name><Discussion><Para> Zzz </Para></Discussion></Parameter></TemplateParameters></Function>]
 
 template<typename PPP, typename QQQ, int RRR>
 void comment_to_html_conversion_20(PPP aaa, QQQ bbb);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_20</Name><USR>c:@FT@&gt;3#T#T#NIcomment_to_html_conversion_20#t0.0#t0.1#</USR><Declaration>template &lt;typename PPP, typename QQQ, int RRR&gt;\nvoid comment_to_html_conversion_20(PPP aaa, QQQ bbb)</Declaration><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>RRR</Name><Index>2</Index><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>UUU</Name><Discussion><Para> Zzz </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_20</Name><USR>c:@FT@&gt;3#T#T#NIcomment_to_html_conversion_20#t0.0#t0.1#v#</USR><Declaration>template &lt;typename PPP, typename QQQ, int RRR&gt;\nvoid comment_to_html_conversion_20(PPP aaa, QQQ bbb)</Declaration><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> Aaa</Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Index>1</Index><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>RRR</Name><Index>2</Index><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>UUU</Name><Discussion><Para> Zzz </Para></Discussion></Parameter></TemplateParameters></Function>]
 
 //===----------------------------------------------------------------------===//
 
@@ -59,12 +59,12 @@
 template<template<template<typename CCC> class DDD, class BBB> class AAA>
 void comment_to_html_conversion_21();
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_21</Name><USR>c:@FT@&gt;1#t&gt;2#t&gt;1#T#Tcomment_to_html_conversion_21#</USR><Declaration>template &lt;template &lt;template &lt;typename CCC&gt; class DDD, class BBB&gt; class AAA&gt;\nvoid comment_to_html_conversion_21()</Declaration><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> Aaa </Para></Discussion></Parameter><Parameter><Name>BBB</Name><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>CCC</Name><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>DDD</Name><Discussion><Para> Ddd</Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_21</Name><USR>c:@FT@&gt;1#t&gt;2#t&gt;1#T#Tcomment_to_html_conversion_21#v#</USR><Declaration>template &lt;template &lt;template &lt;typename CCC&gt; class DDD, class BBB&gt; class AAA&gt;\nvoid comment_to_html_conversion_21()</Declaration><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> Aaa </Para></Discussion></Parameter><Parameter><Name>BBB</Name><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>CCC</Name><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>DDD</Name><Discussion><Para> Ddd</Para></Discussion></Parameter></TemplateParameters></Function>]
 
 template<template<template<typename RRR> class SSS, class QQQ> class PPP>
 void comment_to_html_conversion_21();
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_21</Name><USR>c:@FT@&gt;1#t&gt;2#t&gt;1#T#Tcomment_to_html_conversion_21#</USR><Declaration>template &lt;template &lt;template &lt;typename RRR&gt; class SSS, class QQQ&gt; class PPP&gt;\nvoid comment_to_html_conversion_21()</Declaration><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> Aaa </Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>RRR</Name><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>SSS</Name><Discussion><Para> Ddd</Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_21</Name><USR>c:@FT@&gt;1#t&gt;2#t&gt;1#T#Tcomment_to_html_conversion_21#v#</USR><Declaration>template &lt;template &lt;template &lt;typename RRR&gt; class SSS, class QQQ&gt; class PPP&gt;\nvoid comment_to_html_conversion_21()</Declaration><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> Aaa </Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Discussion><Para> Bbb </Para></Discussion></Parameter><Parameter><Name>RRR</Name><Discussion><Para> Ccc </Para></Discussion></Parameter><Parameter><Name>SSS</Name><Discussion><Para> Ddd</Para></Discussion></Parameter></TemplateParameters></Function>]
 
 //===----------------------------------------------------------------------===//
 
@@ -77,10 +77,10 @@
 template <class C1, template <class C2, template <class C3, class C4> class BBB > class AAA>
 void comment_to_html_conversion_22();
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_22</Name><USR>c:@FT@&gt;2#T#t&gt;2#T#t&gt;2#T#Tcomment_to_html_conversion_22#</USR><Declaration>template &lt;class C1, template &lt;class C2, template &lt;class C3, class C4&gt; class BBB&gt;\n      class AAA&gt;\nvoid comment_to_html_conversion_22()</Declaration><TemplateParameters><Parameter><Name>C1</Name><Index>0</Index><Discussion><Para> Ccc 1 </Para></Discussion></Parameter><Parameter><Name>AAA</Name><Index>1</Index><Discussion><Para> Zzz </Para></Discussion></Parameter><Parameter><Name>C2</Name><Discussion><Para> Ccc 2 </Para></Discussion></Parameter><Parameter><Name>C3</Name><Discussion><Para> Ccc 3 </Para></Discussion></Parameter><Parameter><Name>C4</Name><Discussion><Para> Ccc 4 </Para></Discussion></Parameter><Parameter><Name>BBB</Name><Discussion><Para> Bbb</Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_22</Name><USR>c:@FT@&gt;2#T#t&gt;2#T#t&gt;2#T#Tcomment_to_html_conversion_22#v#</USR><Declaration>template &lt;class C1, template &lt;class C2, template &lt;class C3, class C4&gt; class BBB&gt;\n      class AAA&gt;\nvoid comment_to_html_conversion_22()</Declaration><TemplateParameters><Parameter><Name>C1</Name><Index>0</Index><Discussion><Para> Ccc 1 </Para></Discussion></Parameter><Parameter><Name>AAA</Name><Index>1</Index><Discussion><Para> Zzz </Para></Discussion></Parameter><Parameter><Name>C2</Name><Discussion><Para> Ccc 2 </Para></Discussion></Parameter><Parameter><Name>C3</Name><Discussion><Para> Ccc 3 </Para></Discussion></Parameter><Parameter><Name>C4</Name><Discussion><Para> Ccc 4 </Para></Discussion></Parameter><Parameter><Name>BBB</Name><Discussion><Para> Bbb</Para></Discussion></Parameter></TemplateParameters></Function>]
 
 template<class CCC1, template<class CCC2, template<class CCC3, class CCC4> class QQQ> class PPP>
 void comment_to_html_conversion_22();
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_22</Name><USR>c:@FT@&gt;2#T#t&gt;2#T#t&gt;2#T#Tcomment_to_html_conversion_22#</USR><Declaration>template &lt;class CCC1, template &lt;class CCC2, template &lt;class CCC3, class CCC4&gt;\n                            class QQQ&gt; class PPP&gt;\nvoid comment_to_html_conversion_22()</Declaration><TemplateParameters><Parameter><Name>CCC1</Name><Index>0</Index><Discussion><Para> Ccc 1 </Para></Discussion></Parameter><Parameter><Name>PPP</Name><Index>1</Index><Discussion><Para> Zzz </Para></Discussion></Parameter><Parameter><Name>CCC2</Name><Discussion><Para> Ccc 2 </Para></Discussion></Parameter><Parameter><Name>CCC3</Name><Discussion><Para> Ccc 3 </Para></Discussion></Parameter><Parameter><Name>CCC4</Name><Discussion><Para> Ccc 4 </Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Discussion><Para> Bbb</Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-ftemplate-comments.cpp" line="[[@LINE-2]]" column="6"><Name>comment_to_html_conversion_22</Name><USR>c:@FT@&gt;2#T#t&gt;2#T#t&gt;2#T#Tcomment_to_html_conversion_22#v#</USR><Declaration>template &lt;class CCC1, template &lt;class CCC2, template &lt;class CCC3, class CCC4&gt;\n                            class QQQ&gt; class PPP&gt;\nvoid comment_to_html_conversion_22()</Declaration><TemplateParameters><Parameter><Name>CCC1</Name><Index>0</Index><Discussion><Para> Ccc 1 </Para></Discussion></Parameter><Parameter><Name>PPP</Name><Index>1</Index><Discussion><Para> Zzz </Para></Discussion></Parameter><Parameter><Name>CCC2</Name><Discussion><Para> Ccc 2 </Para></Discussion></Parameter><Parameter><Name>CCC3</Name><Discussion><Para> Ccc 3 </Para></Discussion></Parameter><Parameter><Name>CCC4</Name><Discussion><Para> Ccc 4 </Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Discussion><Para> Bbb</Para></Discussion></Parameter></TemplateParameters></Function>]
 
diff --git a/test/Index/overriding-method-comments.mm b/test/Index/overriding-method-comments.mm
index 9285693..d995e0e 100644
--- a/test/Index/overriding-method-comments.mm
+++ b/test/Index/overriding-method-comments.mm
@@ -116,10 +116,10 @@
 template<typename AAA, typename BBB>
 void foo(AAA, BBB);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-method-comments.mm" line="[[@LINE-2]]" column="6"><Name>foo</Name><USR>c:@FT@&gt;2#T#Tfoo#t0.0#t0.1#</USR><Declaration>template &lt;typename AAA, typename BBB&gt; void foo(AAA, BBB)</Declaration><Abstract><Para> Documentation </Para></Abstract><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> The type, silly as well.</Para></Discussion></Parameter><Parameter><Name>BBB</Name><Index>1</Index><Discussion><Para> The type, silly. </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-method-comments.mm" line="[[@LINE-2]]" column="6"><Name>foo</Name><USR>c:@FT@&gt;2#T#Tfoo#t0.0#t0.1#v#</USR><Declaration>template &lt;typename AAA, typename BBB&gt; void foo(AAA, BBB)</Declaration><Abstract><Para> Documentation </Para></Abstract><TemplateParameters><Parameter><Name>AAA</Name><Index>0</Index><Discussion><Para> The type, silly as well.</Para></Discussion></Parameter><Parameter><Name>BBB</Name><Index>1</Index><Discussion><Para> The type, silly. </Para></Discussion></Parameter></TemplateParameters></Function>]
 
 template<typename PPP, typename QQQ>
 void foo(PPP, QQQ);
 
-// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-method-comments.mm" line="[[@LINE-2]]" column="6"><Name>foo</Name><USR>c:@FT@&gt;2#T#Tfoo#t0.0#t0.1#</USR><Declaration>template &lt;typename PPP, typename QQQ&gt; void foo(PPP, QQQ)</Declaration><Abstract><Para> Documentation </Para></Abstract><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> The type, silly as well.</Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Index>1</Index><Discussion><Para> The type, silly. </Para></Discussion></Parameter></TemplateParameters></Function>]
+// CHECK: FullCommentAsXML=[<Function templateKind="template" file="{{[^"]+}}overriding-method-comments.mm" line="[[@LINE-2]]" column="6"><Name>foo</Name><USR>c:@FT@&gt;2#T#Tfoo#t0.0#t0.1#v#</USR><Declaration>template &lt;typename PPP, typename QQQ&gt; void foo(PPP, QQQ)</Declaration><Abstract><Para> Documentation </Para></Abstract><TemplateParameters><Parameter><Name>PPP</Name><Index>0</Index><Discussion><Para> The type, silly as well.</Para></Discussion></Parameter><Parameter><Name>QQQ</Name><Index>1</Index><Discussion><Para> The type, silly. </Para></Discussion></Parameter></TemplateParameters></Function>]
 
diff --git a/test/Index/skip-parsed-bodies/compile_commands.json b/test/Index/skip-parsed-bodies/compile_commands.json
index da5e777..6707e84 100644
--- a/test/Index/skip-parsed-bodies/compile_commands.json
+++ b/test/Index/skip-parsed-bodies/compile_commands.json
@@ -16,7 +16,7 @@
 }
 ]
 
-// XFAIL: mingw32,win32
+// XFAIL: mingw32,win32,windows-gnu
 // RUN: c-index-test -index-compile-db %s | FileCheck %s
 
 // CHECK:      [enteredMainFile]: t1.cpp
diff --git a/test/Index/usrs-cxx0x.cpp b/test/Index/usrs-cxx0x.cpp
index a48b446..b40bc4c 100644
--- a/test/Index/usrs-cxx0x.cpp
+++ b/test/Index/usrs-cxx0x.cpp
@@ -3,6 +3,16 @@
 
 void f(tuple<int, float, double>);
 
+class TestCls {
+  void meth() &;
+  void meth() &&;
+  void meth(int&&);
+};
+
 // RUN: c-index-test -test-load-source-usrs all -std=c++11 %s | FileCheck %s
 // CHECK: usrs-cxx0x.cpp c:@ST>1#pT@tuple Extent=[1:1 - 2:17]
 // CHECK: usrs-cxx0x.cpp c:@F@f#$@S@tuple>#p3Ifd# Extent=[4:1 - 4:34]
+
+// CHECK: usrs-cxx0x.cpp c:@S@TestCls@F@meth#& Extent=[7:3 - 7:16]
+// CHECK: usrs-cxx0x.cpp c:@S@TestCls@F@meth#&& Extent=[8:3 - 8:17]
+// CHECK: usrs-cxx0x.cpp c:@S@TestCls@F@meth#&&I# Extent=[9:3 - 9:19]
diff --git a/test/Index/usrs.cpp b/test/Index/usrs.cpp
index 909ce75..8ad1702 100644
--- a/test/Index/usrs.cpp
+++ b/test/Index/usrs.cpp
@@ -79,7 +79,23 @@
   foo.bar();
 }
 
-// RUN: c-index-test -test-load-source-usrs all %s | FileCheck %s
+template <class T> typename T::A someTemplFn() {}
+template <class T> typename T::B someTemplFn() {}
+template <class T> int someTemplFn() {}
+
+void funWithChar(char c) {}
+void funWithChar(unsigned char c) {}
+void funWithChar(signed char c) {}
+
+struct { int x; } embedS1;
+struct { int x; } embedS2;
+
+template <typename T>
+class TC1 {
+  void meth(TC1);
+};
+
+// RUN: c-index-test -test-load-source-usrs all -fno-delayed-template-parsing %s | FileCheck %s
 // CHECK: usrs.cpp c:@N@foo Extent=[1:1 - 4:2]
 // CHECK: usrs.cpp c:@N@foo@x Extent=[2:3 - 2:8]
 // CHECK: usrs.cpp c:@N@foo@F@bar#I# Extent=[3:3 - 3:18]
@@ -88,20 +104,20 @@
 // CHECK: usrs.cpp c:usrs.cpp@N@bar@T@QType Extent=[6:3 - 6:20]
 // CHECK: usrs.cpp c:@N@bar@F@bar#I# Extent=[7:3 - 7:20]
 // CHECK: usrs.cpp c:usrs.cpp@94@N@bar@F@bar#I#@z Extent=[7:12 - 7:19]
-// CHECK: usrs.cpp c:@C@ClsA Extent=[10:1 - 14:2]
+// CHECK: usrs.cpp c:@S@ClsA Extent=[10:1 - 14:2]
 // CHECK: usrs.cpp c: Extent=[11:1 - 11:8]
-// CHECK: usrs.cpp c:@C@ClsA@FI@a Extent=[12:3 - 12:8]
-// CHECK: usrs.cpp c:@C@ClsA@FI@b Extent=[12:3 - 12:11]
-// CHECK: usrs.cpp c:@C@ClsA@F@ClsA#I#I# Extent=[13:3 - 13:37]
-// CHECK: usrs.cpp c:usrs.cpp@147@C@ClsA@F@ClsA#I#I#@A Extent=[13:8 - 13:13]
-// CHECK: usrs.cpp c:usrs.cpp@154@C@ClsA@F@ClsA#I#I#@B Extent=[13:15 - 13:20]
+// CHECK: usrs.cpp c:@S@ClsA@FI@a Extent=[12:3 - 12:8]
+// CHECK: usrs.cpp c:@S@ClsA@FI@b Extent=[12:3 - 12:11]
+// CHECK: usrs.cpp c:@S@ClsA@F@ClsA#I#I# Extent=[13:3 - 13:37]
+// CHECK: usrs.cpp c:usrs.cpp@147@S@ClsA@F@ClsA#I#I#@A Extent=[13:8 - 13:13]
+// CHECK: usrs.cpp c:usrs.cpp@154@S@ClsA@F@ClsA#I#I#@B Extent=[13:15 - 13:20]
 // CHECK: usrs.cpp c:@N@foo Extent=[16:1 - 22:2]
-// CHECK: usrs.cpp c:@N@foo@C@ClsB Extent=[17:3 - 21:4]
+// CHECK: usrs.cpp c:@N@foo@S@ClsB Extent=[17:3 - 21:4]
 // CHECK: usrs.cpp c: Extent=[18:3 - 18:10]
-// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@ClsB# Extent=[19:5 - 19:27]
-// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result#1 Extent=[20:5 - 20:23]
-// CHECK: usrs.cpp c:@N@foo@C@ClsB@F@result#1 Extent=[24:1 - 26:2]
-// CHECK: usrs.cpp c:usrs.cpp@aN@C@ClsC Extent=[29:3 - 29:35]
+// CHECK: usrs.cpp c:@N@foo@S@ClsB@F@ClsB# Extent=[19:5 - 19:27]
+// CHECK: usrs.cpp c:@N@foo@S@ClsB@F@result#1 Extent=[20:5 - 20:23]
+// CHECK: usrs.cpp c:@N@foo@S@ClsB@F@result#1 Extent=[24:1 - 26:2]
+// CHECK: usrs.cpp c:usrs.cpp@aN@S@ClsC Extent=[29:3 - 29:35]
 // CHECK: usrs.cpp c:usrs.cpp@aN@w Extent=[30:3 - 30:8]
 // CHECK: usrs.cpp c:@z Extent=[33:1 - 33:6]
 // CHECK: usrs.cpp c:@N@foo Extent=[35:1 - 40:2]
@@ -115,19 +131,19 @@
 // CHECK: usrs.cpp c:usrs.cpp@529@N@foo@N@taz@F@sub#I#I#@b Extent=[38:19 - 38:24]
 // CHECK: usrs.cpp c:@N@foo Extent=[42:1 - 52:3]
 // CHECK: usrs.cpp c:@N@foo@N@taz Extent=[42:17 - 52:2]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD Extent=[43:3 - 51:4]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD Extent=[43:3 - 51:4]
 // CHECK: usrs.cpp c: Extent=[44:3 - 44:10]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator=#I# Extent=[45:5 - 45:52]
-// CHECK: usrs.cpp c:usrs.cpp@638@N@foo@N@taz@C@ClsD@F@operator=#I#@x Extent=[45:21 - 45:26]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator=#d# Extent=[46:5 - 46:61]
-// CHECK: usrs.cpp c:usrs.cpp@690@N@foo@N@taz@C@ClsD@F@operator=#d#@x Extent=[46:21 - 46:29]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator=#&1$@N@foo@N@taz@C@ClsD# Extent=[47:5 - 47:62]
-// CHECK: usrs.cpp c:usrs.cpp@751@N@foo@N@taz@C@ClsD@F@operator=#&1$@N@foo@N@taz@C@ClsD#@x Extent=[47:21 - 47:34]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@qux#S Extent=[48:5 - 48:21]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@uz#I.#S Extent=[49:5 - 49:30]
-// CHECK: usrs.cpp c:usrs.cpp@833@N@foo@N@taz@C@ClsD@F@uz#I.#S@z Extent=[49:19 - 49:24]
-// CHECK: usrs.cpp c:@N@foo@N@taz@C@ClsD@F@operator==#&1$@N@foo@N@taz@C@ClsD#1 Extent=[50:5 - 50:62]
-// CHECK: usrs.cpp c:usrs.cpp@866@N@foo@N@taz@C@ClsD@F@operator==#&1$@N@foo@N@taz@C@ClsD#1@x Extent=[50:21 - 50:34]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD@F@operator=#I# Extent=[45:5 - 45:52]
+// CHECK: usrs.cpp c:usrs.cpp@638@N@foo@N@taz@S@ClsD@F@operator=#I#@x Extent=[45:21 - 45:26]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD@F@operator=#d# Extent=[46:5 - 46:61]
+// CHECK: usrs.cpp c:usrs.cpp@690@N@foo@N@taz@S@ClsD@F@operator=#d#@x Extent=[46:21 - 46:29]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD@F@operator=#&1$@N@foo@N@taz@S@ClsD# Extent=[47:5 - 47:62]
+// CHECK: usrs.cpp c:usrs.cpp@751@N@foo@N@taz@S@ClsD@F@operator=#&1$@N@foo@N@taz@S@ClsD#@x Extent=[47:21 - 47:34]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD@F@qux#S Extent=[48:5 - 48:21]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD@F@uz#I.#S Extent=[49:5 - 49:30]
+// CHECK: usrs.cpp c:usrs.cpp@833@N@foo@N@taz@S@ClsD@F@uz#I.#S@z Extent=[49:19 - 49:24]
+// CHECK: usrs.cpp c:@N@foo@N@taz@S@ClsD@F@operator==#&1$@N@foo@N@taz@S@ClsD#1 Extent=[50:5 - 50:62]
+// CHECK: usrs.cpp c:usrs.cpp@866@N@foo@N@taz@S@ClsD@F@operator==#&1$@N@foo@N@taz@S@ClsD#1@x Extent=[50:21 - 50:34]
 // CHECK: usrs.cpp c:@F@rez Extent=[55:3 - 55:25]
 // CHECK: usrs.cpp c:usrs.cpp@941@F@rez@a Extent=[55:12 - 55:17]
 // CHECK: usrs.cpp c:usrs.cpp@948@F@rez@b Extent=[55:19 - 55:24]
@@ -137,10 +153,22 @@
 // CHECK-NOT: ClsB
 // CHECK: usrs.cpp c:@NA@foo_alias3
 // CHECK: usrs.cpp c:@aN Extent=[68:1 - 73:2]
-// CHECK: usrs.cpp c:usrs.cpp@aN@C@RDar9371763_Foo Extent=[69:1 - 72:2]
+// CHECK: usrs.cpp c:usrs.cpp@aN@S@RDar9371763_Foo Extent=[69:1 - 72:2]
 // CHECK: usrs.cpp c: Extent=[70:1 - 70:8]
-// CHECK: usrs.cpp c:usrs.cpp@aN@C@RDar9371763_Foo@F@bar# Extent=[71:3 - 71:13]
-// CHECK: usrs.cpp c:usrs.cpp@aN@C@RDar9371763_Foo@F@bar# Extent=[75:1 - 75:31]
+// CHECK: usrs.cpp c:usrs.cpp@aN@S@RDar9371763_Foo@F@bar# Extent=[71:3 - 71:13]
+// CHECK: usrs.cpp c:usrs.cpp@aN@S@RDar9371763_Foo@F@bar# Extent=[75:1 - 75:31]
 // CHECK: usrs.cpp c:@F@rdar9371763# Extent=[77:1 - 80:2]
 // CHECK: usrs.cpp c:usrs.cpp@1204@F@rdar9371763#@foo Extent=[78:3 - 78:22]
 
+// CHECK: usrs.cpp c:@FT@>1#TsomeTemplFn#^type-parameter-0-0:::A# Extent=[82:1 - 82:50]
+// CHECK: usrs.cpp c:@FT@>1#TsomeTemplFn#^type-parameter-0-0:::B# Extent=[83:1 - 83:50]
+// CHECK: usrs.cpp c:@FT@>1#TsomeTemplFn#I# Extent=[84:1 - 84:40]
+
+// CHECK: usrs.cpp c:@F@funWithChar#C# Extent=[86:1 - 86:28]
+// CHECK: usrs.cpp c:@F@funWithChar#c# Extent=[87:1 - 87:37]
+// CHECK: usrs.cpp c:@F@funWithChar#r# Extent=[88:1 - 88:35]
+
+// CHECK: usrs.cpp c:usrs.cpp@S@usrs.cpp@1483@FI@x Extent=[90:10 - 90:15]
+// CHECK: usrs.cpp c:usrs.cpp@S@usrs.cpp@1510@FI@x Extent=[91:10 - 91:15]
+
+// CHECK: usrs.cpp c:@ST>1#T@TC1@F@meth#>@ST>1#T@TC11t0.0# Extent=[95:3 - 95:17]
diff --git a/test/Layout/ms-x86-pack-and-align.cpp b/test/Layout/ms-x86-pack-and-align.cpp
index 9783233..d766a7d 100644
--- a/test/Layout/ms-x86-pack-and-align.cpp
+++ b/test/Layout/ms-x86-pack-and-align.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple i686-pc-win32 -fdump-record-layouts -fsyntax-only %s 2>&1 \
+// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple i686-pc-win32 -fdump-record-layouts -fsyntax-only -Wno-inaccessible-base %s 2>&1 \
 // RUN:            | FileCheck %s
-// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple x86_64-pc-win32 -fdump-record-layouts -fsyntax-only %s 2>/dev/null \
+// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple x86_64-pc-win32 -fdump-record-layouts -fsyntax-only -Wno-inaccessible-base %s 2>/dev/null \
 // RUN:            | FileCheck %s -check-prefix CHECK-X64
 
 extern "C" int printf(const char *fmt, ...);
diff --git a/test/Lexer/bcpl-escaped-newline.c b/test/Lexer/bcpl-escaped-newline.c
index 05d4773..0883173 100644
--- a/test/Lexer/bcpl-escaped-newline.c
+++ b/test/Lexer/bcpl-escaped-newline.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -Eonly -trigraphs %s
+// RUN: %clang_cc1 -Eonly -ftrigraphs %s
 // RUN: %clang_cc1 -Eonly -verify %s
 
 //\
diff --git a/test/Lexer/block_cmt_end.c b/test/Lexer/block_cmt_end.c
index f54b6a4..1d00137 100644
--- a/test/Lexer/block_cmt_end.c
+++ b/test/Lexer/block_cmt_end.c
@@ -1,9 +1,9 @@
 /*
-  RUN: %clang_cc1 -E -trigraphs %s | grep bar
-  RUN: %clang_cc1 -E -trigraphs %s | grep foo
-  RUN: %clang_cc1 -E -trigraphs %s | not grep qux
-  RUN: %clang_cc1 -E -trigraphs %s | not grep xyz
-  RUN: %clang_cc1 -fsyntax-only -trigraphs -verify %s  
+  RUN: %clang_cc1 -E -ftrigraphs %s | grep bar
+  RUN: %clang_cc1 -E -ftrigraphs %s | grep foo
+  RUN: %clang_cc1 -E -ftrigraphs %s | not grep qux
+  RUN: %clang_cc1 -E -ftrigraphs %s | not grep xyz
+  RUN: %clang_cc1 -fsyntax-only -ftrigraphs -verify %s  
 */
 
 // This is a simple comment, /*/ does not end a comment, the trailing */ does.
diff --git a/test/Lexer/conflict-marker.c b/test/Lexer/conflict-marker.c
index e5bc7f3..2611827 100644
--- a/test/Lexer/conflict-marker.c
+++ b/test/Lexer/conflict-marker.c
@@ -36,3 +36,5 @@
   y a = x;
   return x + a - z;
 }
+
+<<<<<<<>>>>>>> // expected-error {{expected identifier}}
diff --git a/test/Lexer/constants.c b/test/Lexer/constants.c
index 267e75e..9c84ddc 100644
--- a/test/Lexer/constants.c
+++ b/test/Lexer/constants.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -pedantic -trigraphs %s
+// RUN: %clang_cc1 -fsyntax-only -verify -pedantic -ftrigraphs %s
 
 int x = 000000080;  // expected-error {{invalid digit}}
 
diff --git a/test/Lexer/cxx1z-trigraphs.cpp b/test/Lexer/cxx1z-trigraphs.cpp
index 410626f..0ea2adb 100644
--- a/test/Lexer/cxx1z-trigraphs.cpp
+++ b/test/Lexer/cxx1z-trigraphs.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -std=c++1z %s -verify
-// RUN: %clang_cc1 -std=c++1z %s -trigraphs -fsyntax-only
+// RUN: %clang_cc1 -std=c++1z %s -ftrigraphs -fsyntax-only
 
 ??= define foo ; // expected-error {{}} expected-warning {{trigraph ignored}}
 
diff --git a/test/Lexer/escape_newline.c b/test/Lexer/escape_newline.c
index d0f27df..9fc73dc 100644
--- a/test/Lexer/escape_newline.c
+++ b/test/Lexer/escape_newline.c
@@ -1,7 +1,7 @@
-// RUN: %clang_cc1 -E -trigraphs %s | grep -- ' ->'
-// RUN: %clang_cc1 -E -trigraphs %s 2>&1 | grep 'backslash and newline separated by space'
-// RUN: %clang_cc1 -E -trigraphs %s 2>&1 | grep 'trigraph converted'
-// RUN: %clang_cc1 -E -CC -trigraphs %s
+// RUN: %clang_cc1 -E -ftrigraphs %s | grep -- ' ->'
+// RUN: %clang_cc1 -E -ftrigraphs %s 2>&1 | grep 'backslash and newline separated by space'
+// RUN: %clang_cc1 -E -ftrigraphs %s 2>&1 | grep 'trigraph converted'
+// RUN: %clang_cc1 -E -CC -ftrigraphs %s
 
 // This is an ugly way to spell a -> token.
  -??/      
diff --git a/test/Lexer/has_extension.c b/test/Lexer/has_extension.c
index 2ab3d1d..b7efece 100644
--- a/test/Lexer/has_extension.c
+++ b/test/Lexer/has_extension.c
@@ -36,6 +36,14 @@
 int no_c_alignas();
 #endif
 
+// CHECK-PED-NONE: has_c_alignof
+// CHECK-PED-ERR: no_c_alignof
+#if __has_extension(c_alignof)
+int has_c_alignof();
+#else
+int no_c_alignof();
+#endif
+
 // Arbitrary feature to test that the extension name can be surrounded with
 // double underscores.
 // CHECK-PED-NONE: has_double_underscores
diff --git a/test/Lexer/has_feature_c1x.c b/test/Lexer/has_feature_c1x.c
index cba329c..ff17780 100644
--- a/test/Lexer/has_feature_c1x.c
+++ b/test/Lexer/has_feature_c1x.c
@@ -12,7 +12,6 @@
 #else
 int no_atomic();
 #endif
-
 // CHECK-1X: has_atomic
 // CHECK-NO-1X: no_atomic
 
@@ -21,7 +20,6 @@
 #else
 int no_static_assert();
 #endif
-
 // CHECK-1X: has_static_assert
 // CHECK-NO-1X: no_static_assert
 
@@ -30,7 +28,6 @@
 #else
 int no_generic_selections();
 #endif
-
 // CHECK-1X: has_generic_selections
 // CHECK-NO-1X: no_generic_selections
 
@@ -39,10 +36,17 @@
 #else
 int no_alignas();
 #endif
-
 // CHECK-1X: has_alignas
 // CHECK-NO-1X: no_alignas
 
+#if __has_feature(c_alignof)
+int has_alignof();
+#else
+int no_alignof();
+#endif
+// CHECK-1X: has_alignof
+// CHECK-NO-1X: no_alignof
+
 #if __has_feature(c_thread_local)
 int has_thread_local();
 #else
diff --git a/test/Lexer/has_feature_cxx0x.cpp b/test/Lexer/has_feature_cxx0x.cpp
index e558f88..9fb05de 100644
--- a/test/Lexer/has_feature_cxx0x.cpp
+++ b/test/Lexer/has_feature_cxx0x.cpp
@@ -234,6 +234,16 @@
 // CHECK-11: has_alignas
 // CHECK-NO-11: no_alignas
 
+#if __has_feature(cxx_alignof)
+int has_alignof();
+#else
+int no_alignof();
+#endif
+
+// CHECK-1Y: has_alignof
+// CHECK-11: has_alignof
+// CHECK-NO-11: no_alignof
+
 #if __has_feature(cxx_raw_string_literals)
 int has_raw_string_literals();
 #else
diff --git a/test/Lexer/ms-compatibility.c b/test/Lexer/ms-compatibility.c
new file mode 100644
index 0000000..d159ad1
--- /dev/null
+++ b/test/Lexer/ms-compatibility.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -E -fms-compatibility %s | FileCheck --check-prefix=CHECK-MS-COMPAT %s
+// RUN: %clang_cc1 -fsyntax-only -E %s | FileCheck --check-prefix=CHECK-NO-MS-COMPAT %s
+
+#define FN(x) L#x
+#define F L "aaa"
+void *v1 = FN(aaa);
+void *v2 = F;
+// CHECK-MS-COMPAT: void *v1 = L"aaa";
+// CHECK-MS-COMPAT: void *v2 = L "aaa";
+// CHECK-NO-MS-COMPAT: void *v1 = L "aaa";
+// CHECK-NO-MS-COMPAT: void *v2 = L "aaa";
diff --git a/test/Lexer/pragma-operators.cpp b/test/Lexer/pragma-operators.cpp
index 7270f1e..4d288c9 100644
--- a/test/Lexer/pragma-operators.cpp
+++ b/test/Lexer/pragma-operators.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fms-extensions -std=c++11 -E %s | FileCheck %s
+// RUN: %clang_cc1 -fms-extensions -std=c++11 -E %s -fuse-line-directives | FileCheck %s
 
 // Test that we properly expand the C99 _Pragma and Microsoft __pragma
 // into #pragma directives, with newlines where needed. <rdar://problem/8412013>
diff --git a/test/Misc/ast-dump-attr.cpp b/test/Misc/ast-dump-attr.cpp
index 446f0fa..ed6d1f5 100644
--- a/test/Misc/ast-dump-attr.cpp
+++ b/test/Misc/ast-dump-attr.cpp
@@ -79,7 +79,7 @@
 // CHECK:      FunctionDecl{{.*}}TestInt
 // CHECK-NEXT:   ConstructorAttr{{.*}} 123
 
-int TestString __attribute__((alias("alias1")));
+static int TestString __attribute__((alias("alias1")));
 // CHECK:      VarDecl{{.*}}TestString
 // CHECK-NEXT:   AliasAttr{{.*}} "alias1"
 
diff --git a/test/Misc/ast-dump-color.cpp b/test/Misc/ast-dump-color.cpp
index db4dc2b..479467d 100644
--- a/test/Misc/ast-dump-color.cpp
+++ b/test/Misc/ast-dump-color.cpp
@@ -77,9 +77,9 @@
 //CHECK: {{^}}[[Blue]]| |     `-[[RESET]][[Blue]]TextComment[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:6[[RESET]], [[Yellow]]col:44[[RESET]]> Text=" Like the other variable, but different"{{$}}
 //CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:18:33[[RESET]]> [[Yellow]]col:33[[RESET]] implicit used[[CYAN]] Mutex[[RESET]] [[Green]]'void (void) noexcept'[[RESET]] inline{{.*$}}
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[MAGENTA]]CompoundStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]>{{$}}
-//CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]> [[Yellow]]col:33[[RESET]] implicit[[CYAN]] Mutex[[RESET]] [[Green]]'void (const class Mutex &)'[[RESET]] inline{{ .*$}}
+//CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]> [[Yellow]]col:33[[RESET]] implicit constexpr[[CYAN]] Mutex[[RESET]] [[Green]]'void (const class Mutex &)'[[RESET]] inline{{ .*$}}
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[GREEN]]ParmVarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]> [[Yellow]]col:33[[RESET]] [[Green]]'const class Mutex &'[[RESET]]{{$}}
-//CHECK: {{^}}[[Blue]]| `-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]> [[Yellow]]col:33[[RESET]] implicit[[CYAN]] Mutex[[RESET]] [[Green]]'void (class Mutex &&)'[[RESET]] inline{{ .*$}}
+//CHECK: {{^}}[[Blue]]| `-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]> [[Yellow]]col:33[[RESET]] implicit constexpr[[CYAN]] Mutex[[RESET]] [[Green]]'void (class Mutex &&)'[[RESET]] inline{{ .*$}}
 //CHECK: {{^}}[[Blue]]|   `-[[RESET]][[GREEN]]ParmVarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:33[[RESET]]> [[Yellow]]col:33[[RESET]] [[Green]]'class Mutex &&'[[RESET]]{{$}}
 //CHECK: {{^}}[[Blue]]|-[[RESET]][[GREEN]]VarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:1[[RESET]], [[Yellow]]line:25:3[[RESET]]> [[Yellow]]col:3[[RESET]] referenced[[CYAN]] mu1[[RESET]] [[Green]]'class Mutex':'class Mutex'[[RESET]]
 //CHECK: {{^}}[[Blue]]| `-[[RESET]][[MAGENTA]]CXXConstructExpr[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:3[[RESET]]> [[Green]]'class Mutex':'class Mutex'[[RESET]][[Cyan]][[RESET]][[Cyan]][[RESET]] [[Green]]'void (void) noexcept'[[RESET]]{{$}}
@@ -93,11 +93,11 @@
 //CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:29:3[[RESET]], [[Yellow]]col:42[[RESET]]> [[Yellow]]col:29[[RESET]] invalid[[CYAN]] Invalid[[RESET]] [[Green]]'void (int)'[[RESET]]
 //CHECK: {{^}}[[Blue]]| | |-[[RESET]][[GREEN]]ParmVarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:37[[RESET]], [[Yellow]]<invalid sloc>[[RESET]]> [[Yellow]]col:42[[RESET]] invalid [[Green]]'int'[[RESET]]
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[BLUE]]NoInlineAttr[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:18[[RESET]]>
-//CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:28:8[[RESET]]> [[Yellow]]col:8[[RESET]] implicit used[[CYAN]] Invalid[[RESET]] [[Green]]'void (void) noexcept'[[RESET]] inline
+//CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]line:28:8[[RESET]]> [[Yellow]]col:8[[RESET]] implicit used constexpr[[CYAN]] Invalid[[RESET]] [[Green]]'void (void) noexcept'[[RESET]] inline
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[MAGENTA]]CompoundStmt[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]>
-//CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]> [[Yellow]]col:8[[RESET]] implicit[[CYAN]] Invalid[[RESET]] [[Green]]'void (const struct Invalid &)'[[RESET]] inline noexcept-unevaluated 0x{{[0-9a-fA-F]*}}
+//CHECK: {{^}}[[Blue]]| |-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]> [[Yellow]]col:8[[RESET]] implicit constexpr[[CYAN]] Invalid[[RESET]] [[Green]]'void (const struct Invalid &)'[[RESET]] inline noexcept-unevaluated 0x{{[0-9a-fA-F]*}}
 //CHECK: {{^}}[[Blue]]| | `-[[RESET]][[GREEN]]ParmVarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]> [[Yellow]]col:8[[RESET]] [[Green]]'const struct Invalid &'[[RESET]]
-//CHECK: {{^}}[[Blue]]| `-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]> [[Yellow]]col:8[[RESET]] implicit[[CYAN]] Invalid[[RESET]] [[Green]]'void (struct Invalid &&)'[[RESET]] inline noexcept-unevaluated 0x{{[0-9a-fA-F]*}}
+//CHECK: {{^}}[[Blue]]| `-[[RESET]][[GREEN]]CXXConstructorDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]> [[Yellow]]col:8[[RESET]] implicit constexpr[[CYAN]] Invalid[[RESET]] [[Green]]'void (struct Invalid &&)'[[RESET]] inline noexcept-unevaluated 0x{{[0-9a-fA-F]*}}
 //CHECK: {{^}}[[Blue]]|   `-[[RESET]][[GREEN]]ParmVarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:8[[RESET]]> [[Yellow]]col:8[[RESET]] [[Green]]'struct Invalid &&'[[RESET]]
 //CHECK: {{^}}[[Blue]]`-[[RESET]][[GREEN]]VarDecl[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:1[[RESET]], [[Yellow]]line:30:3[[RESET]]> [[Yellow]]col:3[[RESET]][[CYAN]] Invalid[[RESET]] [[Green]]'struct Invalid':'struct Invalid'[[RESET]]
 //CHECK: {{^}}[[Blue]]  `-[[RESET]][[MAGENTA]]CXXConstructExpr[[RESET]][[Yellow]] 0x{{[0-9a-fA-F]*}}[[RESET]] <[[Yellow]]col:3[[RESET]]> [[Green]]'struct Invalid':'struct Invalid'[[RESET]][[Cyan]][[RESET]][[Cyan]][[RESET]] [[Green]]'void (void) noexcept'[[RESET]]
diff --git a/test/Misc/ast-dump-invalid.cpp b/test/Misc/ast-dump-invalid.cpp
new file mode 100644
index 0000000..3b97cc6
--- /dev/null
+++ b/test/Misc/ast-dump-invalid.cpp
@@ -0,0 +1,20 @@
+// RUN: not %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -fms-extensions -ast-dump -ast-dump-filter Test %s | FileCheck -check-prefix CHECK -strict-whitespace %s
+
+namespace TestInvalidRParenOnCXXUnresolvedConstructExpr {
+template <class T>
+void f(T i, T j) {
+  return T (i, j;
+}
+}
+
+// CHECK: NamespaceDecl {{.*}} <{{.*}}> {{.*}} TestInvalidRParenOnCXXUnresolvedConstructExpr
+// CHECK-NEXT: `-FunctionTemplateDecl
+// CHECK-NEXT:   |-TemplateTypeParmDecl
+// CHECK-NEXT:   `-FunctionDecl
+// CHECK-NEXT:     |-ParmVarDecl
+// CHECK-NEXT:     |-ParmVarDecl
+// CHECK-NEXT:     `-CompoundStmt
+// CHECK-NEXT:       `-ReturnStmt
+// CHECK-NEXT:         `-CXXUnresolvedConstructExpr {{.*}} <col:10, col:16> 'T'
+// CHECK-NEXT:           |-DeclRefExpr {{.*}} <col:13> 'T' lvalue ParmVar {{.*}} 'i' 'T'
+// CHECK-NEXT:           `-DeclRefExpr {{.*}} <col:16> 'T' lvalue ParmVar {{.*}} 'j' 'T'
diff --git a/test/Misc/diag-special-chars.c b/test/Misc/diag-special-chars.c
new file mode 100644
index 0000000..e656a09
--- /dev/null
+++ b/test/Misc/diag-special-chars.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 %s -verify
+// RUN: not %clang_cc1 %s 2>&1 | FileCheck %s
+
+// There is a special characters on the following line, which is used as a
+// marker character for diagnostic printing.  Ensure diagnostics involving
+// this character does not cause problems with the diagnostic printer.
+#error Hi  Bye
+//expected-error@-1 {{Hi  Bye}}
+
+// CHECK: error: Hi  Bye
+// CHECK: #error Hi <U+007F> Bye
diff --git a/test/Misc/diag-template-diffing.cpp b/test/Misc/diag-template-diffing.cpp
index bdd6d62..0f2edfb 100644
--- a/test/Misc/diag-template-diffing.cpp
+++ b/test/Misc/diag-template-diffing.cpp
@@ -1247,6 +1247,33 @@
 // CHECK-ELIDE-NOTREE: type alias template redefinition with different types ('A<(T::num), (default) 0>' vs 'A<T::num, 1>')
 }
 
+namespace TemplateArgumentImplicitConversion {
+template <int X> struct condition {};
+
+struct is_const {
+    constexpr operator int() const { return 10; }
+};
+
+using T = condition<(is_const())>;
+void foo(const T &t) {
+  T &t2 = t;
+}
+// CHECK-ELIDE-NOTREE: binding of reference to type 'condition<[...]>' to a value of type 'const condition<[...]>' drops qualifiers
+}
+
+namespace BoolArgumentBitExtended {
+template <bool B> struct BoolT {};
+
+template <typename T> void foo(T) {}
+
+void test() {
+  BoolT<false> X;
+  foo<BoolT<true>>(X);
+}
+// CHECK-ELIDE-NOTREE: no matching function for call to 'foo'
+// CHECK-ELIDE-NOTREE: candidate function [with T = BoolArgumentBitExtended::BoolT<true>] not viable: no known conversion from 'BoolT<0>' to 'BoolT<1>' for 1st argument
+}
+
 // CHECK-ELIDE-NOTREE: {{[0-9]*}} errors generated.
 // CHECK-NOELIDE-NOTREE: {{[0-9]*}} errors generated.
 // CHECK-ELIDE-TREE: {{[0-9]*}} errors generated.
diff --git a/test/Misc/warning-flags.c b/test/Misc/warning-flags.c
index 2afa88f..657b44d 100644
--- a/test/Misc/warning-flags.c
+++ b/test/Misc/warning-flags.c
@@ -18,14 +18,13 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (98):
+CHECK: Warnings without flags (94):
 CHECK-NEXT:   ext_excess_initializers
 CHECK-NEXT:   ext_excess_initializers_in_char_array_initializer
 CHECK-NEXT:   ext_expected_semi_decl_list
 CHECK-NEXT:   ext_explicit_specialization_storage_class
 CHECK-NEXT:   ext_implicit_lib_function_decl
 CHECK-NEXT:   ext_initializer_string_for_char_array_too_long
-CHECK-NEXT:   ext_many_braces_around_scalar_init
 CHECK-NEXT:   ext_missing_declspec
 CHECK-NEXT:   ext_missing_whitespace_after_macro_name
 CHECK-NEXT:   ext_new_paren_array_nonconst
@@ -50,7 +49,6 @@
 CHECK-NEXT:   warn_arcmt_nsalloc_realloc
 CHECK-NEXT:   warn_asm_label_on_auto_decl
 CHECK-NEXT:   warn_bitfield_width_exceeds_type_size
-CHECK-NEXT:   warn_braces_around_scalar_init
 CHECK-NEXT:   warn_c_kext
 CHECK-NEXT:   warn_call_to_pure_virtual_member_function_from_ctor_dtor
 CHECK-NEXT:   warn_call_wrong_number_of_arguments
@@ -89,7 +87,6 @@
 CHECK-NEXT:   warn_missing_exception_specification
 CHECK-NEXT:   warn_missing_whitespace_after_macro_name
 CHECK-NEXT:   warn_mt_message
-CHECK-NEXT:   warn_multiple_method_decl
 CHECK-NEXT:   warn_no_constructor_for_refconst
 CHECK-NEXT:   warn_not_compound_assign
 CHECK-NEXT:   warn_objc_property_copy_missing_on_block
@@ -103,7 +100,6 @@
 CHECK-NEXT:   warn_pragma_pack_pop_identifer_and_alignment
 CHECK-NEXT:   warn_pragma_pack_show
 CHECK-NEXT:   warn_property_getter_owning_mismatch
-CHECK-NEXT:   warn_readonly_property
 CHECK-NEXT:   warn_register_objc_catch_parm
 CHECK-NEXT:   warn_related_result_type_compatibility_class
 CHECK-NEXT:   warn_related_result_type_compatibility_protocol
diff --git a/test/Modules/Inputs/DependsOnModule.framework/module.map b/test/Modules/Inputs/DependsOnModule.framework/module.map
index 5a1caca..b623085 100644
--- a/test/Modules/Inputs/DependsOnModule.framework/module.map
+++ b/test/Modules/Inputs/DependsOnModule.framework/module.map
@@ -16,6 +16,12 @@
     requires !objc
     header "not_objc.h"
   }
+  explicit module CustomReq1 {
+    requires custom_req1
+  }
+  explicit module CustomReq2 {
+    requires custom_req2
+  }
 
   explicit framework module SubFramework {
     umbrella header "SubFramework.h"
diff --git a/test/Modules/Inputs/ModuleMapLocations/Both_F.framework/Headers/a.h b/test/Modules/Inputs/ModuleMapLocations/Both_F.framework/Headers/a.h
index 9dabfc0..aa47ef4 100644
--- a/test/Modules/Inputs/ModuleMapLocations/Both_F.framework/Headers/a.h
+++ b/test/Modules/Inputs/ModuleMapLocations/Both_F.framework/Headers/a.h
@@ -1 +1,2 @@
+@import Module; // Don't cause redefinition error.
 void will_be_found2(void);
diff --git a/test/Modules/macro-reexport/a2.h b/test/Modules/Inputs/System/usr/include/malloc.h
similarity index 100%
copy from test/Modules/macro-reexport/a2.h
copy to test/Modules/Inputs/System/usr/include/malloc.h
diff --git a/test/Modules/Inputs/System/usr/include/stdlib.h b/test/Modules/Inputs/System/usr/include/stdlib.h
new file mode 100644
index 0000000..a1bf1a8
--- /dev/null
+++ b/test/Modules/Inputs/System/usr/include/stdlib.h
@@ -0,0 +1 @@
+typedef __SIZE_TYPE__ size_t;
diff --git a/test/Modules/Inputs/attr-unavailable/module.modulemap b/test/Modules/Inputs/attr-unavailable/module.modulemap
new file mode 100644
index 0000000..a515942
--- /dev/null
+++ b/test/Modules/Inputs/attr-unavailable/module.modulemap
@@ -0,0 +1,4 @@
+module two { header "two.h" }
+module oneA { header "oneA.h" }
+module oneB { header "oneB.h" export oneA }
+module oneC { header "oneC.h" }
diff --git a/test/Modules/Inputs/attr-unavailable/oneA.h b/test/Modules/Inputs/attr-unavailable/oneA.h
new file mode 100644
index 0000000..a4e572f
--- /dev/null
+++ b/test/Modules/Inputs/attr-unavailable/oneA.h
@@ -0,0 +1,4 @@
+@interface C
+-(void)method2 __attribute__((unavailable));
+-(void)method3 __attribute__((unavailable));
+@end
diff --git a/test/Modules/Inputs/attr-unavailable/oneB.h b/test/Modules/Inputs/attr-unavailable/oneB.h
new file mode 100644
index 0000000..b9536ad
--- /dev/null
+++ b/test/Modules/Inputs/attr-unavailable/oneB.h
@@ -0,0 +1,5 @@
+@import oneA;
+
+@interface D
+-(void)method2;
+@end
diff --git a/test/Modules/Inputs/attr-unavailable/oneC.h b/test/Modules/Inputs/attr-unavailable/oneC.h
new file mode 100644
index 0000000..9dc305e
--- /dev/null
+++ b/test/Modules/Inputs/attr-unavailable/oneC.h
@@ -0,0 +1,3 @@
+@interface E
+-(void)method3;
+@end
diff --git a/test/Modules/Inputs/attr-unavailable/two.h b/test/Modules/Inputs/attr-unavailable/two.h
new file mode 100644
index 0000000..0423f61
--- /dev/null
+++ b/test/Modules/Inputs/attr-unavailable/two.h
@@ -0,0 +1,6 @@
+@interface A
+-(void)method1;
+@end
+@interface B
+-(void)method1 __attribute__((unavailable));
+@end
diff --git a/test/Modules/Inputs/cxx-lookup/module.modulemap b/test/Modules/Inputs/cxx-lookup/module.modulemap
index 6d397af..385c8c9 100644
--- a/test/Modules/Inputs/cxx-lookup/module.modulemap
+++ b/test/Modules/Inputs/cxx-lookup/module.modulemap
@@ -6,3 +6,5 @@
 }
 module X { header "x.h" export * }
 module Y { header "y.h" export * }
+module na { header "na.h" export * }
+module nb { header "nb.h" export * }
diff --git a/test/Modules/Inputs/cxx-lookup/na.h b/test/Modules/Inputs/cxx-lookup/na.h
new file mode 100644
index 0000000..684d37e
--- /dev/null
+++ b/test/Modules/Inputs/cxx-lookup/na.h
@@ -0,0 +1 @@
+namespace N { struct S { friend struct foo; }; }
diff --git a/test/Modules/Inputs/cxx-lookup/nb.h b/test/Modules/Inputs/cxx-lookup/nb.h
new file mode 100644
index 0000000..092c882
--- /dev/null
+++ b/test/Modules/Inputs/cxx-lookup/nb.h
@@ -0,0 +1 @@
+namespace N { extern int n; }
diff --git a/test/Modules/Inputs/deferred-lookup/a.h b/test/Modules/Inputs/deferred-lookup/a.h
new file mode 100644
index 0000000..751aae0
--- /dev/null
+++ b/test/Modules/Inputs/deferred-lookup/a.h
@@ -0,0 +1 @@
+namespace N { int f(int); }
diff --git a/test/Modules/Inputs/deferred-lookup/b.h b/test/Modules/Inputs/deferred-lookup/b.h
new file mode 100644
index 0000000..23925e2
--- /dev/null
+++ b/test/Modules/Inputs/deferred-lookup/b.h
@@ -0,0 +1,6 @@
+namespace N { template<typename T> struct A { friend int f(A); }; }
+namespace N { int f(int); }
+namespace N { int f(int); }
+#include "a.h"
+namespace N { int f(int); }
+inline int g() { return f(N::A<int>()); }
diff --git a/test/Modules/Inputs/deferred-lookup/module.modulemap b/test/Modules/Inputs/deferred-lookup/module.modulemap
new file mode 100644
index 0000000..61578a1
--- /dev/null
+++ b/test/Modules/Inputs/deferred-lookup/module.modulemap
@@ -0,0 +1,2 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
diff --git a/test/Modules/Inputs/dependency-gen-base.modulemap b/test/Modules/Inputs/dependency-gen-base.modulemap
new file mode 100644
index 0000000..8b30ffa
--- /dev/null
+++ b/test/Modules/Inputs/dependency-gen-base.modulemap
@@ -0,0 +1,6 @@
+module "test-base" {
+  export *
+  header "Inputs/dependency-gen-included.h"
+  use "test-base2"
+}
+extern module "test-base2" "Inputs/dependency-gen-base2.modulemap"
diff --git a/test/Modules/Inputs/dependency-gen-base2.modulemap b/test/Modules/Inputs/dependency-gen-base2.modulemap
new file mode 100644
index 0000000..7808c80
--- /dev/null
+++ b/test/Modules/Inputs/dependency-gen-base2.modulemap
@@ -0,0 +1,4 @@
+module "test-base2" {
+  export *
+  textual header "Inputs/dependency-gen-included2.h"
+}
diff --git a/test/Modules/Inputs/dependency-gen-included.h b/test/Modules/Inputs/dependency-gen-included.h
new file mode 100644
index 0000000..0e1cdfc
--- /dev/null
+++ b/test/Modules/Inputs/dependency-gen-included.h
@@ -0,0 +1,9 @@
+//#ifndef DEPENDENCY_GEN_INCLUDED_H
+//#define DEPENDENCY_GEN_INCLUDED_H
+
+#include "Inputs/dependency-gen-included2.h"
+
+void g() {
+}
+
+//#endif
diff --git a/test/Modules/Inputs/dependency-gen-included2.h b/test/Modules/Inputs/dependency-gen-included2.h
new file mode 100644
index 0000000..fcd8f12
--- /dev/null
+++ b/test/Modules/Inputs/dependency-gen-included2.h
@@ -0,0 +1,7 @@
+#ifndef DEPENDENCY_GEN_INCLUDED2_H
+#define DEPENDENCY_GEN_INCLUDED2_H
+
+void h() {
+}
+
+#endif
diff --git a/test/Modules/Inputs/dependency-gen.h b/test/Modules/Inputs/dependency-gen.h
new file mode 100644
index 0000000..2671e26
--- /dev/null
+++ b/test/Modules/Inputs/dependency-gen.h
@@ -0,0 +1,11 @@
+//#ifndef DEPENDENCY_GEN_H
+//#define DEPENDENCY_GEN_H
+
+#include "dependency-gen-included.h"
+
+void f() {
+  g();
+  h();
+}
+
+//#endif
diff --git a/test/Modules/Inputs/header-in-multiple-maps/a.h b/test/Modules/Inputs/header-in-multiple-maps/a.h
new file mode 100644
index 0000000..4c5cd94
--- /dev/null
+++ b/test/Modules/Inputs/header-in-multiple-maps/a.h
@@ -0,0 +1 @@
+struct A {};
diff --git a/test/Modules/Inputs/header-in-multiple-maps/map1 b/test/Modules/Inputs/header-in-multiple-maps/map1
new file mode 100644
index 0000000..ba9baac
--- /dev/null
+++ b/test/Modules/Inputs/header-in-multiple-maps/map1
@@ -0,0 +1,3 @@
+module a { header "a.h" }
+module b { header "a.h" }
+module c { textual header "a.h" }
diff --git a/test/Modules/Inputs/header-in-multiple-maps/map2 b/test/Modules/Inputs/header-in-multiple-maps/map2
new file mode 100644
index 0000000..67e0df3
--- /dev/null
+++ b/test/Modules/Inputs/header-in-multiple-maps/map2
@@ -0,0 +1,3 @@
+module a { textual header "a.h" }
+module b { header "a.h" }
+module c { header "a.h" }
diff --git a/test/Modules/Inputs/header-in-multiple-maps/map3 b/test/Modules/Inputs/header-in-multiple-maps/map3
new file mode 100644
index 0000000..c859fd7
--- /dev/null
+++ b/test/Modules/Inputs/header-in-multiple-maps/map3
@@ -0,0 +1,3 @@
+module a { header "a.h" }
+module b { textual header "a.h" }
+module c { header "a.h" }
diff --git a/test/Modules/Inputs/inferred-attr/InferredExternC.framework/Headers/InferredExternC.h b/test/Modules/Inputs/inferred-attr/InferredExternC.framework/Headers/InferredExternC.h
new file mode 100644
index 0000000..63242fa
--- /dev/null
+++ b/test/Modules/Inputs/inferred-attr/InferredExternC.framework/Headers/InferredExternC.h
@@ -0,0 +1 @@
+// InferredExternC.h
diff --git a/test/Modules/Inputs/inferred-attr/module.modulemap b/test/Modules/Inputs/inferred-attr/module.modulemap
new file mode 100644
index 0000000..beb6ea1
--- /dev/null
+++ b/test/Modules/Inputs/inferred-attr/module.modulemap
@@ -0,0 +1 @@
+framework module * [extern_c] { }
diff --git a/test/Modules/Inputs/initializer_list b/test/Modules/Inputs/initializer_list/direct.h
similarity index 100%
rename from test/Modules/Inputs/initializer_list
rename to test/Modules/Inputs/initializer_list/direct.h
diff --git a/test/Modules/Inputs/initializer_list/direct.modulemap b/test/Modules/Inputs/initializer_list/direct.modulemap
new file mode 100644
index 0000000..56a4100
--- /dev/null
+++ b/test/Modules/Inputs/initializer_list/direct.modulemap
@@ -0,0 +1 @@
+module initializer_list { header "direct.h" }
diff --git a/test/Modules/Inputs/initializer_list/indirect.h b/test/Modules/Inputs/initializer_list/indirect.h
new file mode 100644
index 0000000..75e9817
--- /dev/null
+++ b/test/Modules/Inputs/initializer_list/indirect.h
@@ -0,0 +1 @@
+#include "direct.h"
diff --git a/test/Modules/Inputs/initializer_list/indirect.modulemap b/test/Modules/Inputs/initializer_list/indirect.modulemap
new file mode 100644
index 0000000..14deacf
--- /dev/null
+++ b/test/Modules/Inputs/initializer_list/indirect.modulemap
@@ -0,0 +1 @@
+module initializer_list { header "indirect.h" }
diff --git a/test/Modules/macro-reexport/a1.h b/test/Modules/Inputs/macro-reexport/a1.h
similarity index 100%
rename from test/Modules/macro-reexport/a1.h
rename to test/Modules/Inputs/macro-reexport/a1.h
diff --git a/test/Modules/macro-reexport/a2.h b/test/Modules/Inputs/macro-reexport/a2.h
similarity index 100%
rename from test/Modules/macro-reexport/a2.h
rename to test/Modules/Inputs/macro-reexport/a2.h
diff --git a/test/Modules/macro-reexport/b1.h b/test/Modules/Inputs/macro-reexport/b1.h
similarity index 100%
rename from test/Modules/macro-reexport/b1.h
rename to test/Modules/Inputs/macro-reexport/b1.h
diff --git a/test/Modules/macro-reexport/b2.h b/test/Modules/Inputs/macro-reexport/b2.h
similarity index 100%
rename from test/Modules/macro-reexport/b2.h
rename to test/Modules/Inputs/macro-reexport/b2.h
diff --git a/test/Modules/macro-reexport/c1.h b/test/Modules/Inputs/macro-reexport/c1.h
similarity index 100%
rename from test/Modules/macro-reexport/c1.h
rename to test/Modules/Inputs/macro-reexport/c1.h
diff --git a/test/Modules/macro-reexport/d1.h b/test/Modules/Inputs/macro-reexport/d1.h
similarity index 100%
rename from test/Modules/macro-reexport/d1.h
rename to test/Modules/Inputs/macro-reexport/d1.h
diff --git a/test/Modules/macro-reexport/d2.h b/test/Modules/Inputs/macro-reexport/d2.h
similarity index 100%
rename from test/Modules/macro-reexport/d2.h
rename to test/Modules/Inputs/macro-reexport/d2.h
diff --git a/test/Modules/macro-reexport/e1.h b/test/Modules/Inputs/macro-reexport/e1.h
similarity index 100%
rename from test/Modules/macro-reexport/e1.h
rename to test/Modules/Inputs/macro-reexport/e1.h
diff --git a/test/Modules/macro-reexport/e2.h b/test/Modules/Inputs/macro-reexport/e2.h
similarity index 100%
rename from test/Modules/macro-reexport/e2.h
rename to test/Modules/Inputs/macro-reexport/e2.h
diff --git a/test/Modules/macro-reexport/f1.h b/test/Modules/Inputs/macro-reexport/f1.h
similarity index 100%
rename from test/Modules/macro-reexport/f1.h
rename to test/Modules/Inputs/macro-reexport/f1.h
diff --git a/test/Modules/macro-reexport/module.modulemap b/test/Modules/Inputs/macro-reexport/module.modulemap
similarity index 100%
rename from test/Modules/macro-reexport/module.modulemap
rename to test/Modules/Inputs/macro-reexport/module.modulemap
diff --git a/test/Modules/Inputs/malformed/c.h b/test/Modules/Inputs/malformed/c.h
new file mode 100644
index 0000000..2cce2ca
--- /dev/null
+++ b/test/Modules/Inputs/malformed/c.h
@@ -0,0 +1 @@
+template<typename T> void f() { T::error; }
diff --git a/test/Modules/Inputs/malformed/module.map b/test/Modules/Inputs/malformed/module.map
index 5277ffa..3f088d1 100644
--- a/test/Modules/Inputs/malformed/module.map
+++ b/test/Modules/Inputs/malformed/module.map
@@ -6,3 +6,4 @@
   module b1 { header "b1.h" }
   module b2 { header "b2.h" }
 }
+module c { header "c.h" }
diff --git a/test/Modules/Inputs/merge-anon-in-template/a.h b/test/Modules/Inputs/merge-anon-in-template/a.h
new file mode 100644
index 0000000..82540e3
--- /dev/null
+++ b/test/Modules/Inputs/merge-anon-in-template/a.h
@@ -0,0 +1,4 @@
+template<typename T> struct is_floating {
+  enum { value = 0 };
+  typedef int type;
+};
diff --git a/test/Modules/Inputs/merge-anon-in-template/b.h b/test/Modules/Inputs/merge-anon-in-template/b.h
new file mode 100644
index 0000000..87c053d
--- /dev/null
+++ b/test/Modules/Inputs/merge-anon-in-template/b.h
@@ -0,0 +1,2 @@
+#include "a.h"
+bool k = is_floating<int>::value;
diff --git a/test/Modules/Inputs/merge-anon-in-template/c.h b/test/Modules/Inputs/merge-anon-in-template/c.h
new file mode 100644
index 0000000..e0b9b0a
--- /dev/null
+++ b/test/Modules/Inputs/merge-anon-in-template/c.h
@@ -0,0 +1,6 @@
+template<typename T> struct is_floating {
+  enum { value = 0 };
+  typedef int type;
+};
+#include "b.h"
+bool n20 = is_floating<int>::value;
diff --git a/test/Modules/Inputs/merge-anon-in-template/module.modulemap b/test/Modules/Inputs/merge-anon-in-template/module.modulemap
new file mode 100644
index 0000000..77e0a89
--- /dev/null
+++ b/test/Modules/Inputs/merge-anon-in-template/module.modulemap
@@ -0,0 +1,3 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
+module c { header "c.h" export * }
diff --git a/test/Modules/Inputs/merge-decl-context/a.h b/test/Modules/Inputs/merge-decl-context/a.h
new file mode 100644
index 0000000..bd08eca
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-context/a.h
@@ -0,0 +1,22 @@
+#ifndef A_H
+#define A_H
+
+template <typename T>
+struct A {
+  template <typename I>
+  A(I i1, I i2) {
+  }
+  A(double) {}
+  A(double, double) {}
+};
+
+template <typename T1, typename T2>
+T1 fff(T2* t) {
+  return T1(t, t);
+}
+
+inline A<int> ff(int i) {
+  return fff<A<int>>(&i);
+}
+
+#endif
diff --git a/test/Modules/Inputs/merge-decl-context/b.h b/test/Modules/Inputs/merge-decl-context/b.h
new file mode 100644
index 0000000..cb06ac8
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-context/b.h
@@ -0,0 +1,6 @@
+#ifndef B_H
+#define B_H
+
+#include "a.h"
+
+#endif
diff --git a/test/Modules/Inputs/merge-decl-context/c.h b/test/Modules/Inputs/merge-decl-context/c.h
new file mode 100644
index 0000000..af3a723
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-context/c.h
@@ -0,0 +1,7 @@
+#ifndef C_H
+#define C_H
+
+#include "a.h"
+#include "b.h"
+
+#endif
diff --git a/test/Modules/Inputs/merge-decl-context/merge-decl-context.modulemap b/test/Modules/Inputs/merge-decl-context/merge-decl-context.modulemap
new file mode 100644
index 0000000..fedc5df
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-context/merge-decl-context.modulemap
@@ -0,0 +1,13 @@
+module "a" {
+  textual header "a.h"
+}
+
+module "b" {
+  export *
+  header "b.h"
+}
+
+module "c" {
+  export *
+  header "c.h"
+}
diff --git a/test/Modules/Inputs/merge-decl-order/a.h b/test/Modules/Inputs/merge-decl-order/a.h
new file mode 100644
index 0000000..f505a42
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-order/a.h
@@ -0,0 +1,2 @@
+namespace N { struct SA { friend struct foo; }; }
+namespace N { struct foo; }
diff --git a/test/Modules/Inputs/merge-decl-order/b.h b/test/Modules/Inputs/merge-decl-order/b.h
new file mode 100644
index 0000000..49b06ca
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-order/b.h
@@ -0,0 +1,2 @@
+namespace N { struct SB { friend struct foo; }; }
+#include "a.h"
diff --git a/test/Modules/Inputs/merge-decl-order/module.modulemap b/test/Modules/Inputs/merge-decl-order/module.modulemap
new file mode 100644
index 0000000..61578a1
--- /dev/null
+++ b/test/Modules/Inputs/merge-decl-order/module.modulemap
@@ -0,0 +1,2 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
diff --git a/test/Modules/Inputs/merge-dependent-friends/a.h b/test/Modules/Inputs/merge-dependent-friends/a.h
new file mode 100644
index 0000000..44b1c1d
--- /dev/null
+++ b/test/Modules/Inputs/merge-dependent-friends/a.h
@@ -0,0 +1,2 @@
+namespace N { template<typename T> struct A { friend int f(A); }; }
+int a = f(N::A<int>());
diff --git a/test/Modules/Inputs/merge-dependent-friends/b.h b/test/Modules/Inputs/merge-dependent-friends/b.h
new file mode 100644
index 0000000..bce3387
--- /dev/null
+++ b/test/Modules/Inputs/merge-dependent-friends/b.h
@@ -0,0 +1,2 @@
+namespace N { template<typename T> struct A { friend int f(A); }; }
+int b = f(N::A<int>());
diff --git a/test/Modules/Inputs/merge-dependent-friends/c.h b/test/Modules/Inputs/merge-dependent-friends/c.h
new file mode 100644
index 0000000..3620ce3
--- /dev/null
+++ b/test/Modules/Inputs/merge-dependent-friends/c.h
@@ -0,0 +1,6 @@
+namespace N { template<typename T> struct A { friend int f(A); }; }
+// It would seem like this variable should be called 'c'.
+// But that makes the original problem disappear...
+int e = f(N::A<int>());
+#include "a.h"
+#include "b.h"
diff --git a/test/Modules/Inputs/merge-dependent-friends/d.h b/test/Modules/Inputs/merge-dependent-friends/d.h
new file mode 100644
index 0000000..ce3f69f
--- /dev/null
+++ b/test/Modules/Inputs/merge-dependent-friends/d.h
@@ -0,0 +1,2 @@
+namespace N { template<typename T> struct A { friend int f(A); }; }
+#include "c.h"
diff --git a/test/Modules/Inputs/merge-dependent-friends/module.modulemap b/test/Modules/Inputs/merge-dependent-friends/module.modulemap
new file mode 100644
index 0000000..73a7c41
--- /dev/null
+++ b/test/Modules/Inputs/merge-dependent-friends/module.modulemap
@@ -0,0 +1,4 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
+module c { header "c.h" export * }
+module d { header "d.h" export * }
diff --git a/test/Modules/Inputs/merge-friends/decl.h b/test/Modules/Inputs/merge-friends/decl.h
new file mode 100644
index 0000000..f658f94
--- /dev/null
+++ b/test/Modules/Inputs/merge-friends/decl.h
@@ -0,0 +1 @@
+namespace N { struct foo; }
diff --git a/test/Modules/Inputs/merge-friends/friend.h b/test/Modules/Inputs/merge-friends/friend.h
new file mode 100644
index 0000000..bbbd8ed
--- /dev/null
+++ b/test/Modules/Inputs/merge-friends/friend.h
@@ -0,0 +1,2 @@
+namespace N { struct n8 { friend struct foo; }; }
+#include "decl.h"
diff --git a/test/Modules/Inputs/merge-friends/module.modulemap b/test/Modules/Inputs/merge-friends/module.modulemap
new file mode 100644
index 0000000..1fa52c9
--- /dev/null
+++ b/test/Modules/Inputs/merge-friends/module.modulemap
@@ -0,0 +1,2 @@
+module decl { header "decl.h" export * }
+module friend { header "friend.h" export * }
diff --git a/test/Modules/Inputs/merge-implicit-special-members/a.h b/test/Modules/Inputs/merge-implicit-special-members/a.h
new file mode 100644
index 0000000..3029e4a
--- /dev/null
+++ b/test/Modules/Inputs/merge-implicit-special-members/a.h
@@ -0,0 +1 @@
+struct pthread_mutex_t { int lock; };
diff --git a/test/Modules/Inputs/merge-implicit-special-members/b.h b/test/Modules/Inputs/merge-implicit-special-members/b.h
new file mode 100644
index 0000000..3029e4a
--- /dev/null
+++ b/test/Modules/Inputs/merge-implicit-special-members/b.h
@@ -0,0 +1 @@
+struct pthread_mutex_t { int lock; };
diff --git a/test/Modules/Inputs/merge-implicit-special-members/c.h b/test/Modules/Inputs/merge-implicit-special-members/c.h
new file mode 100644
index 0000000..ee0bebb
--- /dev/null
+++ b/test/Modules/Inputs/merge-implicit-special-members/c.h
@@ -0,0 +1,3 @@
+#include "a.h"
+#include "b.h"
+int k = pthread_mutex_t().lock;
diff --git a/test/Modules/Inputs/merge-implicit-special-members/module.modulemap b/test/Modules/Inputs/merge-implicit-special-members/module.modulemap
new file mode 100644
index 0000000..77e0a89
--- /dev/null
+++ b/test/Modules/Inputs/merge-implicit-special-members/module.modulemap
@@ -0,0 +1,3 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
+module c { header "c.h" export * }
diff --git a/test/Modules/Inputs/merge-name-for-linkage/a.h b/test/Modules/Inputs/merge-name-for-linkage/a.h
new file mode 100644
index 0000000..82f2fdd
--- /dev/null
+++ b/test/Modules/Inputs/merge-name-for-linkage/a.h
@@ -0,0 +1 @@
+typedef union {} pthread_mutex_t;
diff --git a/test/Modules/Inputs/merge-name-for-linkage/b.h b/test/Modules/Inputs/merge-name-for-linkage/b.h
new file mode 100644
index 0000000..82f2fdd
--- /dev/null
+++ b/test/Modules/Inputs/merge-name-for-linkage/b.h
@@ -0,0 +1 @@
+typedef union {} pthread_mutex_t;
diff --git a/test/Modules/Inputs/merge-name-for-linkage/module.modulemap b/test/Modules/Inputs/merge-name-for-linkage/module.modulemap
new file mode 100644
index 0000000..61578a1
--- /dev/null
+++ b/test/Modules/Inputs/merge-name-for-linkage/module.modulemap
@@ -0,0 +1,2 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
diff --git a/test/Modules/Inputs/merge-nested-templates/a.h b/test/Modules/Inputs/merge-nested-templates/a.h
new file mode 100644
index 0000000..826d257
--- /dev/null
+++ b/test/Modules/Inputs/merge-nested-templates/a.h
@@ -0,0 +1 @@
+#include "string.ii"
diff --git a/test/Modules/Inputs/merge-nested-templates/b.h b/test/Modules/Inputs/merge-nested-templates/b.h
new file mode 100644
index 0000000..516694e
--- /dev/null
+++ b/test/Modules/Inputs/merge-nested-templates/b.h
@@ -0,0 +1,2 @@
+#include "a.h"
+std::wstring::iterator j;
diff --git a/test/Modules/Inputs/merge-nested-templates/c.h b/test/Modules/Inputs/merge-nested-templates/c.h
new file mode 100644
index 0000000..ab95e14
--- /dev/null
+++ b/test/Modules/Inputs/merge-nested-templates/c.h
@@ -0,0 +1,3 @@
+#include "string.ii"
+std::wstring::iterator i;
+#include "b.h"
diff --git a/test/Modules/Inputs/merge-nested-templates/module.modulemap b/test/Modules/Inputs/merge-nested-templates/module.modulemap
new file mode 100644
index 0000000..77e0a89
--- /dev/null
+++ b/test/Modules/Inputs/merge-nested-templates/module.modulemap
@@ -0,0 +1,3 @@
+module a { header "a.h" export * }
+module b { header "b.h" export * }
+module c { header "c.h" export * }
diff --git a/test/Modules/Inputs/merge-nested-templates/string.ii b/test/Modules/Inputs/merge-nested-templates/string.ii
new file mode 100644
index 0000000..136d8e7
--- /dev/null
+++ b/test/Modules/Inputs/merge-nested-templates/string.ii
@@ -0,0 +1,14 @@
+namespace std {
+  template <typename, typename Container> struct normal_iterator {
+    normal_iterator() {}
+
+    template <typename I>
+    normal_iterator(normal_iterator<I, typename Container::iterator>) {}
+  };
+
+  template <typename pointer> struct basic_string {
+    typedef normal_iterator<pointer, basic_string> iterator;
+  };
+
+  typedef basic_string<wchar_t *> wstring;
+}
diff --git a/test/Modules/Inputs/merge-template-members/a1.h b/test/Modules/Inputs/merge-template-members/a1.h
new file mode 100644
index 0000000..9212a3f
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/a1.h
@@ -0,0 +1,9 @@
+namespace N {
+  template <typename> struct A {
+    int n;
+    A() : n() {}
+  };
+
+  // Create declaration of A<int>.
+  typedef A<int> AI;
+}
diff --git a/test/Modules/Inputs/merge-template-members/a2.h b/test/Modules/Inputs/merge-template-members/a2.h
new file mode 100644
index 0000000..9212a3f
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/a2.h
@@ -0,0 +1,9 @@
+namespace N {
+  template <typename> struct A {
+    int n;
+    A() : n() {}
+  };
+
+  // Create declaration of A<int>.
+  typedef A<int> AI;
+}
diff --git a/test/Modules/Inputs/merge-template-members/b1.h b/test/Modules/Inputs/merge-template-members/b1.h
new file mode 100644
index 0000000..3828e26
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/b1.h
@@ -0,0 +1,6 @@
+#include "a1.h"
+
+// Add update record for definition of A<int> and constructors.
+// We need an eagerly-emitted use here to get the problematic
+// deserialization ordering.
+N::A<int> b1;
diff --git a/test/Modules/Inputs/merge-template-members/b2.h b/test/Modules/Inputs/merge-template-members/b2.h
new file mode 100644
index 0000000..37357ac
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/b2.h
@@ -0,0 +1,6 @@
+#include "a2.h"
+
+// Add update record for definition of A<int> and constructors.
+// We need an eagerly-emitted use here to get the problematic
+// deserialization ordering.
+N::A<int> b2;
diff --git a/test/Modules/Inputs/merge-template-members/c.h b/test/Modules/Inputs/merge-template-members/c.h
new file mode 100644
index 0000000..92f20a0
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/c.h
@@ -0,0 +1,14 @@
+namespace N {
+  template <typename> struct A {
+    int n;
+    A() : n() {}
+  };
+
+  // Trigger instantiation of definition of A<int>.
+  struct C {
+    A<int> a;
+  };
+}
+
+// Merge in another declaration and update records.
+#include "b1.h"
diff --git a/test/Modules/Inputs/merge-template-members/def.h b/test/Modules/Inputs/merge-template-members/def.h
new file mode 100644
index 0000000..f9f65c3
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/def.h
@@ -0,0 +1,2 @@
+template<typename> struct A { int n; };
+template<typename> struct B { typedef A<void> C; };
diff --git a/test/Modules/Inputs/merge-template-members/merge.h b/test/Modules/Inputs/merge-template-members/merge.h
new file mode 100644
index 0000000..72d2d36
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/merge.h
@@ -0,0 +1,2 @@
+#include "b1.h"
+#include "b2.h"
diff --git a/test/Modules/Inputs/merge-template-members/module.modulemap b/test/Modules/Inputs/merge-template-members/module.modulemap
new file mode 100644
index 0000000..0d72e58
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/module.modulemap
@@ -0,0 +1,9 @@
+module def { header "def.h" export * }
+module update { header "update.h" export * }
+
+module a1 { header "a1.h" export * }
+module a2 { header "a2.h" export * }
+module b1 { header "b1.h" export * }
+module b2 { header "b2.h" export * }
+module merge { header "merge.h" export * }
+module c { header "c.h" export * }
diff --git a/test/Modules/Inputs/merge-template-members/update.h b/test/Modules/Inputs/merge-template-members/update.h
new file mode 100644
index 0000000..cceb52d
--- /dev/null
+++ b/test/Modules/Inputs/merge-template-members/update.h
@@ -0,0 +1,2 @@
+#include "def.h"
+B<int>::C use1;
diff --git a/test/Modules/Inputs/merge-vtable-codegen/a.h b/test/Modules/Inputs/merge-vtable-codegen/a.h
new file mode 100644
index 0000000..c288537
--- /dev/null
+++ b/test/Modules/Inputs/merge-vtable-codegen/a.h
@@ -0,0 +1,8 @@
+#ifndef A_H
+#define A_H
+
+struct A {
+  virtual void x();
+};
+
+#endif
diff --git a/test/Modules/Inputs/merge-vtable-codegen/b.h b/test/Modules/Inputs/merge-vtable-codegen/b.h
new file mode 100644
index 0000000..770e460
--- /dev/null
+++ b/test/Modules/Inputs/merge-vtable-codegen/b.h
@@ -0,0 +1,17 @@
+#ifndef B_H
+#define B_H
+
+#include "a.h"
+
+class B : virtual public A {
+  virtual void x() {}
+};
+
+void b(A* p) {
+  p->x();
+  // Instantiating a class that virtually inherits 'A'
+  // triggers calculation of the vtable offsets in 'A'.
+  B b;
+}
+
+#endif
diff --git a/test/Modules/Inputs/merge-vtable-codegen/c.h b/test/Modules/Inputs/merge-vtable-codegen/c.h
new file mode 100644
index 0000000..40cbbb0
--- /dev/null
+++ b/test/Modules/Inputs/merge-vtable-codegen/c.h
@@ -0,0 +1,6 @@
+#ifndef C_H
+#define C_H
+
+#include "a.h"
+
+#endif
diff --git a/test/Modules/Inputs/merge-vtable-codegen/merge-vtable-codegen.modulemap b/test/Modules/Inputs/merge-vtable-codegen/merge-vtable-codegen.modulemap
new file mode 100644
index 0000000..1edaa07
--- /dev/null
+++ b/test/Modules/Inputs/merge-vtable-codegen/merge-vtable-codegen.modulemap
@@ -0,0 +1,11 @@
+module "a" {
+  textual header "a.h"
+}
+
+module "b" {
+  header "b.h"
+}
+
+module "c" {
+  header "c.h"
+}
diff --git a/test/Modules/Inputs/modular_maps-moduleb-cwd.map b/test/Modules/Inputs/modular_maps-moduleb-cwd.map
new file mode 100644
index 0000000..1ff307f
--- /dev/null
+++ b/test/Modules/Inputs/modular_maps-moduleb-cwd.map
@@ -0,0 +1,4 @@
+module B {
+  header "Inputs/modular_maps/common.h"
+  private header "Inputs/modular_maps/b.h"
+}
diff --git a/test/Modules/Inputs/modular_maps/modulea-cwd.map b/test/Modules/Inputs/modular_maps/modulea-cwd.map
new file mode 100644
index 0000000..10be523
--- /dev/null
+++ b/test/Modules/Inputs/modular_maps/modulea-cwd.map
@@ -0,0 +1,7 @@
+module A {
+  header "Inputs/modular_maps/common.h"
+  header "Inputs/modular_maps/a.h"
+}
+
+extern module B "Inputs/modular_maps-moduleb-cwd.map"
+
diff --git a/test/Modules/Inputs/modular_maps/modulec-cwd.map b/test/Modules/Inputs/modular_maps/modulec-cwd.map
new file mode 100644
index 0000000..ca38b54
--- /dev/null
+++ b/test/Modules/Inputs/modular_maps/modulec-cwd.map
@@ -0,0 +1,3 @@
+module C {
+  header "Inputs/modular_maps/c.h"
+}
diff --git a/test/Modules/Inputs/module.map b/test/Modules/Inputs/module.map
index 7040ee7..8ec3e21 100644
--- a/test/Modules/Inputs/module.map
+++ b/test/Modules/Inputs/module.map
@@ -296,10 +296,6 @@
   header "warn-unused-local-typedef.h"
 }
 
-module initializer_list {
-  header "initializer_list"
-}
-
 module using_decl {
   module a { header "using-decl-a.h" export * }
   module b { header "using-decl-b.h" export * }
diff --git a/test/Modules/Inputs/no-implicit-builds/b.h b/test/Modules/Inputs/no-implicit-builds/b.h
new file mode 100644
index 0000000..4fe1c76
--- /dev/null
+++ b/test/Modules/Inputs/no-implicit-builds/b.h
@@ -0,0 +1,6 @@
+#ifndef B_H
+#define B_H
+
+int b;
+
+#endif
diff --git a/test/Modules/Inputs/no-implicit-builds/b.modulemap b/test/Modules/Inputs/no-implicit-builds/b.modulemap
new file mode 100644
index 0000000..3c8ca54
--- /dev/null
+++ b/test/Modules/Inputs/no-implicit-builds/b.modulemap
@@ -0,0 +1,3 @@
+module "b" {
+  header "b.h"
+}
diff --git a/test/Modules/Inputs/pr19692/my.cc b/test/Modules/Inputs/pr19692/my.cc
deleted file mode 100644
index bb0b7c5..0000000
--- a/test/Modules/Inputs/pr19692/my.cc
+++ /dev/null
@@ -1,5 +0,0 @@
-#include "TFoo.h"
-#include "stdint.h"
-
-  int k = INT64_MAX; // error!
-
diff --git a/test/Modules/Inputs/preprocess/file.h b/test/Modules/Inputs/preprocess/file.h
new file mode 100644
index 0000000..808ade5
--- /dev/null
+++ b/test/Modules/Inputs/preprocess/file.h
@@ -0,0 +1,3 @@
+struct __FILE;
+#include "fwd.h"
+typedef struct __FILE FILE;
diff --git a/test/Modules/Inputs/preprocess/fwd.h b/test/Modules/Inputs/preprocess/fwd.h
new file mode 100644
index 0000000..4a19c6d
--- /dev/null
+++ b/test/Modules/Inputs/preprocess/fwd.h
@@ -0,0 +1 @@
+struct __FILE;
diff --git a/test/Modules/Inputs/preprocess/module.modulemap b/test/Modules/Inputs/preprocess/module.modulemap
new file mode 100644
index 0000000..a5c5b61
--- /dev/null
+++ b/test/Modules/Inputs/preprocess/module.modulemap
@@ -0,0 +1,2 @@
+module fwd { header "fwd.h" export * }
+module file { header "file.h" export * }
diff --git a/test/Modules/Inputs/redecl-templates/a.h b/test/Modules/Inputs/redecl-templates/a.h
new file mode 100644
index 0000000..fd25fcf
--- /dev/null
+++ b/test/Modules/Inputs/redecl-templates/a.h
@@ -0,0 +1,8 @@
+template<int N> struct A;
+template<> struct A<1>;
+
+template<int N> constexpr void f();
+template<> constexpr void f<1>();
+
+template<int N> extern int v;
+template<> extern int v<1>;
diff --git a/test/Modules/Inputs/redecl-templates/module.modulemap b/test/Modules/Inputs/redecl-templates/module.modulemap
new file mode 100644
index 0000000..6480358
--- /dev/null
+++ b/test/Modules/Inputs/redecl-templates/module.modulemap
@@ -0,0 +1 @@
+module A { header "a.h" }
diff --git a/test/Modules/redecls/a.h b/test/Modules/Inputs/redecls/a.h
similarity index 100%
rename from test/Modules/redecls/a.h
rename to test/Modules/Inputs/redecls/a.h
diff --git a/test/Modules/redecls/b.h b/test/Modules/Inputs/redecls/b.h
similarity index 100%
rename from test/Modules/redecls/b.h
rename to test/Modules/Inputs/redecls/b.h
diff --git a/test/Modules/redecls/module.map b/test/Modules/Inputs/redecls/module.map
similarity index 100%
rename from test/Modules/redecls/module.map
rename to test/Modules/Inputs/redecls/module.map
diff --git a/test/Modules/Inputs/relative-dep-gen-1.h b/test/Modules/Inputs/relative-dep-gen-1.h
new file mode 100644
index 0000000..deb5698
--- /dev/null
+++ b/test/Modules/Inputs/relative-dep-gen-1.h
@@ -0,0 +1 @@
+// empty 1
diff --git a/test/Modules/Inputs/relative-dep-gen-2.h b/test/Modules/Inputs/relative-dep-gen-2.h
new file mode 100644
index 0000000..2b9517d
--- /dev/null
+++ b/test/Modules/Inputs/relative-dep-gen-2.h
@@ -0,0 +1 @@
+// empty 2
diff --git a/test/Modules/Inputs/relative-dep-gen-cwd.modulemap b/test/Modules/Inputs/relative-dep-gen-cwd.modulemap
new file mode 100644
index 0000000..b8678d3
--- /dev/null
+++ b/test/Modules/Inputs/relative-dep-gen-cwd.modulemap
@@ -0,0 +1,4 @@
+module "relative-dep-gen" {
+  header "Inputs/relative-dep-gen-1.h"
+  header "Inputs/relative-dep-gen-2.h"
+}
diff --git a/test/Modules/Inputs/relative-dep-gen.modulemap b/test/Modules/Inputs/relative-dep-gen.modulemap
new file mode 100644
index 0000000..4c821e1
--- /dev/null
+++ b/test/Modules/Inputs/relative-dep-gen.modulemap
@@ -0,0 +1,4 @@
+module "relative-dep-gen" {
+  header "relative-dep-gen-1.h"
+  header "relative-dep-gen-2.h"
+}
diff --git a/test/Modules/self-import-header/af.framework/Headers/a1.h b/test/Modules/Inputs/self-import-header/af.framework/Headers/a1.h
similarity index 100%
rename from test/Modules/self-import-header/af.framework/Headers/a1.h
rename to test/Modules/Inputs/self-import-header/af.framework/Headers/a1.h
diff --git a/test/Modules/self-import-header/af.framework/Headers/a2.h b/test/Modules/Inputs/self-import-header/af.framework/Headers/a2.h
similarity index 100%
rename from test/Modules/self-import-header/af.framework/Headers/a2.h
rename to test/Modules/Inputs/self-import-header/af.framework/Headers/a2.h
diff --git a/test/Modules/self-import-header/af.framework/module.map b/test/Modules/Inputs/self-import-header/af.framework/module.map
similarity index 100%
rename from test/Modules/self-import-header/af.framework/module.map
rename to test/Modules/Inputs/self-import-header/af.framework/module.map
diff --git a/test/Modules/self-import-header/depend_builtin/h1.h b/test/Modules/Inputs/self-import-header/depend_builtin/h1.h
similarity index 100%
rename from test/Modules/self-import-header/depend_builtin/h1.h
rename to test/Modules/Inputs/self-import-header/depend_builtin/h1.h
diff --git a/test/Modules/self-import-header/depend_builtin/module.map b/test/Modules/Inputs/self-import-header/depend_builtin/module.map
similarity index 100%
rename from test/Modules/self-import-header/depend_builtin/module.map
rename to test/Modules/Inputs/self-import-header/depend_builtin/module.map
diff --git a/test/Modules/attr-unavailable.m b/test/Modules/attr-unavailable.m
new file mode 100644
index 0000000..0188a84
--- /dev/null
+++ b/test/Modules/attr-unavailable.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/attr-unavailable %s -fsyntax-only -verify
+
+@import two;
+void f(id x) {
+  [x method1];
+}
+
+@import oneA;
+void g(id x) {
+  [x method2]; // expected-error{{'method2' is unavailable}}
+               // expected-note@oneA.h:2 {{'method2' has been explicitly marked unavailable here}}
+  [x method3]; // expected-error{{'method3' is unavailable}}
+               // expected-note@oneA.h:3 {{'method3' has been explicitly marked unavailable here}}
+}
+
+@import oneB;
+void h(id x) {
+  [x method2]; // could be from interface D in module oneB
+}
+
+@import oneC;
+void i(id x) {
+  [x method3]; // could be from interface E in module oncC
+}
diff --git a/test/Modules/autolink.m b/test/Modules/autolink.m
index 47eda3f..5f2e9bd 100644
--- a/test/Modules/autolink.m
+++ b/test/Modules/autolink.m
@@ -37,14 +37,14 @@
 // NOTE: "autolink_sub" is intentionally not linked.
 
 // CHECK: !llvm.module.flags = !{{{.*}}}
-// CHECK: !{{[0-9]+}} = metadata !{i32 6, metadata !"Linker Options", metadata ![[AUTOLINK_OPTIONS:[0-9]+]]}
-// CHECK: ![[AUTOLINK_OPTIONS]] = metadata !{metadata ![[AUTOLINK_PCH:[0-9]+]], metadata ![[AUTOLINK_FRAMEWORK:[0-9]+]], metadata ![[AUTOLINK:[0-9]+]], metadata ![[DEPENDSONMODULE:[0-9]+]], metadata ![[MODULE:[0-9]+]], metadata ![[NOUMBRELLA:[0-9]+]]}
-// CHECK: ![[AUTOLINK_PCH]] = metadata !{metadata !"{{(-l|/DEFAULTLIB:)}}autolink_from_pch{{(\.lib)?}}"}
-// CHECK: ![[AUTOLINK_FRAMEWORK]] = metadata !{metadata !"-framework", metadata !"autolink_framework"}
-// CHECK: ![[AUTOLINK]] = metadata !{metadata !"{{(-l|/DEFAULTLIB:)}}autolink{{(\.lib)?}}"}
-// CHECK: ![[DEPENDSONMODULE]] = metadata !{metadata !"-framework", metadata !"DependsOnModule"}
-// CHECK: ![[MODULE]] = metadata !{metadata !"-framework", metadata !"Module"}
-// CHECK: ![[NOUMBRELLA]] = metadata !{metadata !"-framework", metadata !"NoUmbrella"}
+// CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[AUTOLINK_OPTIONS:[0-9]+]]}
+// CHECK: ![[AUTOLINK_OPTIONS]] = !{![[AUTOLINK_PCH:[0-9]+]], ![[AUTOLINK_FRAMEWORK:[0-9]+]], ![[AUTOLINK:[0-9]+]], ![[DEPENDSONMODULE:[0-9]+]], ![[MODULE:[0-9]+]], ![[NOUMBRELLA:[0-9]+]]}
+// CHECK: ![[AUTOLINK_PCH]] = !{!"{{(-l|/DEFAULTLIB:)}}autolink_from_pch{{(\.lib)?}}"}
+// CHECK: ![[AUTOLINK_FRAMEWORK]] = !{!"-framework", !"autolink_framework"}
+// CHECK: ![[AUTOLINK]] = !{!"{{(-l|/DEFAULTLIB:)}}autolink{{(\.lib)?}}"}
+// CHECK: ![[DEPENDSONMODULE]] = !{!"-framework", !"DependsOnModule"}
+// CHECK: ![[MODULE]] = !{!"-framework", !"Module"}
+// CHECK: ![[NOUMBRELLA]] = !{!"-framework", !"NoUmbrella"}
 
 // CHECK-AUTOLINK-DISABLED: !llvm.module.flags
 // CHECK-AUTOLINK-DISABLED-NOT: "Linker Options"
diff --git a/test/Modules/compiler_builtins.m b/test/Modules/compiler_builtins.m
index 4b8cb5b..f120bcf 100644
--- a/test/Modules/compiler_builtins.m
+++ b/test/Modules/compiler_builtins.m
@@ -1,6 +1,6 @@
 // RUN: rm -rf %t
-// RUN: %clang -fsyntax-only -fmodules -fmodules-cache-path=%t -D__need_wint_t %s -Xclang -verify
-// RUN: %clang -fsyntax-only -std=c99 -fmodules -fmodules-cache-path=%t -D__need_wint_t %s -Xclang -verify
+// RUN: %clang -fsyntax-only -fmodules -fmodules-cache-path=%t -D__need_wint_t %s -I%S/Inputs/System/usr/include -Xclang -verify
+// RUN: %clang -fsyntax-only -std=c99 -fmodules -fmodules-cache-path=%t -D__need_wint_t %s -I%S/Inputs/System/usr/include -Xclang -verify
 // expected-no-diagnostics
 
 #ifdef __SSE__
diff --git a/test/Modules/cxx-irgen.cpp b/test/Modules/cxx-irgen.cpp
index ecaf704..13902bf 100644
--- a/test/Modules/cxx-irgen.cpp
+++ b/test/Modules/cxx-irgen.cpp
@@ -5,7 +5,6 @@
 
 @import cxx_irgen_top;
 
-// CHECK-DAG: call {{[a-z]*[ ]?i32}} @_ZN8CtorInitIiE1fEv(
 CtorInit<int> x;
 
 @import cxx_irgen_left;
@@ -34,23 +33,25 @@
 
 // CHECK-DAG: define linkonce_odr {{signext i32|i32}} @_Z3minIiET_S0_S0_(i32
 int c = min(1, 2);
-
-// CHECK-LABEL: define {{.*}} @_ZN20OperatorDeleteLookup1AD0Ev(
-// CHECK: call void @_ZN20OperatorDeleteLookup1AdlEPv(
+// CHECK: define available_externally {{signext i32|i32}} @_ZN1SIiE1fEv({{.*}} #[[ALWAYS_INLINE]] align
 
 namespace ImplicitSpecialMembers {
-  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1DC2EOS0_(
-  // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
-  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1DC2ERKS0_(
-  // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
-  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1CC2EOS0_(
-  // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
-  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1CC2ERKS0_(
+  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1BC2ERKS0_(
   // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
   // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1BC2EOS0_(
   // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
-  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1BC2ERKS0_(
+  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1CC2ERKS0_(
   // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
+  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1CC2EOS0_(
+  // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
+  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1DC2ERKS0_(
+  // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
+  // CHECK-LABEL: define {{.*}} @_ZN22ImplicitSpecialMembers1DC2EOS0_(
+  // CHECK: call {{.*}} @_ZN22ImplicitSpecialMembers1AC1ERKS0_(
+  // CHECK-LABEL: define {{.*}} @_ZN20OperatorDeleteLookup1AD0Ev(
+  // CHECK: call void @_ZN20OperatorDeleteLookup1AdlEPv(
+
+  // CHECK-DAG: call {{[a-z]*[ ]?i32}} @_ZN8CtorInitIiE1fEv(
 
   extern B b1;
   B b2(b1);
@@ -71,6 +72,5 @@
   void g() { f(); }
 }
 
-// CHECK: define available_externally {{signext i32|i32}} @_ZN1SIiE1fEv({{.*}} #[[ALWAYS_INLINE]] align
 
 // CHECK: attributes #[[ALWAYS_INLINE]] = {{.*}} alwaysinline
diff --git a/test/Modules/cxx-lookup.cpp b/test/Modules/cxx-lookup.cpp
index 47c879d..bd019c7 100644
--- a/test/Modules/cxx-lookup.cpp
+++ b/test/Modules/cxx-lookup.cpp
@@ -4,3 +4,8 @@
 namespace llvm {}
 #include "c2.h"
 llvm::GlobalValue *p;
+
+#include "na.h"
+namespace N { struct foo; }
+#include "nb.h"
+N::foo *use_n_foo;
diff --git a/test/Modules/cxx-templates.cpp b/test/Modules/cxx-templates.cpp
index d9c8a8c..46c2f33 100644
--- a/test/Modules/cxx-templates.cpp
+++ b/test/Modules/cxx-templates.cpp
@@ -28,14 +28,8 @@
   f<double>(1.0);
   f<int>();
   f(); // expected-error {{no matching function}}
-#ifdef EARLY_IMPORT
-  // FIXME: The textual inclusion above shouldn't affect this!
-  // expected-note@Inputs/cxx-templates-a.h:3 {{couldn't infer template argument}}
-  // expected-note@Inputs/cxx-templates-a.h:4 {{requires 1 argument}}
-#else
   // expected-note@Inputs/cxx-templates-b.h:3 {{couldn't infer template argument}}
   // expected-note@Inputs/cxx-templates-b.h:4 {{requires single argument}}
-#endif
 
   N::f(0);
   N::f<double>(1.0);
@@ -195,11 +189,11 @@
 // CHECK-NAMESPACE-N-NEXT: `-FunctionTemplate {{.*}} 'f'
 
 // CHECK-DUMP:      ClassTemplateDecl {{.*}} <{{.*[/\\]}}cxx-templates-common.h:1:1, {{.*}}>  col:{{.*}} in cxx_templates_common SomeTemplate
-// CHECK-DUMP:        ClassTemplateSpecializationDecl {{.*}} prev [[CHAR2:[^ ]*]] {{.*}} SomeTemplate
+// CHECK-DUMP:        ClassTemplateSpecializationDecl {{.*}} prev {{.*}} SomeTemplate
 // CHECK-DUMP-NEXT:     TemplateArgument type 'char [2]'
-// CHECK-DUMP:        ClassTemplateSpecializationDecl [[CHAR2]] {{.*}} SomeTemplate definition
+// CHECK-DUMP:        ClassTemplateSpecializationDecl {{.*}} SomeTemplate definition
 // CHECK-DUMP-NEXT:     TemplateArgument type 'char [2]'
-// CHECK-DUMP:        ClassTemplateSpecializationDecl {{.*}} prev [[CHAR1:[^ ]*]] {{.*}} SomeTemplate
+// CHECK-DUMP:        ClassTemplateSpecializationDecl {{.*}} prev {{.*}} SomeTemplate
 // CHECK-DUMP-NEXT:     TemplateArgument type 'char [1]'
-// CHECK-DUMP:        ClassTemplateSpecializationDecl [[CHAR1]] {{.*}} SomeTemplate definition
+// CHECK-DUMP:        ClassTemplateSpecializationDecl {{.*}} SomeTemplate definition
 // CHECK-DUMP-NEXT:     TemplateArgument type 'char [1]'
diff --git a/test/Modules/declare-use-compatible.cpp b/test/Modules/declare-use-compatible.cpp
new file mode 100644
index 0000000..4c3d79b
--- /dev/null
+++ b/test/Modules/declare-use-compatible.cpp
@@ -0,0 +1,36 @@
+// Used module not built with -decluse.
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -x c++ -fmodules -fmodule-name=XB -emit-module \
+// RUN:   -I %S/Inputs/declare-use %S/Inputs/declare-use/module.map -o %t/b.pcm
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t \
+// RUN:   -fmodules-decluse \
+// RUN:   -fmodule-file=%t/b.pcm -fmodule-name=XE -I %S/Inputs/declare-use %s
+//
+// Main module not built with -decluse.
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -x c++ -fmodules -fmodule-name=XB -emit-module \
+// RUN:   -fmodules-decluse \
+// RUN:   -I %S/Inputs/declare-use %S/Inputs/declare-use/module.map -o %t/b.pcm
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t \
+// RUN:   -fmodule-file=%t/b.pcm -fmodule-name=XE -I %S/Inputs/declare-use %s
+//
+// Used module not built with -decluse.
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -x c++ -fmodules -fmodule-name=XB -emit-module \
+// RUN:   -I %S/Inputs/declare-use %S/Inputs/declare-use/module.map -o %t/b.pcm
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t \
+// RUN:   -fmodules-strict-decluse \
+// RUN:   -fmodule-file=%t/b.pcm -fmodule-name=XE -I %S/Inputs/declare-use %s
+//
+// Main module not built with -decluse.
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -x c++ -fmodules -fmodule-name=XB -emit-module \
+// RUN:   -fmodules-strict-decluse \
+// RUN:   -I %S/Inputs/declare-use %S/Inputs/declare-use/module.map -o %t/b.pcm
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t \
+// RUN:   -fmodule-file=%t/b.pcm -fmodule-name=XE -I %S/Inputs/declare-use %s
+
+#include "b.h"
+
+const int g = b;
+
diff --git a/test/Modules/deferred-lookup.cpp b/test/Modules/deferred-lookup.cpp
new file mode 100644
index 0000000..aaac389
--- /dev/null
+++ b/test/Modules/deferred-lookup.cpp
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/deferred-lookup -verify %s
+// expected-no-diagnostics
+
+namespace N { int f(int); }
+#include "b.h"
diff --git a/test/Modules/dependency-gen.modulemap b/test/Modules/dependency-gen.modulemap
new file mode 100644
index 0000000..5cb8a4d
--- /dev/null
+++ b/test/Modules/dependency-gen.modulemap
@@ -0,0 +1,18 @@
+// REQUIRES: shell
+//
+// RUN: cd %S
+// RUN: rm -f %t.cpm %t-base.pcm %t-base.d %t.d
+// RUN: %clang_cc1 -I. -x c++ -fmodule-maps -fmodule-name=test-base -fno-modules-implicit-maps -fmodules -emit-module -fno-validate-pch -fmodules-strict-decluse Inputs/dependency-gen-base.modulemap -dependency-file %t-base.d -MT %t-base.pcm -o %t-base.pcm -fmodule-map-file-home-is-cwd
+// RUN: %clang_cc1 -I. -x c++ -fmodule-maps -fmodule-name=test -fno-modules-implicit-maps -fmodules -emit-module -fno-validate-pch -fmodules-strict-decluse -fmodule-file=%t-base.pcm %s -dependency-file %t.d -MT %t.pcm -o %t.pcm -fmodule-map-file-home-is-cwd
+// RUN: FileCheck %s < %t.d
+module "test" {
+  export *
+  header "Inputs/dependency-gen.h"
+  use "test-base"
+  use "test-base2"
+}
+extern module "test-base2" "Inputs/dependency-gen-base2.modulemap"
+extern module "test-base" "Inputs/dependency-gen-base.modulemap"
+
+// CHECK: {{ |\./}}Inputs/dependency-gen-included2.h
+// CHECK: {{ |\./}}Inputs/dependency-gen-base.modulemap
diff --git a/test/Modules/diagnostics.modulemap b/test/Modules/diagnostics.modulemap
new file mode 100644
index 0000000..14eb408
--- /dev/null
+++ b/test/Modules/diagnostics.modulemap
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -fmodule-map-file=%s -fsyntax-only -x c++ /dev/null 2>&1
+//
+// RUN: cp %s %t-duplicate.modulemap
+// RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -fmodule-map-file=%s -fmodule-map-file=%t-duplicate.modulemap -fsyntax-only -x c++ /dev/null 2>&1 | FileCheck --check-prefix=CHECK-DUPLICATE %s
+
+// PR22299: Ensure we can produce diagnostics for duplicate modules from -fmodule-map-file=.
+//
+// CHECK-DUPLICATE: duplicate.modulemap:[[@LINE+2]]:8: error: redefinition of module 'foo'
+// CHECK-DUPLICATE: diagnostics.modulemap:[[@LINE+1]]:8: note: previously defined here
+module foo {}
+
+//* Check that we accept BCPL comments properly, not just as an extension. */
diff --git a/test/Modules/explicit-build-relpath.cpp b/test/Modules/explicit-build-relpath.cpp
new file mode 100644
index 0000000..d9c1566
--- /dev/null
+++ b/test/Modules/explicit-build-relpath.cpp
@@ -0,0 +1,49 @@
+// REQUIRES: shell
+//
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: cd %t
+
+// ----------------------
+// Build modules A and B.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -fmodule-name=a -emit-module %S/Inputs/explicit-build/module.modulemap -o a.pcm
+//
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -fmodule-file=a.pcm \
+// RUN:            -fmodule-name=b -emit-module %S/Inputs/explicit-build/module.modulemap -o b-rel.pcm
+//
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -fmodule-file=%t/a.pcm \
+// RUN:            -fmodule-name=b -emit-module %S/Inputs/explicit-build/module.modulemap -o b-abs.pcm
+
+// ------------------------------------------
+// Mix and match relative and absolute paths.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -I%S/Inputs/explicit-build \
+// RUN:            -fmodule-file=%t/a.pcm \
+// RUN:            -fmodule-file=a.pcm \
+// RUN:            -verify %s
+//
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -I%S/Inputs/explicit-build \
+// RUN:            -fmodule-file=%t/a.pcm \
+// RUN:            -fmodule-file=b-rel.pcm \
+// RUN:            -verify %s
+//
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -I%S/Inputs/explicit-build \
+// RUN:            -fmodule-file=a.pcm \
+// RUN:            -fmodule-file=b-abs.pcm \
+// RUN:            -verify %s
+//
+// RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -I%S/Inputs/explicit-build \
+// RUN:            -fmodule-file=b-rel.pcm \
+// RUN:            -fmodule-file=b-abs.pcm \
+// RUN:            -verify %s 2>&1 | FileCheck %s
+// CHECK: module 'b' is defined in both '{{.*}}b-rel.pcm' and '{{.*}}b-abs.pcm'
+
+#include "a.h"
+static_assert(a == 1, "");
+// expected-no-diagnostics
diff --git a/test/Modules/explicit-build.cpp b/test/Modules/explicit-build.cpp
index 8d8237f..ce3a1af 100644
--- a/test/Modules/explicit-build.cpp
+++ b/test/Modules/explicit-build.cpp
@@ -153,3 +153,23 @@
 // RUN:            %s 2>&1 | FileCheck --check-prefix=CHECK-BAD-FILE %s
 //
 // CHECK-BAD-FILE: fatal error: file '{{.*}}t.pcm' is not a precompiled module file
+
+// -------------------------------
+// Check that we don't get upset if B's timestamp is newer than C's.
+// RUN: touch %t/b.pcm
+//
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -I%S/Inputs/explicit-build \
+// RUN:            -fmodule-file=%t/c.pcm \
+// RUN:            -verify %s -DHAVE_A -DHAVE_B -DHAVE_C
+//
+// ... but that we do get upset if our B is different from the B that C expects.
+//
+// RUN: cp %t/b-not-a.pcm %t/b.pcm
+//
+// RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \
+// RUN:            -I%S/Inputs/explicit-build \
+// RUN:            -fmodule-file=%t/c.pcm \
+// RUN:            %s -DHAVE_A -DHAVE_B -DHAVE_C 2>&1 | FileCheck --check-prefix=CHECK-MISMATCHED-B %s
+//
+// CHECK-MISMATCHED-B: fatal error: malformed or corrupted AST file: {{.*}}b.pcm": module file out of date
diff --git a/test/Modules/exponential-paths.cpp b/test/Modules/exponential-paths.cpp
new file mode 100644
index 0000000..e7c0afc
--- /dev/null
+++ b/test/Modules/exponential-paths.cpp
@@ -0,0 +1,188 @@
+// REQUIRES: shell
+//
+// RUN: rm -rf %t
+// RUN: mkdir %t
+//
+// Build module map with 40 modules; two layers with importing and re-exporting
+// the previous layer.
+//
+// RUN: echo 'module a0 { header "a0.h" export * }' > %t/module.modulemap
+// RUN: echo 'module b0 { header "b0.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a1 { header "a1.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b1 { header "b1.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a2 { header "a2.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b2 { header "b2.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a3 { header "a3.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b3 { header "b3.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a4 { header "a4.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b4 { header "b4.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a5 { header "a5.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b5 { header "b5.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a6 { header "a6.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b6 { header "b6.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a7 { header "a7.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b7 { header "b7.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a8 { header "a8.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b8 { header "b8.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a9 { header "a9.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b9 { header "b9.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a10 { header "a10.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b10 { header "b10.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a11 { header "a11.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b11 { header "b11.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a12 { header "a12.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b12 { header "b12.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a13 { header "a13.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b13 { header "b13.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a14 { header "a14.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b14 { header "b14.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a15 { header "a15.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b15 { header "b15.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a16 { header "a16.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b16 { header "b16.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a17 { header "a17.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b17 { header "b17.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a18 { header "a18.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b18 { header "b18.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a19 { header "a19.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b19 { header "b19.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module a20 { header "a20.h" export * }' >> %t/module.modulemap
+// RUN: echo 'module b20 { header "b20.h" export * }' >> %t/module.modulemap
+//
+// Build the corresponding headers.
+//
+// RUN: echo 'extern int n;' > %t/a0.h
+// RUN: cp %t/a0.h %t/b0.h
+// RUN: echo '#include "a0.h"' > %t/a1.h
+// RUN: echo '#include "b0.h"' >> %t/a1.h
+// RUN: cp %t/a1.h %t/b1.h
+// RUN: echo '#include "a1.h"' > %t/a2.h
+// RUN: echo '#include "b1.h"' >> %t/a2.h
+// RUN: cp %t/a2.h %t/b2.h
+// RUN: echo '#include "a2.h"' > %t/a3.h
+// RUN: echo '#include "b2.h"' >> %t/a3.h
+// RUN: cp %t/a3.h %t/b3.h
+// RUN: echo '#include "a3.h"' > %t/a4.h
+// RUN: echo '#include "b3.h"' >> %t/a4.h
+// RUN: cp %t/a4.h %t/b4.h
+// RUN: echo '#include "a4.h"' > %t/a5.h
+// RUN: echo '#include "b4.h"' >> %t/a5.h
+// RUN: cp %t/a5.h %t/b5.h
+// RUN: echo '#include "a5.h"' > %t/a6.h
+// RUN: echo '#include "b5.h"' >> %t/a6.h
+// RUN: cp %t/a6.h %t/b6.h
+// RUN: echo '#include "a6.h"' > %t/a7.h
+// RUN: echo '#include "b6.h"' >> %t/a7.h
+// RUN: cp %t/a7.h %t/b7.h
+// RUN: echo '#include "a7.h"' > %t/a8.h
+// RUN: echo '#include "b7.h"' >> %t/a8.h
+// RUN: cp %t/a8.h %t/b8.h
+// RUN: echo '#include "a8.h"' > %t/a9.h
+// RUN: echo '#include "b8.h"' >> %t/a9.h
+// RUN: cp %t/a9.h %t/b9.h
+// RUN: echo '#include "a9.h"' > %t/a10.h
+// RUN: echo '#include "b9.h"' >> %t/a10.h
+// RUN: cp %t/a10.h %t/b10.h
+// RUN: echo '#include "a10.h"' > %t/a11.h
+// RUN: echo '#include "b10.h"' >> %t/a11.h
+// RUN: cp %t/a11.h %t/b11.h
+// RUN: echo '#include "a11.h"' > %t/a12.h
+// RUN: echo '#include "b11.h"' >> %t/a12.h
+// RUN: cp %t/a12.h %t/b12.h
+// RUN: echo '#include "a12.h"' > %t/a13.h
+// RUN: echo '#include "b12.h"' >> %t/a13.h
+// RUN: cp %t/a13.h %t/b13.h
+// RUN: echo '#include "a13.h"' > %t/a14.h
+// RUN: echo '#include "b13.h"' >> %t/a14.h
+// RUN: cp %t/a14.h %t/b14.h
+// RUN: echo '#include "a14.h"' > %t/a15.h
+// RUN: echo '#include "b14.h"' >> %t/a15.h
+// RUN: cp %t/a15.h %t/b15.h
+// RUN: echo '#include "a15.h"' > %t/a16.h
+// RUN: echo '#include "b15.h"' >> %t/a16.h
+// RUN: cp %t/a16.h %t/b16.h
+// RUN: echo '#include "a16.h"' > %t/a17.h
+// RUN: echo '#include "b16.h"' >> %t/a17.h
+// RUN: cp %t/a17.h %t/b17.h
+// RUN: echo '#include "a17.h"' > %t/a18.h
+// RUN: echo '#include "b17.h"' >> %t/a18.h
+// RUN: cp %t/a18.h %t/b18.h
+// RUN: echo '#include "a18.h"' > %t/a19.h
+// RUN: echo '#include "b18.h"' >> %t/a19.h
+// RUN: cp %t/a19.h %t/b19.h
+// RUN: echo '#include "a19.h"' > %t/a20.h
+// RUN: echo '#include "b19.h"' >> %t/a20.h
+// RUN: cp %t/a20.h %t/b20.h
+//
+// Explicitly build all the modules.
+//
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a0 -x c++ -emit-module %t/module.modulemap -o %t/a0.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b0 -x c++ -emit-module %t/module.modulemap -o %t/b0.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a1 -x c++ -emit-module %t/module.modulemap -o %t/a1.pcm -fmodule-file=%t/a0.pcm -fmodule-file=%t/b0.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b1 -x c++ -emit-module %t/module.modulemap -o %t/b1.pcm -fmodule-file=%t/a0.pcm -fmodule-file=%t/b0.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a2 -x c++ -emit-module %t/module.modulemap -o %t/a2.pcm -fmodule-file=%t/a1.pcm -fmodule-file=%t/b1.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b2 -x c++ -emit-module %t/module.modulemap -o %t/b2.pcm -fmodule-file=%t/a1.pcm -fmodule-file=%t/b1.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a3 -x c++ -emit-module %t/module.modulemap -o %t/a3.pcm -fmodule-file=%t/a2.pcm -fmodule-file=%t/b2.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b3 -x c++ -emit-module %t/module.modulemap -o %t/b3.pcm -fmodule-file=%t/a2.pcm -fmodule-file=%t/b2.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a4 -x c++ -emit-module %t/module.modulemap -o %t/a4.pcm -fmodule-file=%t/a3.pcm -fmodule-file=%t/b3.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b4 -x c++ -emit-module %t/module.modulemap -o %t/b4.pcm -fmodule-file=%t/a3.pcm -fmodule-file=%t/b3.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a5 -x c++ -emit-module %t/module.modulemap -o %t/a5.pcm -fmodule-file=%t/a4.pcm -fmodule-file=%t/b4.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b5 -x c++ -emit-module %t/module.modulemap -o %t/b5.pcm -fmodule-file=%t/a4.pcm -fmodule-file=%t/b4.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a6 -x c++ -emit-module %t/module.modulemap -o %t/a6.pcm -fmodule-file=%t/a5.pcm -fmodule-file=%t/b5.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b6 -x c++ -emit-module %t/module.modulemap -o %t/b6.pcm -fmodule-file=%t/a5.pcm -fmodule-file=%t/b5.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a7 -x c++ -emit-module %t/module.modulemap -o %t/a7.pcm -fmodule-file=%t/a6.pcm -fmodule-file=%t/b6.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b7 -x c++ -emit-module %t/module.modulemap -o %t/b7.pcm -fmodule-file=%t/a6.pcm -fmodule-file=%t/b6.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a8 -x c++ -emit-module %t/module.modulemap -o %t/a8.pcm -fmodule-file=%t/a7.pcm -fmodule-file=%t/b7.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b8 -x c++ -emit-module %t/module.modulemap -o %t/b8.pcm -fmodule-file=%t/a7.pcm -fmodule-file=%t/b7.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a9 -x c++ -emit-module %t/module.modulemap -o %t/a9.pcm -fmodule-file=%t/a8.pcm -fmodule-file=%t/b8.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b9 -x c++ -emit-module %t/module.modulemap -o %t/b9.pcm -fmodule-file=%t/a8.pcm -fmodule-file=%t/b8.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a10 -x c++ -emit-module %t/module.modulemap -o %t/a10.pcm -fmodule-file=%t/a9.pcm -fmodule-file=%t/b9.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b10 -x c++ -emit-module %t/module.modulemap -o %t/b10.pcm -fmodule-file=%t/a9.pcm -fmodule-file=%t/b9.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a11 -x c++ -emit-module %t/module.modulemap -o %t/a11.pcm -fmodule-file=%t/a10.pcm -fmodule-file=%t/b10.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b11 -x c++ -emit-module %t/module.modulemap -o %t/b11.pcm -fmodule-file=%t/a10.pcm -fmodule-file=%t/b10.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a12 -x c++ -emit-module %t/module.modulemap -o %t/a12.pcm -fmodule-file=%t/a11.pcm -fmodule-file=%t/b11.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b12 -x c++ -emit-module %t/module.modulemap -o %t/b12.pcm -fmodule-file=%t/a11.pcm -fmodule-file=%t/b11.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a13 -x c++ -emit-module %t/module.modulemap -o %t/a13.pcm -fmodule-file=%t/a12.pcm -fmodule-file=%t/b12.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b13 -x c++ -emit-module %t/module.modulemap -o %t/b13.pcm -fmodule-file=%t/a12.pcm -fmodule-file=%t/b12.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a14 -x c++ -emit-module %t/module.modulemap -o %t/a14.pcm -fmodule-file=%t/a13.pcm -fmodule-file=%t/b13.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b14 -x c++ -emit-module %t/module.modulemap -o %t/b14.pcm -fmodule-file=%t/a13.pcm -fmodule-file=%t/b13.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a15 -x c++ -emit-module %t/module.modulemap -o %t/a15.pcm -fmodule-file=%t/a14.pcm -fmodule-file=%t/b14.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b15 -x c++ -emit-module %t/module.modulemap -o %t/b15.pcm -fmodule-file=%t/a14.pcm -fmodule-file=%t/b14.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a16 -x c++ -emit-module %t/module.modulemap -o %t/a16.pcm -fmodule-file=%t/a15.pcm -fmodule-file=%t/b15.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b16 -x c++ -emit-module %t/module.modulemap -o %t/b16.pcm -fmodule-file=%t/a15.pcm -fmodule-file=%t/b15.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a17 -x c++ -emit-module %t/module.modulemap -o %t/a17.pcm -fmodule-file=%t/a16.pcm -fmodule-file=%t/b16.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b17 -x c++ -emit-module %t/module.modulemap -o %t/b17.pcm -fmodule-file=%t/a16.pcm -fmodule-file=%t/b16.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a18 -x c++ -emit-module %t/module.modulemap -o %t/a18.pcm -fmodule-file=%t/a17.pcm -fmodule-file=%t/b17.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b18 -x c++ -emit-module %t/module.modulemap -o %t/b18.pcm -fmodule-file=%t/a17.pcm -fmodule-file=%t/b17.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a19 -x c++ -emit-module %t/module.modulemap -o %t/a19.pcm -fmodule-file=%t/a18.pcm -fmodule-file=%t/b18.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b19 -x c++ -emit-module %t/module.modulemap -o %t/b19.pcm -fmodule-file=%t/a18.pcm -fmodule-file=%t/b18.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=a20 -x c++ -emit-module %t/module.modulemap -o %t/a20.pcm -fmodule-file=%t/a19.pcm -fmodule-file=%t/b19.pcm
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fmodule-name=b20 -x c++ -emit-module %t/module.modulemap -o %t/b20.pcm -fmodule-file=%t/a19.pcm -fmodule-file=%t/b19.pcm
+//
+// Build, using all the modules.
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%t -fsyntax-only %s \
+// RUN:            -fmodule-file=%t/a0.pcm -fmodule-file=%t/b0.pcm \
+// RUN:            -fmodule-file=%t/a1.pcm -fmodule-file=%t/b1.pcm \
+// RUN:            -fmodule-file=%t/a2.pcm -fmodule-file=%t/b2.pcm \
+// RUN:            -fmodule-file=%t/a3.pcm -fmodule-file=%t/b3.pcm \
+// RUN:            -fmodule-file=%t/a4.pcm -fmodule-file=%t/b4.pcm \
+// RUN:            -fmodule-file=%t/a5.pcm -fmodule-file=%t/b5.pcm \
+// RUN:            -fmodule-file=%t/a6.pcm -fmodule-file=%t/b6.pcm \
+// RUN:            -fmodule-file=%t/a7.pcm -fmodule-file=%t/b7.pcm \
+// RUN:            -fmodule-file=%t/a8.pcm -fmodule-file=%t/b8.pcm \
+// RUN:            -fmodule-file=%t/a9.pcm -fmodule-file=%t/b9.pcm \
+// RUN:            -fmodule-file=%t/a10.pcm -fmodule-file=%t/b10.pcm \
+// RUN:            -fmodule-file=%t/a11.pcm -fmodule-file=%t/b11.pcm \
+// RUN:            -fmodule-file=%t/a12.pcm -fmodule-file=%t/b12.pcm \
+// RUN:            -fmodule-file=%t/a13.pcm -fmodule-file=%t/b13.pcm \
+// RUN:            -fmodule-file=%t/a14.pcm -fmodule-file=%t/b14.pcm \
+// RUN:            -fmodule-file=%t/a15.pcm -fmodule-file=%t/b15.pcm \
+// RUN:            -fmodule-file=%t/a16.pcm -fmodule-file=%t/b16.pcm \
+// RUN:            -fmodule-file=%t/a17.pcm -fmodule-file=%t/b17.pcm \
+// RUN:            -fmodule-file=%t/a18.pcm -fmodule-file=%t/b18.pcm \
+// RUN:            -fmodule-file=%t/a19.pcm -fmodule-file=%t/b19.pcm \
+// RUN:            -fmodule-file=%t/a20.pcm -fmodule-file=%t/b20.pcm
+
+#include "a20.h"
+#include "b20.h"
+int k = n;
diff --git a/test/Modules/header-in-multiple-maps.cpp b/test/Modules/header-in-multiple-maps.cpp
new file mode 100644
index 0000000..a9c0c80
--- /dev/null
+++ b/test/Modules/header-in-multiple-maps.cpp
@@ -0,0 +1,9 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/header-in-multiple-maps -fmodule-map-file=%S/Inputs/header-in-multiple-maps/map1 -verify %s
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/header-in-multiple-maps -fmodule-map-file=%S/Inputs/header-in-multiple-maps/map2 -verify %s
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/header-in-multiple-maps -fmodule-map-file=%S/Inputs/header-in-multiple-maps/map3 -verify %s
+// expected-no-diagnostics
+
+#include "a.h"
+#include "a.h"
+A *p;
diff --git a/test/Modules/ignored_macros.m b/test/Modules/ignored_macros.m
index e8ee50a..669db4d 100644
--- a/test/Modules/ignored_macros.m
+++ b/test/Modules/ignored_macros.m
@@ -10,7 +10,7 @@
 // RUN: %clang_cc1 -fmodules-cache-path=%t.modules -fmodules -I %S/Inputs -emit-pch -o %t.pch -x objective-c-header %s -verify
 // RUN: not %clang_cc1 -fmodules-cache-path=%t.modules -DIGNORED=1 -fmodules -I %S/Inputs -include-pch %t.pch %s > %t.err 2>&1
 // RUN: FileCheck -check-prefix=CHECK-CONFLICT %s < %t.err
-// CHECK-CONFLICT: module 'ignored_macros' found in both
+// CHECK-CONFLICT: PCH was compiled with module cache path
 
 // Third trial: pass -DIGNORED=1 only to the second invocation, but
 // make it ignored. There should be no failure, IGNORED is defined in
diff --git a/test/Modules/implementation-of-module.m b/test/Modules/implementation-of-module.m
index b398404..818cce8 100644
--- a/test/Modules/implementation-of-module.m
+++ b/test/Modules/implementation-of-module.m
@@ -16,7 +16,7 @@
 // RUN: %clang_cc1 -x objective-c-header -fmodules -fmodules-cache-path=%t -w -Werror=auto-import %s -I %S/Inputs \
 // RUN:     -fmodule-implementation-of category_right -emit-pch -o %t.pch
 // RUN: %clang_cc1 -x objective-c-header -fmodules -fmodules-cache-path=%t -w -Werror=auto-import %s -I %S/Inputs \
-// RUN:     -DWITH_PREFIX -include-pch %t.pch -fmodule-implementation-of category_right
+// RUN:     -DWITH_PREFIX -fmodules-ignore-macro=WITH_PREFIX -include-pch %t.pch -fmodule-implementation-of category_right
 
 #ifndef WITH_PREFIX
 
diff --git a/test/Modules/inferred-attributes.mm b/test/Modules/inferred-attributes.mm
new file mode 100644
index 0000000..5fc1d62
--- /dev/null
+++ b/test/Modules/inferred-attributes.mm
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -F %S/Inputs/inferred-attr -fsyntax-only -verify %s
+// expected-no-diagnostics
+extern "C" {
+@import InferredExternC;
+}
diff --git a/test/Modules/initializer_list.cpp b/test/Modules/initializer_list.cpp
index 0cbcbbb..ea6e282 100644
--- a/test/Modules/initializer_list.cpp
+++ b/test/Modules/initializer_list.cpp
@@ -1,7 +1,23 @@
 // RUN: rm -rf %t
-// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -verify -std=c++11
+//
+// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodules-cache-path=%t \
+// RUN:     -I %S/Inputs/initializer_list \
+// RUN:     -fmodule-map-file=%S/Inputs/initializer_list/direct.modulemap \
+// RUN:     %s -verify -std=c++11
+//
+// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodules-cache-path=%t \
+// RUN:     -I %S/Inputs/initializer_list \
+// RUN:     -fmodule-map-file=%S/Inputs/initializer_list/indirect.modulemap \
+// RUN:     %s -verify -std=c++11 -DINCLUDE_DIRECT
 
 // expected-no-diagnostics
+
+#ifdef INCLUDE_DIRECT
+#include "direct.h"
+auto k = {1, 2, 3};
+#endif
+
 @import initializer_list;
 
+auto v = {1, 2, 3};
 int n = std::min({1, 2, 3});
diff --git a/test/Modules/macro-reexport.cpp b/test/Modules/macro-reexport.cpp
new file mode 100644
index 0000000..1df49b9
--- /dev/null
+++ b/test/Modules/macro-reexport.cpp
@@ -0,0 +1,30 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fsyntax-only -DC1 -I%S/Inputs/macro-reexport %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DC1 -I%S/Inputs/macro-reexport -fmodules %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DD1 -I%S/Inputs/macro-reexport %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DD1 -I%S/Inputs/macro-reexport -fmodules %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DD2 -I%S/Inputs/macro-reexport %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DD2 -I%S/Inputs/macro-reexport -fmodules %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DF1 -I%S/Inputs/macro-reexport %s -fmodules-cache-path=%t -verify
+// RUN: %clang_cc1 -fsyntax-only -DF1 -I%S/Inputs/macro-reexport -fmodules %s -fmodules-cache-path=%t -verify
+
+#if defined(F1)
+#include "f1.h"
+void f() { return assert(true); } // expected-error {{undeclared identifier 'd'}}
+#include "e2.h" // undefines d1's macro
+void g() { return assert(true); } // expected-error {{undeclared identifier 'assert'}}
+#elif defined(D1)
+#include "e1.h" // undefines c1's macro but not d1's macro
+#include "d1.h"
+void f() { return assert(true); } // expected-error {{undeclared identifier 'd'}}
+#include "e2.h" // undefines d1's macro
+void g() { return assert(true); } // expected-error {{undeclared identifier 'assert'}}
+#elif defined(D2)
+#include "d2.h"
+void f() { return assert(true); } // expected-error {{undeclared identifier 'b'}}
+#else
+// e2 undefines d1's macro, which overrides c1's macro.
+#include "e2.h"
+#include "c1.h"
+void f() { return assert(true); } // expected-error {{undeclared identifier 'assert'}}
+#endif
diff --git a/test/Modules/macro-reexport/macro-reexport.cpp b/test/Modules/macro-reexport/macro-reexport.cpp
deleted file mode 100644
index af2ec84..0000000
--- a/test/Modules/macro-reexport/macro-reexport.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-// RUN: rm -rf %t
-// RUN: %clang_cc1 -fsyntax-only -DC1 -I. %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DC1 -I. -fmodules %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DD1 -I. %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DD1 -I. -fmodules %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DD2 -I. %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DD2 -I. -fmodules %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DF1 -I. %s -fmodules-cache-path=%t -verify
-// RUN: %clang_cc1 -fsyntax-only -DF1 -I. -fmodules %s -fmodules-cache-path=%t -verify
-
-#if defined(F1)
-#include "f1.h"
-void f() { return assert(true); } // expected-error {{undeclared identifier 'd'}}
-#include "e2.h" // undefines d1's macro
-void g() { return assert(true); } // expected-error {{undeclared identifier 'assert'}}
-#elif defined(D1)
-#include "e1.h" // undefines c1's macro but not d1's macro
-#include "d1.h"
-void f() { return assert(true); } // expected-error {{undeclared identifier 'd'}}
-#include "e2.h" // undefines d1's macro
-void g() { return assert(true); } // expected-error {{undeclared identifier 'assert'}}
-#elif defined(D2)
-#include "d2.h"
-void f() { return assert(true); } // expected-error {{undeclared identifier 'b'}}
-#else
-// e2 undefines d1's macro, which overrides c1's macro.
-#include "e2.h"
-#include "c1.h"
-void f() { return assert(true); } // expected-error {{undeclared identifier 'assert'}}
-#endif
diff --git a/test/Modules/malformed.cpp b/test/Modules/malformed.cpp
index cd7b334..2554c3a 100644
--- a/test/Modules/malformed.cpp
+++ b/test/Modules/malformed.cpp
@@ -1,23 +1,37 @@
+// This test explicitly cd's to the test/Modules directory so that we can test
+// that filenames found via relative -I paths are printed correctly.
+//
+// REQUIRES: shell
+//
 // RUN: rm -rf %t
-// RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/malformed -DHEADER="a1.h" %s 2>&1 | FileCheck %s --check-prefix=CHECK-A
-// RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/malformed -DHEADER="b1.h" %s 2>&1 | FileCheck %s --check-prefix=CHECK-B
+// RUN: cd %S
+// RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="a1.h" %s 2>&1 | FileCheck %s --check-prefix=CHECK-A
+// RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="b1.h" %s 2>&1 | FileCheck %s --check-prefix=CHECK-B
+// RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="c.h" malformed.cpp 2>&1 | FileCheck %s --check-prefix=CHECK-C
 
 #define STR2(x) #x
 #define STR(x) STR2(x)
 #include STR(HEADER)
 
 // CHECK-A: While building module 'malformed_a'
-// CHECK-A: a1.h:1:{{.*}} error: expected '}'
-// CHECK-A: a1.h:1:{{.*}} note: to match this '{'
+// CHECK-A: {{^}}Inputs/malformed/a1.h:1:{{.*}} error: expected '}'
+// CHECK-A: {{^}}Inputs/malformed/a1.h:1:{{.*}} note: to match this '{'
 //
 // CHECK-A: While building module 'malformed_a'
-// CHECK-A: a2.h:1:{{.*}} error: extraneous closing brace
+// CHECK-A: {{^}}Inputs/malformed/a2.h:1:{{.*}} error: extraneous closing brace
 
 // CHECK-B: While building module 'malformed_b'
-// CHECK-B: b1.h:2:{{.*}} error: expected '}'
-// CHECK-B: b1.h:1:{{.*}} note: to match this '{'
-// CHECK-B: b1.h:3:{{.*}} error: extraneous closing brace ('}')
+// CHECK-B: {{^}}Inputs/malformed/b1.h:2:{{.*}} error: expected '}'
+// CHECK-B: {{^}}Inputs/malformed/b1.h:1:{{.*}} note: to match this '{'
+// CHECK-B: {{^}}Inputs/malformed/b1.h:3:{{.*}} error: extraneous closing brace ('}')
 //
 // CHECK-B: While building module 'malformed_b'
-// CHECK-B: b2.h:1:{{.*}} error: redefinition of 'g'
-// CHECK-B: b2.h:1:{{.*}} note: previous definition is here
+// CHECK-B: {{^}}Inputs/malformed/b2.h:1:{{.*}} error: redefinition of 'g'
+// CHECK-B: {{^}}Inputs/malformed/b2.h:1:{{.*}} note: previous definition is here
+
+void test() { f<int>(); }
+// Test that we use relative paths to name files within an imported module.
+//
+// CHECK-C: In module 'c' imported from malformed.cpp:14:
+// CHECK-C: {{^}}Inputs/malformed/c.h:1:33: error: type 'int' cannot be used prior to '::'
+// CHECK-C: {{^}}malformed.cpp:[[@LINE-5]]:15: note: in instantiation of
diff --git a/test/Modules/merge-anon-in-template.cpp b/test/Modules/merge-anon-in-template.cpp
new file mode 100644
index 0000000..6e4e6e0
--- /dev/null
+++ b/test/Modules/merge-anon-in-template.cpp
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-anon-in-template -verify %s
+// expected-no-diagnostics
+#include "a.h"
+#include "c.h"
+is_floating<int>::type t;
diff --git a/test/Modules/merge-decl-context.cpp b/test/Modules/merge-decl-context.cpp
new file mode 100644
index 0000000..90c234b
--- /dev/null
+++ b/test/Modules/merge-decl-context.cpp
@@ -0,0 +1,24 @@
+// RUN: rm -rf %t
+
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-name=b -o %t/b.pcm -fmodule-maps \
+// RUN:     -emit-module %S/Inputs/merge-decl-context/merge-decl-context.modulemap -I%S/Inputs \
+// RUN:     -I %S/Inputs/merge-decl-context
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-name=c -o %t/c.pcm -fmodule-maps \
+// RUN:     -fmodule-file=%t/b.pcm \
+// RUN:     -emit-module %S/Inputs/merge-decl-context/merge-decl-context.modulemap -I%S/Inputs \
+// RUN:     -I %S/Inputs/merge-decl-context
+
+// Use the two modules in a single compile.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-file=%t/c.pcm -fmodule-file=%t/b.pcm \
+// RUN:     -fmodule-map-file=%S/Inputs/merge-decl-context/merge-decl-context.modulemap -I%S/Inputs \
+// RUN:     -emit-llvm -o %t/test.o %s
+
+#include "Inputs/merge-decl-context/a.h"
+#include "Inputs/merge-decl-context/b.h"
+#include "Inputs/merge-decl-context/c.h"
+
+void t() {
+  ff(42);
+}
+
+
diff --git a/test/Modules/merge-decl-order.cpp b/test/Modules/merge-decl-order.cpp
new file mode 100644
index 0000000..d3b21fd
--- /dev/null
+++ b/test/Modules/merge-decl-order.cpp
@@ -0,0 +1,9 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-decl-order -verify %s
+// expected-no-diagnostics
+
+// Check that we include all decls from 'a' before the decls from 'b' in foo's
+// redecl chain. If we don't, then name lookup only finds invisible friend
+// declarations and the lookup below will fail.
+#include "b.h"
+N::foo *use;
diff --git a/test/Modules/merge-dependent-friends.cpp b/test/Modules/merge-dependent-friends.cpp
new file mode 100644
index 0000000..0b0c903
--- /dev/null
+++ b/test/Modules/merge-dependent-friends.cpp
@@ -0,0 +1,4 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-dependent-friends -verify %s
+// expected-no-diagnostics
+#include "d.h"
diff --git a/test/Modules/merge-friends.cpp b/test/Modules/merge-friends.cpp
new file mode 100644
index 0000000..8284bfe
--- /dev/null
+++ b/test/Modules/merge-friends.cpp
@@ -0,0 +1,5 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-friends -verify %s
+// expected-no-diagnostics
+#include "friend.h"
+N::foo *use;
diff --git a/test/Modules/merge-implicit-special-members.cpp b/test/Modules/merge-implicit-special-members.cpp
new file mode 100644
index 0000000..a8b917c
--- /dev/null
+++ b/test/Modules/merge-implicit-special-members.cpp
@@ -0,0 +1,5 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-implicit-special-members -verify %s
+// expected-no-diagnostics
+#include "c.h"
+int n = pthread_mutex_t().lock;
diff --git a/test/Modules/merge-name-for-linkage.cpp b/test/Modules/merge-name-for-linkage.cpp
new file mode 100644
index 0000000..1700b61
--- /dev/null
+++ b/test/Modules/merge-name-for-linkage.cpp
@@ -0,0 +1,8 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-name-for-linkage -verify %s
+// expected-no-diagnostics
+typedef union {} pthread_mutex_t;
+#include "a.h"
+pthread_mutex_t x;
+#include "b.h"
+pthread_mutex_t y;
diff --git a/test/Modules/merge-nested-templates.cpp b/test/Modules/merge-nested-templates.cpp
new file mode 100644
index 0000000..42764ea
--- /dev/null
+++ b/test/Modules/merge-nested-templates.cpp
@@ -0,0 +1,4 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-nested-templates -verify %s
+// expected-no-diagnostics
+#include "c.h"
diff --git a/test/Modules/merge-template-members.cpp b/test/Modules/merge-template-members.cpp
new file mode 100644
index 0000000..1fdaa9c
--- /dev/null
+++ b/test/Modules/merge-template-members.cpp
@@ -0,0 +1,27 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-template-members -verify -emit-llvm-only %s -DTEST=1
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-template-members -verify -emit-llvm-only %s -DTEST=2
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I%S/Inputs/merge-template-members -verify -emit-llvm-only %s -DTEST=3
+// expected-no-diagnostics
+
+#if TEST == 1
+
+template<typename> struct A { int n; };
+template<typename> struct B { typedef A<void> C; };
+template class B<int>;
+
+#include "update.h"
+B<int>::C use2;
+
+#elif TEST == 2
+
+#include "c.h"
+N::A<int> ai;
+
+#elif TEST == 3
+
+#include "merge.h"
+
+#else
+#error Unknown test
+#endif
diff --git a/test/Modules/merge-vtable-codegen.cpp b/test/Modules/merge-vtable-codegen.cpp
new file mode 100644
index 0000000..7372073
--- /dev/null
+++ b/test/Modules/merge-vtable-codegen.cpp
@@ -0,0 +1,24 @@
+// RUN: rm -rf %t
+
+// First, build two modules that both re-export the same header.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-name=b -o %t/b.pcm -fmodule-maps \
+// RUN:     -emit-module %S/Inputs/merge-vtable-codegen/merge-vtable-codegen.modulemap \
+// RUN:     -I %S/Inputs/merge-vtable-codegen
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-name=c -o %t/c.pcm -fmodule-maps \
+// RUN:     -emit-module %S/Inputs/merge-vtable-codegen/merge-vtable-codegen.modulemap \
+// RUN:     -I %S/Inputs/merge-vtable-codegen
+
+// Use the two modules in a single compile.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-file=%t/b.pcm -fmodule-file=%t/c.pcm \
+// RUN:     -fmodule-map-file=%S/Inputs/merge-vtable-codegen/merge-vtable-codegen.modulemap \
+// RUN:     -emit-llvm -o %t/test.o %s
+
+// Note that order is important:
+// Module 'c' just reexports A, while module 'b' defines a method that uses a
+// virtual method of A.
+#include "Inputs/merge-vtable-codegen/c.h"
+#include "Inputs/merge-vtable-codegen/b.h"
+
+void t() {
+  b(nullptr);
+}
diff --git a/test/Modules/modular_maps.cpp b/test/Modules/modular_maps.cpp
index 484e727..606c979 100644
--- a/test/Modules/modular_maps.cpp
+++ b/test/Modules/modular_maps.cpp
@@ -1,6 +1,18 @@
 // RUN: rm -rf %t
-// RUN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=%S/Inputs/modular_maps/modulea.map -fmodule-map-file=%S/Inputs/modular_maps/modulec.map -I %S/Inputs/modular_maps %s -verify
-// RUN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=%S/Inputs/modular_maps/modulec.map -fmodule-map-file=%S/Inputs/modular_maps/modulea.map -I %S/Inputs/modular_maps %s -verify
+//
+// RxN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=%S/Inputs/modular_maps/modulea.map -fmodule-map-file=%S/Inputs/modular_maps/modulec.map -I %S/Inputs/modular_maps %s -verify
+// RxN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=%S/Inputs/modular_maps/modulec.map -fmodule-map-file=%S/Inputs/modular_maps/modulea.map -I %S/Inputs/modular_maps %s -verify
+//
+// RxN: cd %S
+// RxN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=Inputs/modular_maps/modulea.map -fmodule-map-file=Inputs/modular_maps/modulec.map -I Inputs/modular_maps %s -verify
+// RxN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=Inputs/modular_maps/modulec.map -fmodule-map-file=Inputs/modular_maps/modulea.map -I Inputs/modular_maps %s -verify
+//
+// RUN: cd %S
+// RUN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=Inputs/modular_maps/modulea-cwd.map -fmodule-map-file=Inputs/modular_maps/modulec-cwd.map -I Inputs/modular_maps %s -verify -fmodule-map-file-home-is-cwd
+// RxN: %clang_cc1 -x objective-c++ -fmodules-cache-path=%t -fmodules -fmodule-map-file=Inputs/modular_maps/modulec-cwd.map -fmodule-map-file=Inputs/modular_maps/modulea-cwd.map -I Inputs/modular_maps %s -verify -fmodule-map-file-home-is-cwd
+
+// chdir is unsupported on Lit internal runner.
+// REQUIRES: shell
 
 #include "common.h"
 #include "a.h"
diff --git a/test/Modules/modulemap-locations.m b/test/Modules/modulemap-locations.m
index 9acdcd6..949c478 100644
--- a/test/Modules/modulemap-locations.m
+++ b/test/Modules/modulemap-locations.m
@@ -1,5 +1,5 @@
 // RUN: rm -rf %t 
-// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/ModuleMapLocations/Module_ModuleMap -I %S/Inputs/ModuleMapLocations/Both -F %S/Inputs/ModuleMapLocations -x objective-c -fsyntax-only %s -verify
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/ModuleMapLocations/Module_ModuleMap -I %S/Inputs/ModuleMapLocations/Both -F %S/Inputs/ModuleMapLocations -I %S/Inputs/ModuleMapLocations -F %S/Inputs -x objective-c -fsyntax-only %s -verify
 
 // regular
 @import module_modulemap;
diff --git a/test/Modules/no-implicit-builds.cpp b/test/Modules/no-implicit-builds.cpp
new file mode 100644
index 0000000..d9e8fa1
--- /dev/null
+++ b/test/Modules/no-implicit-builds.cpp
@@ -0,0 +1,33 @@
+// RUN: rm -rf %t
+
+// Produce an error if a module is needed, but not found.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t \
+// RUN:     -fmodule-map-file=%S/Inputs/no-implicit-builds/b.modulemap \
+// RUN:     -fno-implicit-modules %s -verify
+
+// Compile the module and put it into the cache.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t \
+// RUN:     -fmodule-map-file=%S/Inputs/no-implicit-builds/b.modulemap \
+// RUN:     %s -Rmodule-build 2>&1 | FileCheck --check-prefix=CHECK-CACHE-BUILD %s
+// CHECK-CACHE-BUILD: {{building module 'b'}}
+
+// Produce an error if a module is found in the cache but implicit modules is off.
+// Note that the command line must match the command line for the first check, otherwise
+// this check might not find the module in the cache and trivially succeed.
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodules-cache-path=%t \
+// RUN:     -fmodule-map-file=%S/Inputs/no-implicit-builds/b.modulemap \
+// RUN:     %s -Rmodule-build -fno-implicit-modules -verify
+
+// Verify that we can still pass the module via -fmodule-file when implicit modules
+// are switched off:
+// - First, explicitly compile the module:
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-name=b -o %t/b.pcm \
+// RUN:     -emit-module %S/Inputs/no-implicit-builds/b.modulemap \
+// RUN:     -fno-implicit-modules
+//
+// - Next, verify that we can load it:
+// RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fmodule-file=%t/b.pcm \
+// RUN:     -fmodule-map-file=%S/Inputs/no-implicit-builds/b.modulemap \
+// RUN:     -fno-implicit-modules %s
+
+#include "Inputs/no-implicit-builds/b.h"  // expected-error {{is needed but has not been provided}}
diff --git a/test/Modules/no-implicit-maps.cpp b/test/Modules/no-implicit-maps.cpp
new file mode 100644
index 0000000..cb270a0
--- /dev/null
+++ b/test/Modules/no-implicit-maps.cpp
@@ -0,0 +1,3 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -x objective-c -fno-modules-implicit-maps -fmodules-cache-path=%t -fmodules -I %S/Inputs/private %s -verify
+@import libPrivate1;  // expected-error {{not found}}
diff --git a/test/Modules/pr21217.cpp b/test/Modules/pr21217.cpp
new file mode 100644
index 0000000..a439c97
--- /dev/null
+++ b/test/Modules/pr21217.cpp
@@ -0,0 +1,3 @@
+// RUN: not %clang_cc1 -fmodules -fmodule-map-file=does-not-exist.modulemap -verify %s 2>&1 | FileCheck %s
+
+// CHECK: module map file 'does-not-exist.modulemap' not found
diff --git a/test/Modules/preprocess.m b/test/Modules/preprocess.m
index 5c32997..9b563fe 100644
--- a/test/Modules/preprocess.m
+++ b/test/Modules/preprocess.m
@@ -1,9 +1,14 @@
 // RUN: rm -rf %t
-// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -include %S/Inputs/preprocess-prefix.h -E %s | FileCheck -strict-whitespace %s
-// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -x objective-c-header -emit-pch %S/Inputs/preprocess-prefix.h -o %t.pch
-// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -include-pch %t.pch -E %s | FileCheck -strict-whitespace %s
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -I %S/Inputs/preprocess -include %S/Inputs/preprocess-prefix.h -E %s | FileCheck -strict-whitespace %s
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -I %S/Inputs/preprocess -x objective-c-header -emit-pch %S/Inputs/preprocess-prefix.h -o %t.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -I %S/Inputs/preprocess -include-pch %t.pch -E %s | FileCheck -strict-whitespace %s
+//
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -I %S/Inputs/preprocess -x objective-c++ -include %S/Inputs/preprocess-prefix.h -E %s | FileCheck -strict-whitespace %s
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -I %S/Inputs/preprocess -x objective-c++-header -emit-pch %S/Inputs/preprocess-prefix.h -o %t.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs -I %S/Inputs/preprocess -x objective-c++ -include-pch %t.pch -E %s | FileCheck -strict-whitespace %s
 #import "diamond_right.h"
 #import "diamond_right.h" // to check that imports get their own line
+#include "file.h"
 void test() {
   top_left_before();
   left_and_right();
@@ -15,6 +20,7 @@
 
 // CHECK: @import diamond_right; /* clang -E: implicit import for "{{.*}}diamond_right.h" */{{$}}
 // CHECK: @import diamond_right; /* clang -E: implicit import for "{{.*}}diamond_right.h" */{{$}}
+// CHECK: @import file; /* clang -E: implicit import for "{{.*}}file.h" */{{$}}
 // CHECK-NEXT: void test() {{{$}}
 // CHECK-NEXT:    top_left_before();{{$}}
 // CHECK-NEXT:    left_and_right();{{$}}
diff --git a/test/Modules/private.cpp b/test/Modules/private.cpp
index 93b4b94..31e60e4 100644
--- a/test/Modules/private.cpp
+++ b/test/Modules/private.cpp
@@ -1,5 +1,6 @@
 // RUN: rm -rf %t
 // RUN: %clang_cc1 -x objective-c -fmodules-cache-path=%t -fmodules -I %S/Inputs/private %s -verify
+// RUN: %clang_cc1 -x objective-c -fmodules-cache-path=%t -fmodules -I %S/Inputs/private %s -fsyntax-only -Wno-private-header
 
 #include "common.h"
 @import libPrivate1;
diff --git a/test/Modules/redecl-templates.cpp b/test/Modules/redecl-templates.cpp
new file mode 100644
index 0000000..6bbec02
--- /dev/null
+++ b/test/Modules/redecl-templates.cpp
@@ -0,0 +1,32 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -x c++ -I %S/Inputs/redecl-templates %s -verify -std=c++14
+// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t -I %S/Inputs/redecl-templates %s -verify -std=c++14
+// expected-no-diagnostics
+
+template<int N> struct A {};
+template<int N> using X = A<N>;
+
+template<int N> constexpr void f() {}
+template<int N> constexpr void g() { f<N>(); }
+
+template<int N> extern int v;
+template<int N> int &w = v<N>;
+
+#include "a.h"
+
+// Be careful not to mention A here, that'll import the decls from "a.h".
+int g(X<1> *);
+X<1> *p = 0;
+
+// This will implicitly instantiate A<1> if we haven't imported the explicit
+// specialization declaration from "a.h".
+int k = g(p);
+// Likewise for f and v.
+void h() { g<1>(); }
+int &x = w<1>;
+
+// This is OK: we declared the explicit specialization before we triggered
+// instantiation of this specialization.
+template<> struct A<1> {};
+template<> constexpr void f<1>() {}
+template<> int v<1>;
diff --git a/test/Modules/redecls.m b/test/Modules/redecls.m
new file mode 100644
index 0000000..fa643b9
--- /dev/null
+++ b/test/Modules/redecls.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t.mcp
+// RUN: %clang_cc1 -fmodules %s -emit-pch -o %t1.pch -fmodules-cache-path=%t.mcp -I %S/Inputs/redecls
+// RUN: %clang_cc1 -fmodules %s -emit-pch -o %t2.pch -include-pch %t1.pch -fmodules-cache-path=%t.mcp -I %S/Inputs/redecls
+// RUN: %clang_cc1 -fmodules %s -fsyntax-only -include-pch %t2.pch -I %S/Inputs/redecls -fmodules-cache-path=%t.mcp -verify
+
+#ifndef HEADER1
+#define HEADER1
+
+@import a;
+
+#elif !defined(HEADER2)
+#define HEADER2
+
+@class AA;
+@import b;
+
+#else
+
+// rdar://13712705
+@interface SS : AA
+@end
+
+#warning parsed this
+#endif
+// expected-warning@-2{{parsed this}}
diff --git a/test/Modules/redecls/main.m b/test/Modules/redecls/main.m
deleted file mode 100644
index bf3788a..0000000
--- a/test/Modules/redecls/main.m
+++ /dev/null
@@ -1,27 +0,0 @@
-// RUN: rm -rf %t.mcp
-// RUN: %clang_cc1 -fmodules -x objective-c -emit-module -fmodule-name=a %S/module.map -fmodules-cache-path=%t.mcp
-// RUN: %clang_cc1 -fmodules -x objective-c -emit-module -fmodule-name=b %S/module.map -fmodules-cache-path=%t.mcp
-// RUN: %clang_cc1 -fmodules %s -emit-pch -o %t1.pch -fmodules-cache-path=%t.mcp -I %S
-// RUN: %clang_cc1 -fmodules %s -emit-pch -o %t2.pch -include-pch %t1.pch -fmodules-cache-path=%t.mcp -I %S
-// RUN: %clang_cc1 -fmodules %s -fsyntax-only -include-pch %t2.pch -I %S -fmodules-cache-path=%t.mcp -verify
-
-#ifndef HEADER1
-#define HEADER1
-
-@import a;
-
-#elif !defined(HEADER2)
-#define HEADER2
-
-@class AA;
-@import b;
-
-#else
-
-// rdar://13712705
-@interface SS : AA
-@end
-
-#warning parsed this
-#endif
-// expected-warning@-2{{parsed this}}
diff --git a/test/Modules/relative-dep-gen.cpp b/test/Modules/relative-dep-gen.cpp
new file mode 100644
index 0000000..c817177
--- /dev/null
+++ b/test/Modules/relative-dep-gen.cpp
@@ -0,0 +1,26 @@
+// REQUIRES: shell
+//
+// RUN: cd %S
+// RUN: rm -rf %t
+// RUN: mkdir %t
+//
+// RUN: %clang_cc1 -cc1 -fmodule-name=relative-dep-gen -emit-module -x c++ Inputs/relative-dep-gen.modulemap -dependency-file %t/build.d -MT mod.pcm -o %t/mod.pcm
+// RUN: %clang_cc1 -cc1 -fmodule-map-file=Inputs/relative-dep-gen.modulemap -fmodule-file=%t/mod.pcm -dependency-file %t/use-explicit.d -MT use.o relative-dep-gen.cpp -fsyntax-only
+// RUN: %clang_cc1 -cc1 -fmodule-map-file=Inputs/relative-dep-gen.modulemap -dependency-file %t/use-implicit.d relative-dep-gen.cpp -MT use.o -fsyntax-only
+//
+// RUN: FileCheck --check-prefix=CHECK-BUILD %s < %t/build.d
+// RUN: FileCheck --check-prefix=CHECK-USE %s < %t/use-explicit.d
+// RUN: FileCheck --check-prefix=CHECK-USE %s < %t/use-implicit.d
+//
+// RUN: %clang_cc1 -cc1 -fmodule-name=relative-dep-gen -emit-module -x c++ Inputs/relative-dep-gen-cwd.modulemap -dependency-file %t/build-cwd.d -MT mod.pcm -o %t/mod-cwd.pcm -fmodule-map-file-home-is-cwd
+// RUN: %clang_cc1 -cc1 -fmodule-map-file=Inputs/relative-dep-gen-cwd.modulemap -fmodule-file=%t/mod-cwd.pcm -dependency-file %t/use-explicit-cwd.d -MT use.o relative-dep-gen.cpp -fsyntax-only -fmodule-map-file-home-is-cwd
+// RUN: %clang_cc1 -cc1 -fmodule-map-file=Inputs/relative-dep-gen-cwd.modulemap -dependency-file %t/use-implicit-cwd.d relative-dep-gen.cpp -MT use.o -fsyntax-only -fmodule-map-file-home-is-cwd
+//
+// RUN: FileCheck --check-prefix=CHECK-BUILD %s < %t/build-cwd.d
+// RUN: FileCheck --check-prefix=CHECK-USE %s < %t/use-explicit-cwd.d
+// RUN: FileCheck --check-prefix=CHECK-USE %s < %t/use-implicit-cwd.d
+
+#include "Inputs/relative-dep-gen-1.h"
+
+// CHECK-BUILD: mod.pcm: Inputs/relative-dep-gen-1.h Inputs/relative-dep-gen-2.h
+// CHECK-USE: use.o: relative-dep-gen.cpp Inputs/relative-dep-gen-1.h
diff --git a/test/Modules/requires.m b/test/Modules/requires.m
index b8b2c55..ff0ddfe 100644
--- a/test/Modules/requires.m
+++ b/test/Modules/requires.m
@@ -1,6 +1,8 @@
 // RUN: rm -rf %t
-// RUN: %clang_cc1 -Wauto-import -fmodules-cache-path=%t -fmodules -F %S/Inputs %s -verify
+// RUN: %clang_cc1 -Wauto-import -fmodules-cache-path=%t -fmodules -F %S/Inputs %s -verify -fmodule-feature custom_req1
 
 @import DependsOnModule.CXX; // expected-error{{module 'DependsOnModule.CXX' requires feature 'cplusplus'}}
 @import DependsOnModule.NotCXX;
 @import DependsOnModule.NotObjC; // expected-error{{module 'DependsOnModule.NotObjC' is incompatible with feature 'objc'}}
+@import DependsOnModule.CustomReq1; // OK
+@import DependsOnModule.CustomReq2; // expected-error{{module 'DependsOnModule.CustomReq2' requires feature 'custom_req2'}}
diff --git a/test/Modules/resolution-change.m b/test/Modules/resolution-change.m
index b725a64..6882fe4 100644
--- a/test/Modules/resolution-change.m
+++ b/test/Modules/resolution-change.m
@@ -17,9 +17,9 @@
 // RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -include-pch %t-A.pch %s -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-NOA %s
 // CHECK-NOA: module 'A' in AST file '{{.*A.*pcm}}' (imported by AST file '{{.*DependsOnA.*pcm}}') is not defined in any loaded module map
 
-// Use the PCH and have it resolve the the other A
+// Use the PCH and have it resolve to the other A
 // RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I %S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-WRONGA %s
-// CHECK-WRONGA: module 'A' imported by AST file '{{.*DependsOnA.*pcm}}' found in a different module map file ({{.*path2.*}}) than when the importing AST file was built ({{.*path1.*}})
+// CHECK-WRONGA: module 'A' was built in directory '{{.*Inputs.modules-with-same-name.path1.A}}' but now resides in directory '{{.*Inputs.modules-with-same-name.path2.A}}'
 
 #ifndef HEADER
 #define HEADER
diff --git a/test/Modules/self-import-header.m b/test/Modules/self-import-header.m
new file mode 100644
index 0000000..9b4bd5d
--- /dev/null
+++ b/test/Modules/self-import-header.m
@@ -0,0 +1,9 @@
+// rdar://13840148
+
+// RUN: rm -rf %t
+// RUN: %clang -fsyntax-only -isysroot %S/Inputs/System/usr/include -fmodules -fmodules-cache-path=%t \
+// RUN:    -target x86_64-darwin \
+// RUN:    -F %S -F %S/Inputs/self-import-header -I %S/Inputs/self-import-header \
+// RUN:    %s -D__need_wint_t -Werror=implicit-function-declaration
+
+@import af;
diff --git a/test/Modules/self-import-header/test.m b/test/Modules/self-import-header/test.m
deleted file mode 100644
index 377c01d..0000000
--- a/test/Modules/self-import-header/test.m
+++ /dev/null
@@ -1,8 +0,0 @@
-// rdar://13840148
-
-// RUN: rm -rf %t
-// RUN: %clang -fsyntax-only -isysroot %S/../Inputs/System/usr/include -fmodules -fmodules-cache-path=%t \
-// RUN:    -target x86_64-darwin \
-// RUN:    -F %S -I %S %s -D__need_wint_t -Werror=implicit-function-declaration
-
-@import af;
diff --git a/test/Modules/templates-2.mm b/test/Modules/templates-2.mm
index b7ceafb..8a752f7 100644
--- a/test/Modules/templates-2.mm
+++ b/test/Modules/templates-2.mm
@@ -23,14 +23,14 @@
 // CHECK-LABEL: define {{.*}} @_ZN27EmitDefaultedSpecialMembers11SmallStringILj256EED1Ev(
 // CHECK: call {{.*}} @_ZN27EmitDefaultedSpecialMembers11SmallStringILj256EED2Ev(
 
-// CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers11SmallStringILj256EED2Ev(
-// CHECK: call void @_ZN27EmitDefaultedSpecialMembers11SmallVectorIcLj256EED2Ev(
-// CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers11SmallVectorIcLj256EED2Ev(
-// CHECK: call void @_ZN27EmitDefaultedSpecialMembers15SmallVectorImplIcED2Ev(
-// CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers15SmallVectorImplIcED2Ev(
-
 // CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers11SmallStringILj256EEC2Ev(
 // CHECK: call void @_ZN27EmitDefaultedSpecialMembers11SmallVectorIcLj256EEC2Ev(
 // CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers11SmallVectorIcLj256EEC2Ev(
 // CHECK: call void @_ZN27EmitDefaultedSpecialMembers15SmallVectorImplIcEC2Ev(
 // CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers15SmallVectorImplIcEC2Ev(
+
+// CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers11SmallStringILj256EED2Ev(
+// CHECK: call void @_ZN27EmitDefaultedSpecialMembers11SmallVectorIcLj256EED2Ev(
+// CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers11SmallVectorIcLj256EED2Ev(
+// CHECK: call void @_ZN27EmitDefaultedSpecialMembers15SmallVectorImplIcED2Ev(
+// CHECK-LABEL: define linkonce_odr void @_ZN27EmitDefaultedSpecialMembers15SmallVectorImplIcED2Ev(
diff --git a/test/OpenMP/atomic_messages.c b/test/OpenMP/atomic_messages.c
index d2d3308..ae490ee 100644
--- a/test/OpenMP/atomic_messages.c
+++ b/test/OpenMP/atomic_messages.c
@@ -63,3 +63,40 @@
 
   return a.a;
 }
+
+int writeint() {
+  int a = 0, b = 0;
+// Test for atomic write
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected an expression statement}}
+  ;
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected built-in assignment operator}}
+  foo();
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected built-in assignment operator}}
+  a += b;
+#pragma omp atomic write
+  a = 0;
+#pragma omp atomic write
+  a = b;
+  // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}}
+#pragma omp atomic write write
+  a = b;
+
+  return 0;
+}
+
+int writeS() {
+  struct S a, b;
+  // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}}
+#pragma omp atomic write write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected expression of scalar type}}
+  a = b;
+
+  return a.a;
+}
diff --git a/test/OpenMP/atomic_messages.cpp b/test/OpenMP/atomic_messages.cpp
index 3965a77..a6c07ad 100644
--- a/test/OpenMP/atomic_messages.cpp
+++ b/test/OpenMP/atomic_messages.cpp
@@ -100,11 +100,24 @@
   T a, b = 0;
 // Test for atomic write
 #pragma omp atomic write
-  // expected-error@+1 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is an l-value expression with scalar type}}
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected an expression statement}}
   ;
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}}
 #pragma omp atomic write write
   a = b;
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected built-in assignment operator}}
+  foo();
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected built-in assignment operator}}
+  a += b;
+#pragma omp atomic write
+  a = 0;
+#pragma omp atomic write
+  a = b;
 
   return T();
 }
@@ -113,11 +126,24 @@
   int a, b = 0;
 // Test for atomic write
 #pragma omp atomic write
-  // expected-error@+1 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is an l-value expression with scalar type}}
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected an expression statement}}
   ;
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}}
 #pragma omp atomic write write
   a = b;
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected built-in assignment operator}}
+  foo();
+#pragma omp atomic write
+  // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}}
+  // expected-note@+1 {{expected built-in assignment operator}}
+  a += b;
+#pragma omp atomic write
+  a = 0;
+#pragma omp atomic write
+  a = foo();
 
   return write<int>();
 }
diff --git a/test/OpenMP/atomic_read_codegen.c b/test/OpenMP/atomic_read_codegen.c
new file mode 100644
index 0000000..c97fe8c
--- /dev/null
+++ b/test/OpenMP/atomic_read_codegen.c
@@ -0,0 +1,333 @@
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp=libiomp5 -x c -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+_Bool bv, bx;
+char cv, cx;
+unsigned char ucv, ucx;
+short sv, sx;
+unsigned short usv, usx;
+int iv, ix;
+unsigned int uiv, uix;
+long lv, lx;
+unsigned long ulv, ulx;
+long long llv, llx;
+unsigned long long ullv, ullx;
+float fv, fx;
+double dv, dx;
+long double ldv, ldx;
+_Complex int civ, cix;
+_Complex float cfv, cfx;
+_Complex double cdv, cdx;
+
+typedef int int4 __attribute__((__vector_size__(16)));
+int4 int4x;
+
+struct BitFields {
+  int : 32;
+  int a : 31;
+} bfx;
+
+struct BitFields_packed {
+  int : 32;
+  int a : 31;
+} __attribute__ ((__packed__)) bfx_packed;
+
+struct BitFields2 {
+  int : 31;
+  int a : 1;
+} bfx2;
+
+struct BitFields2_packed {
+  int : 31;
+  int a : 1;
+} __attribute__ ((__packed__)) bfx2_packed;
+
+struct BitFields3 {
+  int : 11;
+  int a : 14;
+} bfx3;
+
+struct BitFields3_packed {
+  int : 11;
+  int a : 14;
+} __attribute__ ((__packed__)) bfx3_packed;
+
+struct BitFields4 {
+  short : 16;
+  int a: 1;
+  long b : 7;
+} bfx4;
+
+struct BitFields4_packed {
+  short : 16;
+  int a: 1;
+  long b : 7;
+} __attribute__ ((__packed__)) bfx4_packed;
+
+typedef float float2 __attribute__((ext_vector_type(2)));
+float2 float2x;
+
+register int rix __asm__("0");
+
+int main() {
+// CHECK: load atomic i8*
+// CHECK: store i8
+#pragma omp atomic read
+  bv = bx;
+// CHECK: load atomic i8*
+// CHECK: store i8
+#pragma omp atomic read
+  cv = cx;
+// CHECK: load atomic i8*
+// CHECK: store i8
+#pragma omp atomic read
+  ucv = ucx;
+// CHECK: load atomic i16*
+// CHECK: store i16
+#pragma omp atomic read
+  sv = sx;
+// CHECK: load atomic i16*
+// CHECK: store i16
+#pragma omp atomic read
+  usv = usx;
+// CHECK: load atomic i32*
+// CHECK: store i32
+#pragma omp atomic read
+  iv = ix;
+// CHECK: load atomic i32*
+// CHECK: store i32
+#pragma omp atomic read
+  uiv = uix;
+// CHECK: load atomic i64*
+// CHECK: store i64
+#pragma omp atomic read
+  lv = lx;
+// CHECK: load atomic i64*
+// CHECK: store i64
+#pragma omp atomic read
+  ulv = ulx;
+// CHECK: load atomic i64*
+// CHECK: store i64
+#pragma omp atomic read
+  llv = llx;
+// CHECK: load atomic i64*
+// CHECK: store i64
+#pragma omp atomic read
+  ullv = ullx;
+// CHECK: load atomic i32* bitcast (float*
+// CHECK: bitcast i32 {{.*}} to float
+// CHECK: store float
+#pragma omp atomic read
+  fv = fx;
+// CHECK: load atomic i64* bitcast (double*
+// CHECK: bitcast i64 {{.*}} to double
+// CHECK: store double
+#pragma omp atomic read
+  dv = dx;
+// CHECK: [[LD:%.+]] = load atomic i128* bitcast (x86_fp80*
+// CHECK: [[BITCAST:%.+]] = bitcast x86_fp80* [[LDTEMP:%.*]] to i128*
+// CHECK: store i128 [[LD]], i128* [[BITCAST]]
+// CHECK: [[LD:%.+]] = load x86_fp80* [[LDTEMP]]
+// CHECK: store x86_fp80 [[LD]]
+#pragma omp atomic read
+  ldv = ldx;
+// CHECK: call{{.*}} void @__atomic_load(i64 8,
+// CHECK: store i32
+// CHECK: store i32
+#pragma omp atomic read
+  civ = cix;
+// CHECK: call{{.*}} void @__atomic_load(i64 8,
+// CHECK: store float
+// CHECK: store float
+#pragma omp atomic read
+  cfv = cfx;
+// CHECK: call{{.*}} void @__atomic_load(i64 16,
+// CHECK: call{{.*}} @__kmpc_flush(
+// CHECK: store double
+// CHECK: store double
+#pragma omp atomic seq_cst read
+  cdv = cdx;
+// CHECK: load atomic i64*
+// CHECK: store i8
+#pragma omp atomic read
+  bv = ulx;
+// CHECK: load atomic i8*
+// CHECK: store i8
+#pragma omp atomic read
+  cv = bx;
+// CHECK: load atomic i8*
+// CHECK: call{{.*}} @__kmpc_flush(
+// CHECK: store i8
+#pragma omp atomic read, seq_cst
+  ucv = cx;
+// CHECK: load atomic i64*
+// CHECK: store i16
+#pragma omp atomic read
+  sv = ulx;
+// CHECK: load atomic i64*
+// CHECK: store i16
+#pragma omp atomic read
+  usv = lx;
+// CHECK: load atomic i32*
+// CHECK: call{{.*}} @__kmpc_flush(
+// CHECK: store i32
+#pragma omp atomic seq_cst, read
+  iv = uix;
+// CHECK: load atomic i32*
+// CHECK: store i32
+#pragma omp atomic read
+  uiv = ix;
+// CHECK: call{{.*}} void @__atomic_load(i64 8,
+// CHECK: store i64
+#pragma omp atomic read
+  lv = cix;
+// CHECK: load atomic i32*
+// CHECK: store i64
+#pragma omp atomic read
+  ulv = fx;
+// CHECK: load atomic i64*
+// CHECK: store i64
+#pragma omp atomic read
+  llv = dx;
+// CHECK: load atomic i128*
+// CHECK: store i64
+#pragma omp atomic read
+  ullv = ldx;
+// CHECK: call{{.*}} void @__atomic_load(i64 8,
+// CHECK: store float
+#pragma omp atomic read
+  fv = cix;
+// CHECK: load atomic i16*
+// CHECK: store double
+#pragma omp atomic read
+  dv = sx;
+// CHECK: load atomic i8*
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bx;
+// CHECK: load atomic i8*
+// CHECK: store i32
+// CHECK: store i32
+#pragma omp atomic read
+  civ = bx;
+// CHECK: load atomic i16*
+// CHECK: store float
+// CHECK: store float
+#pragma omp atomic read
+  cfv = usx;
+// CHECK: load atomic i64*
+// CHECK: store double
+// CHECK: store double
+#pragma omp atomic read
+  cdv = llx;
+// CHECK: [[I128VAL:%.+]] = load atomic i128* bitcast (<4 x i32>* @{{.+}} to i128*) monotonic
+// CHECK: [[I128PTR:%.+]] = bitcast <4 x i32>* [[LDTEMP:%.+]] to i128*
+// CHECK: store i128 [[I128VAL]], i128* [[I128PTR]]
+// CHECK: [[LD:%.+]] = load <4 x i32>* [[LDTEMP]]
+// CHECK: extractelement <4 x i32> [[LD]]
+// CHECK: store i8
+#pragma omp atomic read
+  bv = int4x[0];
+// CHECK: [[LD:%.+]] = load atomic i32* bitcast (i8* getelementptr (i8* bitcast (%{{.+}}* @{{.+}} to i8*), i64 4) to i32*) monotonic
+// CHECK: store i32 [[LD]], i32* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i32* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i32 [[LD]], 1
+// CHECK: ashr i32 [[SHL]], 1
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx.a;
+// CHECK: [[LDTEMP_VOID_PTR:%.+]] = bitcast i32* [[LDTEMP:%.+]] to i8*
+// CHECK: call void @__atomic_load(i64 4, i8* getelementptr (i8* bitcast (%struct.BitFields_packed* @bfx_packed to i8*), i64 4), i8* [[LDTEMP_VOID_PTR]], i32 5)
+// CHECK: [[LD:%.+]] = load i32* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i32 [[LD]], 1
+// CHECK: ashr i32 [[SHL]], 1
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx_packed.a;
+// CHECK: [[LD:%.+]] = load atomic i32* getelementptr inbounds (%struct.BitFields2* @bfx2, i32 0, i32 0) monotonic
+// CHECK: store i32 [[LD]], i32* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i32* [[LDTEMP]]
+// CHECK: ashr i32 [[LD]], 31
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx2.a;
+// CHECK: [[LD:%.+]] = load atomic i8* getelementptr (i8* bitcast (%struct.BitFields2_packed* @bfx2_packed to i8*), i64 3) monotonic
+// CHECK: store i8 [[LD]], i8* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i8* [[LDTEMP]]
+// CHECK: ashr i8 [[LD]], 7
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx2_packed.a;
+// CHECK: [[LD:%.+]] = load atomic i32* getelementptr inbounds (%struct.BitFields3* @bfx3, i32 0, i32 0) monotonic
+// CHECK: store i32 [[LD]], i32* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i32* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i32 [[LD]], 7
+// CHECK: ashr i32 [[SHL]], 18
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx3.a;
+// CHECK: [[LDTEMP_VOID_PTR:%.+]] = bitcast i24* [[LDTEMP:%.+]] to i8*
+// CHECK: call void @__atomic_load(i64 3, i8* getelementptr (i8* bitcast (%struct.BitFields3_packed* @bfx3_packed to i8*), i64 1), i8* [[LDTEMP_VOID_PTR]], i32 5)
+// CHECK: [[LD:%.+]] = load i24* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i24 [[LD]], 7
+// CHECK: [[ASHR:%.+]] = ashr i24 [[SHL]], 10
+// CHECK: sext i24 [[ASHR]] to i32
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx3_packed.a;
+// CHECK: [[LD:%.+]] = load atomic i64* bitcast (%struct.BitFields4* @bfx4 to i64*) monotonic
+// CHECK: store i64 [[LD]], i64* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i64* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i64 [[LD]], 47
+// CHECK: [[ASHR:%.+]] = ashr i64 [[SHL]], 63
+// CHECK: trunc i64 [[ASHR]] to i32
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx4.a;
+// CHECK: [[LD:%.+]] = load atomic i8* getelementptr inbounds (%struct.BitFields4_packed* @bfx4_packed, i32 0, i32 0, i64 2) monotonic
+// CHECK: store i8 [[LD]], i8* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i8* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i8 [[LD]], 7
+// CHECK: [[ASHR:%.+]] = ashr i8 [[SHL]], 7
+// CHECK: sext i8 [[ASHR]] to i32
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx4_packed.a;
+// CHECK: [[LD:%.+]] = load atomic i64* bitcast (%struct.BitFields4* @bfx4 to i64*) monotonic
+// CHECK: store i64 [[LD]], i64* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i64* [[LDTEMP]]
+// CHECK: [[SHL:%.+]] = shl i64 [[LD]], 40
+// CHECK: [[ASHR:%.+]] = ashr i64 [[SHL]], 57
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx4.b;
+// CHECK: [[LD:%.+]] = load atomic i8* getelementptr inbounds (%struct.BitFields4_packed* @bfx4_packed, i32 0, i32 0, i64 2) monotonic
+// CHECK: store i8 [[LD]], i8* [[LDTEMP:%.+]]
+// CHECK: [[LD:%.+]] = load i8* [[LDTEMP]]
+// CHECK: [[ASHR:%.+]] = ashr i8 [[LD]], 1
+// CHECK: sext i8 [[ASHR]] to i64
+// CHECK: store x86_fp80
+#pragma omp atomic read
+  ldv = bfx4_packed.b;
+// CHECK: [[LD:%.+]] = load atomic i32* bitcast (<2 x float>* @{{.+}} to i32*) monotonic
+// CHECK: [[BITCAST:%.+]] = bitcast <2 x float>* [[LDTEMP:%.+]] to i32*
+// CHECK: store i32 [[LD]], i32* [[BITCAST]]
+// CHECK: [[LD:%.+]] = load <2 x float>* [[LDTEMP]]
+// CHECK: extractelement <2 x float> [[LD]]
+// CHECK: store i64
+#pragma omp atomic read
+  ulv = float2x.x;
+// CHECK: call{{.*}} i{{[0-9]+}} @llvm.read_register
+// CHECK: call{{.*}} @__kmpc_flush(
+// CHECK: store double
+#pragma omp atomic read seq_cst
+  dv = rix;
+  return 0;
+}
+
+#endif
diff --git a/test/OpenMP/barrier_codegen.cpp b/test/OpenMP/barrier_codegen.cpp
new file mode 100644
index 0000000..2e817c1
--- /dev/null
+++ b/test/OpenMP/barrier_codegen.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+// CHECK: [[IDENT_T:%.+]] = type { i32, i32, i32, i32, i8* }
+// CHECK-DAG: [[EXPLICIT_BARRIER_LOC:@.+]] = {{.+}} [[IDENT_T]] { i32 0, i32 34, i32 0, i32 0, i8* getelementptr inbounds ([{{[0-9]+}} x i8]* @{{.+}}, i32 0, i32 0) }
+// CHECK-DAG: [[LOC:@.+]] = {{.+}} [[IDENT_T]] { i32 0, i32 2, i32 0, i32 0, i8* getelementptr inbounds ([{{[0-9]+}} x i8]* @{{.+}}, i32 0, i32 0) }
+
+void foo() {}
+
+template <class T>
+T tmain(T argc) {
+  static T a;
+#pragma omp barrier
+  return a + argc;
+}
+
+// CHECK-LABEL: @main
+int main(int argc, char **argv) {
+  static int a;
+#pragma omp barrier
+  // CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* [[LOC]])
+  // CHECK: call i32 @__kmpc_cancel_barrier([[IDENT_T]]* [[EXPLICIT_BARRIER_LOC]], i32 [[GTID]])
+  // CHECK: call {{.+}} [[TMAIN_INT:@.+]](i{{[0-9][0-9]}}
+  // CHECK: call {{.+}} [[TMAIN_CHAR:@.+]](i{{[0-9]}}
+  return tmain(argc) + tmain(argv[0][0]) + a;
+}
+
+// CHECK: define {{.+}} [[TMAIN_INT]](
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* [[LOC]])
+// CHECK: call i32 @__kmpc_cancel_barrier([[IDENT_T]]* [[EXPLICIT_BARRIER_LOC]], i32 [[GTID]])
+
+// CHECK: define {{.+}} [[TMAIN_CHAR]](
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* [[LOC]])
+// CHECK: call i32 @__kmpc_cancel_barrier([[IDENT_T]]* [[EXPLICIT_BARRIER_LOC]], i32 [[GTID]])
+
+#endif
diff --git a/test/OpenMP/critical_codegen.cpp b/test/OpenMP/critical_codegen.cpp
index dda532c..37a062d 100644
--- a/test/OpenMP/critical_codegen.cpp
+++ b/test/OpenMP/critical_codegen.cpp
@@ -35,4 +35,13 @@
   return a;
 }
 
+// CHECK-LABEL: parallel_critical
+void parallel_critical(float *a) {
+#pragma omp parallel
+#pragma omp critical
+  // CHECK-NOT: __kmpc_global_thread_num
+  for (unsigned i = 131071; i <= 2147483647; i += 127)
+    a[i] += i;
+}
+
 #endif
diff --git a/test/OpenMP/flush_codegen.cpp b/test/OpenMP/flush_codegen.cpp
index eb9c721..7dc58f4 100644
--- a/test/OpenMP/flush_codegen.cpp
+++ b/test/OpenMP/flush_codegen.cpp
@@ -19,16 +19,16 @@
   static int a;
 #pragma omp flush
 #pragma omp flush(a)
-  // CHECK: call void (%{{.+}}*, ...)* @__kmpc_flush(%{{.+}}* {{(@|%).+}}, i32 0)
-  // CHECK: call void (%{{.+}}*, ...)* @__kmpc_flush(%{{.+}}* {{(@|%).+}}, i32 0)
+  // CHECK: call void @__kmpc_flush(%{{.+}}* {{(@|%).+}})
+  // CHECK: call void @__kmpc_flush(%{{.+}}* {{(@|%).+}})
   return tmain(a);
   // CHECK: call {{.*}} [[TMAIN:@.+]](
   // CHECK: ret
 }
 
 // CHECK: [[TMAIN]]
-// CHECK: call void (%{{.+}}*, ...)* @__kmpc_flush(%{{.+}}* {{(@|%).+}}, i32 0)
-// CHECK: call void (%{{.+}}*, ...)* @__kmpc_flush(%{{.+}}* {{(@|%).+}}, i32 0)
+// CHECK: call void @__kmpc_flush(%{{.+}}* {{(@|%).+}})
+// CHECK: call void @__kmpc_flush(%{{.+}}* {{(@|%).+}})
 // CHECK: ret
 
 #endif
diff --git a/test/OpenMP/for_codegen.cpp b/test/OpenMP/for_codegen.cpp
new file mode 100644
index 0000000..3193d84
--- /dev/null
+++ b/test/OpenMP/for_codegen.cpp
@@ -0,0 +1,158 @@
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -fexceptions -fcxx-exceptions -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -g -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+//
+// expected-no-diagnostics
+#ifndef HEADER
+#define HEADER
+
+// CHECK: [[IDENT_T_TY:%.+]] = type { i32, i32, i32, i32, i8* }
+// CHECK-LABEL: define {{.*void}} @{{.*}}without_schedule_clause{{.*}}(float* {{.+}}, float* {{.+}}, float* {{.+}}, float* {{.+}})
+void without_schedule_clause(float *a, float *b, float *c, float *d) {
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEFAULT_LOC:[@%].+]])
+  #pragma omp for
+// CHECK: call void @__kmpc_for_static_init_4([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], i32 34, i32* [[IS_LAST:%[^,]+]], i32* [[OMP_LB:%[^,]+]], i32* [[OMP_UB:%[^,]+]], i32* [[OMP_ST:%[^,]+]], i32 1, i32 1)
+// UB = min(UB, GlobalUB)
+// CHECK-NEXT: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[UBCMP:%.+]] = icmp sgt i32 [[UB]], 4571423
+// CHECK-NEXT: br i1 [[UBCMP]], label [[UB_TRUE:%[^,]+]], label [[UB_FALSE:%[^,]+]]
+// CHECK: [[UBRESULT:%.+]] = phi i32 [ 4571423, [[UB_TRUE]] ], [ [[UBVAL:%[^,]+]], [[UB_FALSE]] ]
+// CHECK-NEXT: store i32 [[UBRESULT]], i32* [[OMP_UB]]
+// CHECK-NEXT: [[LB:%.+]] = load i32* [[OMP_LB]]
+// CHECK-NEXT: store i32 [[LB]], i32* [[OMP_IV:[^,]+]]
+// Loop header
+// CHECK: [[IV:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[CMP:%.+]] = icmp sle i32 [[IV]], [[UB]]
+// CHECK-NEXT: br i1 [[CMP]], label %[[LOOP1_BODY:[^,]+]], label %[[LOOP1_END:[^,]+]]
+  for (int i = 33; i < 32000000; i += 7) {
+// CHECK: [[LOOP1_BODY]]
+// Start of body: calculate i from IV:
+// CHECK: [[IV1_1:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[CALC_I_1:%.+]] = mul nsw i32 [[IV1_1]], 7
+// CHECK-NEXT: [[CALC_I_2:%.+]] = add nsw i32 33, [[CALC_I_1]]
+// CHECK-NEXT: store i32 [[CALC_I_2]], i32* [[LC_I:.+]]
+// ... loop body ...
+// End of body: store into a[i]:
+// CHECK: store float [[RESULT:%.+]], float* {{%.+}}
+    a[i] = b[i] * c[i] * d[i];
+// CHECK: [[IV1_2:%.+]] = load i32* [[OMP_IV]]{{.*}}
+// CHECK-NEXT: [[ADD1_2:%.+]] = add nsw i32 [[IV1_2]], 1
+// CHECK-NEXT: store i32 [[ADD1_2]], i32* [[OMP_IV]]
+// CHECK-NEXT: br label %{{.+}}
+  }
+// CHECK: [[LOOP1_END]]
+// CHECK: call void @__kmpc_for_static_fini([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK: call {{.+}} @__kmpc_cancel_barrier([[IDENT_T_TY]]* [[DEFAULT_LOC_BARRIER:[@%].+]], i32 [[GTID]])
+// CHECK: ret void
+}
+
+// CHECK-LABEL: define {{.*void}} @{{.*}}static_not_chunked{{.*}}(float* {{.+}}, float* {{.+}}, float* {{.+}}, float* {{.+}})
+void static_not_chunked(float *a, float *b, float *c, float *d) {
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEFAULT_LOC:[@%].+]])
+  #pragma omp for schedule(static)
+// CHECK: call void @__kmpc_for_static_init_4([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], i32 34, i32* [[IS_LAST:%[^,]+]], i32* [[OMP_LB:%[^,]+]], i32* [[OMP_UB:%[^,]+]], i32* [[OMP_ST:%[^,]+]], i32 1, i32 1)
+// UB = min(UB, GlobalUB)
+// CHECK-NEXT: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[UBCMP:%.+]] = icmp sgt i32 [[UB]], 4571423
+// CHECK-NEXT: br i1 [[UBCMP]], label [[UB_TRUE:%[^,]+]], label [[UB_FALSE:%[^,]+]]
+// CHECK: [[UBRESULT:%.+]] = phi i32 [ 4571423, [[UB_TRUE]] ], [ [[UBVAL:%[^,]+]], [[UB_FALSE]] ]
+// CHECK-NEXT: store i32 [[UBRESULT]], i32* [[OMP_UB]]
+// CHECK-NEXT: [[LB:%.+]] = load i32* [[OMP_LB]]
+// CHECK-NEXT: store i32 [[LB]], i32* [[OMP_IV:[^,]+]]
+// Loop header
+// CHECK: [[IV:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[CMP:%.+]] = icmp sle i32 [[IV]], [[UB]]
+// CHECK-NEXT: br i1 [[CMP]], label %[[LOOP1_BODY:[^,]+]], label %[[LOOP1_END:[^,]+]]
+  for (int i = 32000000; i > 33; i += -7) {
+// CHECK: [[LOOP1_BODY]]
+// Start of body: calculate i from IV:
+// CHECK: [[IV1_1:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[CALC_I_1:%.+]] = mul nsw i32 [[IV1_1]], 7
+// CHECK-NEXT: [[CALC_I_2:%.+]] = sub nsw i32 32000000, [[CALC_I_1]]
+// CHECK-NEXT: store i32 [[CALC_I_2]], i32* [[LC_I:.+]]
+// ... loop body ...
+// End of body: store into a[i]:
+// CHECK: store float [[RESULT:%.+]], float* {{%.+}}
+    a[i] = b[i] * c[i] * d[i];
+// CHECK: [[IV1_2:%.+]] = load i32* [[OMP_IV]]{{.*}}
+// CHECK-NEXT: [[ADD1_2:%.+]] = add nsw i32 [[IV1_2]], 1
+// CHECK-NEXT: store i32 [[ADD1_2]], i32* [[OMP_IV]]
+// CHECK-NEXT: br label %{{.+}}
+  }
+// CHECK: [[LOOP1_END]]
+// CHECK: call void @__kmpc_for_static_fini([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK: call {{.+}} @__kmpc_cancel_barrier([[IDENT_T_TY]]* [[DEFAULT_LOC_BARRIER:[@%].+]], i32 [[GTID]])
+// CHECK: ret void
+}
+
+// CHECK-LABEL: define {{.*void}} @{{.*}}static_chunked{{.*}}(float* {{.+}}, float* {{.+}}, float* {{.+}}, float* {{.+}})
+void static_chunked(float *a, float *b, float *c, float *d) {
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEFAULT_LOC:[@%].+]])
+  #pragma omp for schedule(static, 5)
+// CHECK: call void @__kmpc_for_static_init_4u([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]], i32 33, i32* [[IS_LAST:%[^,]+]], i32* [[OMP_LB:%[^,]+]], i32* [[OMP_UB:%[^,]+]], i32* [[OMP_ST:%[^,]+]], i32 1, i32 5)
+// UB = min(UB, GlobalUB)
+// CHECK: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[UBCMP:%.+]] = icmp ugt i32 [[UB]], 16908288
+// CHECK-NEXT: br i1 [[UBCMP]], label [[UB_TRUE:%[^,]+]], label [[UB_FALSE:%[^,]+]]
+// CHECK: [[UBRESULT:%.+]] = phi i32 [ 16908288, [[UB_TRUE]] ], [ [[UBVAL:%[^,]+]], [[UB_FALSE]] ]
+// CHECK-NEXT: store i32 [[UBRESULT]], i32* [[OMP_UB]]
+// CHECK-NEXT: [[LB:%.+]] = load i32* [[OMP_LB]]
+// CHECK-NEXT: store i32 [[LB]], i32* [[OMP_IV:[^,]+]]
+
+// Outer loop header
+// CHECK: [[O_IV:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[O_UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[O_CMP:%.+]] = icmp ule i32 [[O_IV]], [[O_UB]]
+// CHECK-NEXT: br i1 [[O_CMP]], label %[[O_LOOP1_BODY:[^,]+]], label %[[O_LOOP1_END:[^,]+]]
+
+// Loop header
+// CHECK: [[O_LOOP1_BODY]]
+// CHECK: [[IV:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[CMP:%.+]] = icmp ule i32 [[IV]], [[UB]]
+// CHECK-NEXT: br i1 [[CMP]], label %[[LOOP1_BODY:[^,]+]], label %[[LOOP1_END:[^,]+]]
+  for (unsigned i = 131071; i <= 2147483647; i += 127) {
+// CHECK: [[LOOP1_BODY]]
+// Start of body: calculate i from IV:
+// CHECK: [[IV1_1:%.+]] = load i32* [[OMP_IV]]
+// CHECK-NEXT: [[CALC_I_1:%.+]] = mul i32 [[IV1_1]], 127
+// CHECK-NEXT: [[CALC_I_2:%.+]] = add i32 131071, [[CALC_I_1]]
+// CHECK-NEXT: store i32 [[CALC_I_2]], i32* [[LC_I:.+]]
+// ... loop body ...
+// End of body: store into a[i]:
+// CHECK: store float [[RESULT:%.+]], float* {{%.+}}
+    a[i] = b[i] * c[i] * d[i];
+// CHECK: [[IV1_2:%.+]] = load i32* [[OMP_IV]]{{.*}}
+// CHECK-NEXT: [[ADD1_2:%.+]] = add i32 [[IV1_2]], 1
+// CHECK-NEXT: store i32 [[ADD1_2]], i32* [[OMP_IV]]
+// CHECK-NEXT: br label %{{.+}}
+  }
+// CHECK: [[LOOP1_END]]
+// Update the counters, adding stride
+// CHECK:  [[LB:%.+]] = load i32* [[OMP_LB]]
+// CHECK-NEXT: [[ST:%.+]] = load i32* [[OMP_ST]]
+// CHECK-NEXT: [[ADD_LB:%.+]] = add i32 [[LB]], [[ST]]
+// CHECK-NEXT: store i32 [[ADD_LB]], i32* [[OMP_LB]]
+// CHECK-NEXT: [[UB:%.+]] = load i32* [[OMP_UB]]
+// CHECK-NEXT: [[ST:%.+]] = load i32* [[OMP_ST]]
+// CHECK-NEXT: [[ADD_UB:%.+]] = add i32 [[UB]], [[ST]]
+// CHECK-NEXT: store i32 [[ADD_UB]], i32* [[OMP_UB]]
+
+// CHECK: [[O_LOOP1_END]]
+// CHECK: call void @__kmpc_for_static_fini([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK: call {{.+}} @__kmpc_cancel_barrier([[IDENT_T_TY]]* [[DEFAULT_LOC_BARRIER:[@%].+]], i32 [[GTID]])
+// CHECK: ret void
+}
+
+void parallel_for(float *a) {
+#pragma omp parallel
+#pragma omp for schedule(static, 5)
+  // CHECK-NOT: __kmpc_global_thread_num
+  for (unsigned i = 131071; i <= 2147483647; i += 127)
+    a[i] += i;
+}
+
+#endif // HEADER
+
diff --git a/test/OpenMP/master_codegen.cpp b/test/OpenMP/master_codegen.cpp
new file mode 100644
index 0000000..38eaa33
--- /dev/null
+++ b/test/OpenMP/master_codegen.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -emit-llvm %s -fexceptions -fcxx-exceptions -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+// CHECK:       [[IDENT_T_TY:%.+]] = type { i32, i32, i32, i32, i8* }
+
+// CHECK:       define void [[FOO:@.+]]()
+
+void foo() {}
+
+// CHECK-LABEL: @main
+int main() {
+  // CHECK:       [[A_ADDR:%.+]] = alloca i8
+  char a;
+
+// CHECK:       [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEFAULT_LOC:@.+]])
+// CHECK:       [[RES:%.+]] = call i32 @__kmpc_master([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  [[IS_MASTER:%.+]] = icmp ne i32 [[RES]], 0
+// CHECK-NEXT:  br i1 [[IS_MASTER]], label {{%?}}[[THEN:.+]], label {{%?}}[[EXIT:.+]]
+// CHECK:       [[THEN]]
+// CHECK-NEXT:  store i8 2, i8* [[A_ADDR]]
+// CHECK-NEXT:  call void @__kmpc_end_master([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  br label {{%?}}[[EXIT]]
+// CHECK:       [[EXIT]]
+#pragma omp master
+  a = 2;
+// CHECK:       [[RES:%.+]] = call i32 @__kmpc_master([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  [[IS_MASTER:%.+]] = icmp ne i32 [[RES]], 0
+// CHECK-NEXT:  br i1 [[IS_MASTER]], label {{%?}}[[THEN:.+]], label {{%?}}[[EXIT:.+]]
+// CHECK:       [[THEN]]
+// CHECK-NEXT:  call void [[FOO]]()
+// CHECK-NEXT:  call void @__kmpc_end_master([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  br label {{%?}}[[EXIT]]
+// CHECK:       [[EXIT]]
+#pragma omp master
+  foo();
+// CHECK-NOT:   call i32 @__kmpc_master
+// CHECK-NOT:   call void @__kmpc_end_master
+  return a;
+}
+
+// CHECK-LABEL: parallel_master
+void parallel_master(float *a) {
+#pragma omp parallel
+#pragma omp master
+  // CHECK-NOT: __kmpc_global_thread_num
+  for (unsigned i = 131071; i <= 2147483647; i += 127)
+    a[i] += i;
+}
+
+#endif
diff --git a/test/OpenMP/parallel_codegen.cpp b/test/OpenMP/parallel_codegen.cpp
index e50ab43..ffaca9a 100644
--- a/test/OpenMP/parallel_codegen.cpp
+++ b/test/OpenMP/parallel_codegen.cpp
@@ -70,7 +70,7 @@
 // CHECK-NEXT:  [[ARGC:%.+]] = load i32* [[ARGC_REF]]
 // CHECK-NEXT:  invoke void [[FOO:@.+foo.+]](i32{{[ ]?[a-z]*}} [[ARGC]])
 // CHECK:       ret void
-// CHECK:       call void @{{.+terminate.*}}(
+// CHECK:       call void @{{.+terminate.*|abort}}(
 // CHECK-NEXT:  unreachable
 // CHECK-NEXT:  }
 // CHECK-DEBUG-LABEL: define internal void @.omp_outlined.(i32* %.global_tid., i32* %.bound_tid., %struct.anon* %__context)
@@ -82,7 +82,7 @@
 // CHECK-DEBUG-NEXT:  [[ARGC:%.+]] = load i32* [[ARGC_REF]]
 // CHECK-DEBUG-NEXT:  invoke void [[FOO:@.+foo.+]](i32 [[ARGC]])
 // CHECK-DEBUG:       ret void
-// CHECK-DEBUG:       call void @{{.+terminate.*}}(
+// CHECK-DEBUG:       call void @{{.+terminate.*|abort}}(
 // CHECK-DEBUG-NEXT:  unreachable
 // CHECK-DEBUG-NEXT:  }
 
@@ -123,7 +123,7 @@
 // CHECK-NEXT:  [[ARGC:%.+]] = load i8*** [[ARGC_REF]]
 // CHECK-NEXT:  invoke void [[FOO1:@.+foo.+]](i8** [[ARGC]])
 // CHECK:       ret void
-// CHECK:       call void @{{.+terminate.*}}(
+// CHECK:       call void @{{.+terminate.*|abort}}(
 // CHECK-NEXT:  unreachable
 // CHECK-NEXT:  }
 // CHECK-DEBUG-LABEL: define internal void @.omp_outlined.1(i32* %.global_tid., i32* %.bound_tid., %struct.anon.0* %__context)
@@ -135,7 +135,7 @@
 // CHECK-DEBUG-NEXT:  [[ARGC:%.+]] = load i8*** [[ARGC_REF]]
 // CHECK-DEBUG-NEXT:  invoke void [[FOO1:@.+foo.+]](i8** [[ARGC]])
 // CHECK-DEBUG:       ret void
-// CHECK-DEBUG:       call void @{{.+terminate.*}}(
+// CHECK-DEBUG:       call void @{{.+terminate.*|abort}}(
 // CHECK-DEBUG-NEXT:  unreachable
 // CHECK-DEBUG-NEXT:  }
 
diff --git a/test/OpenMP/parallel_firstprivate_codegen.cpp b/test/OpenMP/parallel_firstprivate_codegen.cpp
index d15616d..811f2df 100644
--- a/test/OpenMP/parallel_firstprivate_codegen.cpp
+++ b/test/OpenMP/parallel_firstprivate_codegen.cpp
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple %itanium_abi_triple -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple %itanium_abi_triple -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -std=c++11 -DLAMBDA -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck -check-prefix=LAMBDA %s
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -fblocks -DBLOCKS -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck -check-prefix=BLOCKS %s
 // expected-no-diagnostics
 #ifndef HEADER
 #define HEADER
@@ -12,7 +14,7 @@
   ~St() {}
 };
 
-volatile int g;
+volatile int g = 1212;
 
 template <class T>
 struct S {
@@ -47,6 +49,83 @@
 }
 
 int main() {
+#ifdef LAMBDA
+  // LAMBDA: [[G:@.+]] = global i{{[0-9]+}} 1212,
+  // LAMBDA-LABEL: @main
+  // LAMBDA: call void [[OUTER_LAMBDA:@.+]](
+  [&]() {
+  // LAMBDA: define{{.*}} internal{{.*}} void [[OUTER_LAMBDA]](
+  // LAMBDA: [[G_LOCAL_REF:%.+]] = getelementptr inbounds %{{.+}}* [[AGG_CAPTURED:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+  // LAMBDA: store i{{[0-9]+}}* [[G]], i{{[0-9]+}}** [[G_LOCAL_REF]]
+  // LAMBDA: [[ARG:%.+]] = bitcast %{{.+}}* [[AGG_CAPTURED]] to i8*
+  // LAMBDA: call void {{.+}}* @__kmpc_fork_call({{.+}}, i32 1, {{.+}}* [[OMP_REGION:@.+]] to {{.+}}, i8* [[ARG]])
+#pragma omp parallel firstprivate(g)
+  {
+    // LAMBDA: define{{.*}} internal{{.*}} void [[OMP_REGION]](i32* %{{.+}}, i32* %{{.+}}, %{{.+}}* [[ARG:%.+]])
+    // LAMBDA: [[G_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}},
+    // LAMBDA: store %{{.+}}* [[ARG]], %{{.+}}** [[ARG_REF:%.+]],
+    // LAMBDA: [[ARG:%.+]] = load %{{.+}}** [[ARG_REF]]
+    // LAMBDA: [[G_REF_ADDR:%.+]] = getelementptr inbounds %{{.+}}* [[ARG]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+    // LAMBDA: [[G_REF:%.+]] = load i{{[0-9]+}}** [[G_REF_ADDR]]
+    // LAMBDA: [[G_VAL:%.+]] = load volatile i{{[0-9]+}}* [[G_REF]]
+    // LAMBDA: store volatile i{{[0-9]+}} [[G_VAL]], i{{[0-9]+}}* [[G_PRIVATE_ADDR]]
+    // LAMBDA: call i32 @__kmpc_cancel_barrier(
+    g = 1;
+    // LAMBDA: store volatile i{{[0-9]+}} 1, i{{[0-9]+}}* [[G_PRIVATE_ADDR]],
+    // LAMBDA: [[G_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+    // LAMBDA: store i{{[0-9]+}}* [[G_PRIVATE_ADDR]], i{{[0-9]+}}** [[G_PRIVATE_ADDR_REF]]
+    // LAMBDA: call void [[INNER_LAMBDA:@.+]](%{{.+}}* [[ARG]])
+    [&]() {
+      // LAMBDA: define {{.+}} void [[INNER_LAMBDA]](%{{.+}}* [[ARG_PTR:%.+]])
+      // LAMBDA: store %{{.+}}* [[ARG_PTR]], %{{.+}}** [[ARG_PTR_REF:%.+]],
+      g = 2;
+      // LAMBDA: [[ARG_PTR:%.+]] = load %{{.+}}** [[ARG_PTR_REF]]
+      // LAMBDA: [[G_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+      // LAMBDA: [[G_REF:%.+]] = load i{{[0-9]+}}** [[G_PTR_REF]]
+      // LAMBDA: store volatile i{{[0-9]+}} 2, i{{[0-9]+}}* [[G_REF]]
+    }();
+  }
+  }();
+  return 0;
+#elif defined(BLOCKS)
+  // BLOCKS: [[G:@.+]] = global i{{[0-9]+}} 1212,
+  // BLOCKS-LABEL: @main
+  // BLOCKS: call void {{%.+}}(i8*
+  ^{
+  // BLOCKS: define{{.*}} internal{{.*}} void {{.+}}(i8*
+  // BLOCKS: [[G_LOCAL_REF:%.+]] = getelementptr inbounds %{{.+}}* [[AGG_CAPTURED:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+  // BLOCKS: store i{{[0-9]+}}* [[G]], i{{[0-9]+}}** [[G_LOCAL_REF]]
+  // BLOCKS: [[ARG:%.+]] = bitcast %{{.+}}* [[AGG_CAPTURED]] to i8*
+  // BLOCKS: call void {{.+}}* @__kmpc_fork_call({{.+}}, i32 1, {{.+}}* [[OMP_REGION:@.+]] to {{.+}}, i8* [[ARG]])
+#pragma omp parallel firstprivate(g)
+  {
+    // BLOCKS: define{{.*}} internal{{.*}} void [[OMP_REGION]](i32* %{{.+}}, i32* %{{.+}}, %{{.+}}* [[ARG:%.+]])
+    // BLOCKS: [[G_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}},
+    // BLOCKS: store %{{.+}}* [[ARG]], %{{.+}}** [[ARG_REF:%.+]],
+    // BLOCKS: [[ARG:%.+]] = load %{{.+}}** [[ARG_REF]]
+    // BLOCKS: [[G_REF_ADDR:%.+]] = getelementptr inbounds %{{.+}}* [[ARG]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+    // BLOCKS: [[G_REF:%.+]] = load i{{[0-9]+}}** [[G_REF_ADDR]]
+    // BLOCKS: [[G_VAL:%.+]] = load volatile i{{[0-9]+}}* [[G_REF]]
+    // BLOCKS: store volatile i{{[0-9]+}} [[G_VAL]], i{{[0-9]+}}* [[G_PRIVATE_ADDR]]
+    // BLOCKS: call i32 @__kmpc_cancel_barrier(
+    g = 1;
+    // BLOCKS: store volatile i{{[0-9]+}} 1, i{{[0-9]+}}* [[G_PRIVATE_ADDR]],
+    // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+    // BLOCKS: i{{[0-9]+}}* [[G_PRIVATE_ADDR]]
+    // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+    // BLOCKS: call void {{%.+}}(i8*
+    ^{
+      // BLOCKS: define {{.+}} void {{@.+}}(i8*
+      g = 2;
+      // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+      // BLOCKS: store volatile i{{[0-9]+}} 2, i{{[0-9]+}}*
+      // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+      // BLOCKS: ret
+    }();
+  }
+  }();
+  return 0;
+#else
   S<float> test;
   int t_var = 0;
   int vec[] = {1, 2};
@@ -58,6 +137,7 @@
     s_arr[0] = var;
   }
   return tmain<int>();
+#endif
 }
 
 // CHECK: define {{.*}}i{{[0-9]+}} @main()
@@ -112,7 +192,7 @@
 // CHECK: call {{.*}} [[ST_TY_DESTR]]([[ST_TY]]* [[ST_TY_TEMP]])
 // CHECK: [[GTID_REF:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_ADDR]]
 // CHECK: [[GTID:%.+]] = load i{{[0-9]+}}* [[GTID_REF]]
-// CHECK: call void @__kmpc_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
+// CHECK: call i32 @__kmpc_cancel_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
 // CHECK-DAG: call {{.*}} [[S_FLOAT_TY_DESTR]]([[S_FLOAT_TY]]* [[VAR_PRIV]])
 // CHECK-DAG: call {{.*}} [[S_FLOAT_TY_DESTR]]([[S_FLOAT_TY]]*
 // CHECK: ret void
@@ -167,7 +247,7 @@
 // CHECK: call {{.*}} [[ST_TY_DESTR]]([[ST_TY]]* [[ST_TY_TEMP]])
 // CHECK: [[GTID_REF:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_ADDR]]
 // CHECK: [[GTID:%.+]] = load i{{[0-9]+}}* [[GTID_REF]]
-// CHECK: call void @__kmpc_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
+// CHECK: call i32 @__kmpc_cancel_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
 // CHECK-DAG: call {{.*}} [[S_INT_TY_DESTR]]([[S_INT_TY]]* [[VAR_PRIV]])
 // CHECK-DAG: call {{.*}} [[S_INT_TY_DESTR]]([[S_INT_TY]]*
 // CHECK: ret void
diff --git a/test/OpenMP/parallel_for_lastprivate_messages.cpp b/test/OpenMP/parallel_for_lastprivate_messages.cpp
index bd1dd4b..915cbf7 100644
--- a/test/OpenMP/parallel_for_lastprivate_messages.cpp
+++ b/test/OpenMP/parallel_for_lastprivate_messages.cpp
@@ -15,7 +15,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note {{static data member is predetermined as shared}}
@@ -181,7 +181,7 @@
 #pragma omp parallel for lastprivate(xa) // OK
   for (i = 0; i < argc; ++i)
     foo();
-#pragma omp parallel for lastprivate(S2::S2s) // expected-error {{shared variable cannot be lastprivate}}
+#pragma omp parallel for lastprivate(S2::S2s)
   for (i = 0; i < argc; ++i)
     foo();
 #pragma omp parallel for lastprivate(S2::S2sc) // expected-error {{shared variable cannot be lastprivate}}
diff --git a/test/OpenMP/parallel_for_reduction_messages.cpp b/test/OpenMP/parallel_for_reduction_messages.cpp
index 8e482ef..676b86f 100644
--- a/test/OpenMP/parallel_for_reduction_messages.cpp
+++ b/test/OpenMP/parallel_for_reduction_messages.cpp
@@ -16,7 +16,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note 2 {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note 2 {{'S2sc' defined here}}
@@ -135,7 +135,7 @@
 #pragma omp parallel for reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   for (int i = 0; i < 10; ++i)
     foo();
-#pragma omp parallel for reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel for reduction(&& : S2::S2s)
   for (int i = 0; i < 10; ++i)
     foo();
 #pragma omp parallel for reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
@@ -249,7 +249,7 @@
 #pragma omp parallel for reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   for (int i = 0; i < 10; ++i)
     foo();
-#pragma omp parallel for reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel for reduction(&& : S2::S2s)
   for (int i = 0; i < 10; ++i)
     foo();
 #pragma omp parallel for reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
diff --git a/test/OpenMP/parallel_for_simd_lastprivate_messages.cpp b/test/OpenMP/parallel_for_simd_lastprivate_messages.cpp
index b620c7f..3d53259 100644
--- a/test/OpenMP/parallel_for_simd_lastprivate_messages.cpp
+++ b/test/OpenMP/parallel_for_simd_lastprivate_messages.cpp
@@ -15,7 +15,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note {{static data member is predetermined as shared}}
@@ -181,7 +181,7 @@
 #pragma omp parallel for simd lastprivate(xa) // OK
   for (i = 0; i < argc; ++i)
     foo();
-#pragma omp parallel for simd lastprivate(S2::S2s) // expected-error {{shared variable cannot be lastprivate}}
+#pragma omp parallel for simd lastprivate(S2::S2s)
   for (i = 0; i < argc; ++i)
     foo();
 #pragma omp parallel for simd lastprivate(S2::S2sc) // expected-error {{shared variable cannot be lastprivate}}
diff --git a/test/OpenMP/parallel_for_simd_reduction_messages.cpp b/test/OpenMP/parallel_for_simd_reduction_messages.cpp
index 61690dd..2395cbd 100644
--- a/test/OpenMP/parallel_for_simd_reduction_messages.cpp
+++ b/test/OpenMP/parallel_for_simd_reduction_messages.cpp
@@ -16,7 +16,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note 2 {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note 2 {{'S2sc' defined here}}
@@ -135,7 +135,7 @@
 #pragma omp parallel for simd reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   for (int i = 0; i < 10; ++i)
     foo();
-#pragma omp parallel for simd reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel for simd reduction(&& : S2::S2s)
   for (int i = 0; i < 10; ++i)
     foo();
 #pragma omp parallel for simd reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
@@ -249,7 +249,7 @@
 #pragma omp parallel for simd reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   for (int i = 0; i < 10; ++i)
     foo();
-#pragma omp parallel for simd reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel for simd reduction(&& : S2::S2s)
   for (int i = 0; i < 10; ++i)
     foo();
 #pragma omp parallel for simd reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
diff --git a/test/OpenMP/parallel_num_threads_codegen.cpp b/test/OpenMP/parallel_num_threads_codegen.cpp
index 4ccf789..c095e43 100644
--- a/test/OpenMP/parallel_num_threads_codegen.cpp
+++ b/test/OpenMP/parallel_num_threads_codegen.cpp
@@ -44,7 +44,7 @@
 // CHECK-DAG:   [[S_ADDR:%.+]] = alloca [[S_TY]]
 // CHECK-DAG:   [[A_ADDR:%.+]] = alloca i8
 // CHECK-DAG:   [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEF_LOC_2]])
-// CHECK-DAG:   call {{.*}} [[S_TY_CONSTR:@.+]]([[S_TY]]* [[S_ADDR]], [[INTPTR_T_TY]] 0)
+// CHECK-DAG:   call {{.*}} [[S_TY_CONSTR:@.+]]([[S_TY]]* [[S_ADDR]], [[INTPTR_T_TY]] [[INTPTR_T_TY_ATTR:(signext )?]]0)
 // CHECK:       [[S_CHAR_OP:%.+]] = invoke{{.*}} i8 [[S_TY_CHAR_OP:@.+]]([[S_TY]]* [[S_ADDR]])
 // CHECK:       store i8 [[S_CHAR_OP]], i8* [[A_ADDR]]
 // CHECK:       call void @__kmpc_push_num_threads([[IDENT_T_TY]]* [[DEF_LOC_2]], i32 [[GTID]], i32 2)
@@ -72,7 +72,7 @@
 // CHECK:       [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEF_LOC_2]])
 // CHECK:       call void @__kmpc_push_num_threads([[IDENT_T_TY]]* [[DEF_LOC_2]], i32 [[GTID]], i32 1)
 // CHECK:       call void {{.*}}* @__kmpc_fork_call(
-// CHECK:       call {{.*}} [[S_TY_CONSTR]]([[S_TY]]* [[S_TEMP:%.+]], [[INTPTR_T_TY]] 23)
+// CHECK:       call {{.*}} [[S_TY_CONSTR]]([[S_TY]]* [[S_TEMP:%.+]], [[INTPTR_T_TY]] [[INTPTR_T_TY_ATTR]]23)
 // CHECK:       [[S_CHAR_OP:%.+]] = invoke{{.*}} i8 [[S_TY_CHAR_OP]]([[S_TY]]* [[S_TEMP]])
 // CHECK:       [[RES:%.+]] = sext {{.*}}i8 [[S_CHAR_OP]] to i32
 // CHECK:       call void @__kmpc_push_num_threads([[IDENT_T_TY]]* [[DEF_LOC_2]], i32 [[GTID]], i32 [[RES]])
diff --git a/test/OpenMP/parallel_private_codegen.cpp b/test/OpenMP/parallel_private_codegen.cpp
index 2db0674..6911068 100644
--- a/test/OpenMP/parallel_private_codegen.cpp
+++ b/test/OpenMP/parallel_private_codegen.cpp
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -std=c++11 -DLAMBDA -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck -check-prefix=LAMBDA %s
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -fblocks -DBLOCKS -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck -check-prefix=BLOCKS %s
 // expected-no-diagnostics
 #ifndef HEADER
 #define HEADER
@@ -14,6 +16,8 @@
   ~S() {}
 };
 
+volatile int g = 1212;
+
 // CHECK: [[S_FLOAT_TY:%.+]] = type { float }
 // CHECK: [[CAP_MAIN_TY:%.+]] = type { [2 x i{{[0-9]+}}]*, i{{[0-9]+}}*, [2 x [[S_FLOAT_TY]]]*, [[S_FLOAT_TY]]* }
 // CHECK: [[S_INT_TY:%.+]] = type { i{{[0-9]+}} }
@@ -22,7 +26,7 @@
 template <typename T>
 T tmain() {
   S<T> test;
-  T t_var;
+  T t_var = T();
   T vec[] = {1, 2};
   S<T> s_arr[] = {1, 2};
   S<T> var(3);
@@ -35,8 +39,75 @@
 }
 
 int main() {
+#ifdef LAMBDA
+  // LAMBDA: [[G:@.+]] = global i{{[0-9]+}} 1212,
+  // LAMBDA-LABEL: @main
+  // LAMBDA: call void [[OUTER_LAMBDA:@.+]](
+  [&]() {
+  // LAMBDA: define{{.*}} internal{{.*}} void [[OUTER_LAMBDA]](
+  // LAMBDA: [[G_LOCAL_REF:%.+]] = getelementptr inbounds %{{.+}}* [[AGG_CAPTURED:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+  // LAMBDA: store i{{[0-9]+}}* [[G]], i{{[0-9]+}}** [[G_LOCAL_REF]]
+  // LAMBDA: [[ARG:%.+]] = bitcast %{{.+}}* [[AGG_CAPTURED]] to i8*
+  // LAMBDA: call void {{.+}}* @__kmpc_fork_call({{.+}}, i32 1, {{.+}}* [[OMP_REGION:@.+]] to {{.+}}, i8* [[ARG]])
+#pragma omp parallel private(g)
+  {
+    // LAMBDA: define{{.*}} internal{{.*}} void [[OMP_REGION]](i32* %{{.+}}, i32* %{{.+}}, %{{.+}}* [[ARG:%.+]])
+    // LAMBDA: [[G_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}},
+    // LAMBDA: store %{{.+}}* [[ARG]], %{{.+}}** [[ARG_REF:%.+]],
+    // LAMBDA: call i32 @__kmpc_cancel_barrier(
+    g = 1;
+    // LAMBDA: store volatile i{{[0-9]+}} 1, i{{[0-9]+}}* [[G_PRIVATE_ADDR]],
+    // LAMBDA: [[G_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+    // LAMBDA: store i{{[0-9]+}}* [[G_PRIVATE_ADDR]], i{{[0-9]+}}** [[G_PRIVATE_ADDR_REF]]
+    // LAMBDA: call void [[INNER_LAMBDA:@.+]](%{{.+}}* [[ARG]])
+    [&]() {
+      // LAMBDA: define {{.+}} void [[INNER_LAMBDA]](%{{.+}}* [[ARG_PTR:%.+]])
+      // LAMBDA: store %{{.+}}* [[ARG_PTR]], %{{.+}}** [[ARG_PTR_REF:%.+]],
+      g = 2;
+      // LAMBDA: [[ARG_PTR:%.+]] = load %{{.+}}** [[ARG_PTR_REF]]
+      // LAMBDA: [[G_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+      // LAMBDA: [[G_REF:%.+]] = load i{{[0-9]+}}** [[G_PTR_REF]]
+      // LAMBDA: store volatile i{{[0-9]+}} 2, i{{[0-9]+}}* [[G_REF]]
+    }();
+  }
+  }();
+  return 0;
+#elif defined(BLOCKS)
+  // BLOCKS: [[G:@.+]] = global i{{[0-9]+}} 1212,
+  // BLOCKS-LABEL: @main
+  // BLOCKS: call void {{%.+}}(i8*
+  ^{
+  // BLOCKS: define{{.*}} internal{{.*}} void {{.+}}(i8*
+  // BLOCKS: [[G_LOCAL_REF:%.+]] = getelementptr inbounds %{{.+}}* [[AGG_CAPTURED:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+  // BLOCKS: store i{{[0-9]+}}* [[G]], i{{[0-9]+}}** [[G_LOCAL_REF]]
+  // BLOCKS: [[ARG:%.+]] = bitcast %{{.+}}* [[AGG_CAPTURED]] to i8*
+  // BLOCKS: call void {{.+}}* @__kmpc_fork_call({{.+}}, i32 1, {{.+}}* [[OMP_REGION:@.+]] to {{.+}}, i8* [[ARG]])
+#pragma omp parallel private(g)
+  {
+    // BLOCKS: define{{.*}} internal{{.*}} void [[OMP_REGION]](i32* %{{.+}}, i32* %{{.+}}, %{{.+}}* [[ARG:%.+]])
+    // BLOCKS: [[G_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}},
+    // BLOCKS: store %{{.+}}* [[ARG]], %{{.+}}** [[ARG_REF:%.+]],
+    // BLOCKS: call i32 @__kmpc_cancel_barrier(
+    g = 1;
+    // BLOCKS: store volatile i{{[0-9]+}} 1, i{{[0-9]+}}* [[G_PRIVATE_ADDR]],
+    // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+    // BLOCKS: i{{[0-9]+}}* [[G_PRIVATE_ADDR]]
+    // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+    // BLOCKS: call void {{%.+}}(i8*
+    ^{
+      // BLOCKS: define {{.+}} void {{@.+}}(i8*
+      g = 2;
+      // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+      // BLOCKS: store volatile i{{[0-9]+}} 2, i{{[0-9]+}}*
+      // BLOCKS-NOT: [[G]]{{[[^:word:]]}}
+      // BLOCKS: ret
+    }();
+  }
+  }();
+  return 0;
+#else
   S<float> test;
-  int t_var;
+  int t_var = 0;
   int vec[] = {1, 2};
   S<float> s_arr[] = {1, 2};
   S<float> var(3);
@@ -46,6 +117,7 @@
     s_arr[0] = var;
   }
   return tmain<int>();
+#endif
 }
 
 // CHECK: define i{{[0-9]+}} @main()
@@ -73,7 +145,7 @@
 // CHECK: call {{.*}} [[S_FLOAT_TY_DEF_CONSTR]]([[S_FLOAT_TY]]* [[VAR_PRIV]])
 // CHECK: [[GTID_REF:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_REF]]
 // CHECK: [[GTID:%.+]] = load i{{[0-9]+}}* [[GTID_REF]]
-// CHECK: call void @__kmpc_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
+// CHECK: call i32 @__kmpc_cancel_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
 // CHECK-DAG: call void [[S_FLOAT_TY_DESTR]]([[S_FLOAT_TY]]* [[VAR_PRIV]])
 // CHECK-DAG: call void [[S_FLOAT_TY_DESTR]]([[S_FLOAT_TY]]*
 // CHECK: ret void
@@ -101,7 +173,7 @@
 // CHECK: call {{.*}} [[S_INT_TY_DEF_CONSTR]]([[S_INT_TY]]* [[VAR_PRIV]])
 // CHECK: [[GTID_REF:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_REF]]
 // CHECK: [[GTID:%.+]] = load i{{[0-9]+}}* [[GTID_REF]]
-// CHECK: call void @__kmpc_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
+// CHECK: call i32 @__kmpc_cancel_barrier(%{{.+}}* [[IMPLICIT_BARRIER_LOC]], i{{[0-9]+}} [[GTID]])
 // CHECK-DAG: call void [[S_INT_TY_DESTR]]([[S_INT_TY]]* [[VAR_PRIV]])
 // CHECK-DAG: call void [[S_INT_TY_DESTR]]([[S_INT_TY]]*
 // CHECK: ret void
diff --git a/test/OpenMP/parallel_private_messages.cpp b/test/OpenMP/parallel_private_messages.cpp
index 14c5cbd..74949ba 100644
--- a/test/OpenMP/parallel_private_messages.cpp
+++ b/test/OpenMP/parallel_private_messages.cpp
@@ -13,7 +13,7 @@
   mutable int a;
 public:
   S2():a(0) { }
-  static float S2s; // expected-note {{static data member is predetermined as shared}}
+  static float S2s;
 };
 const S2 b;
 const S2 ba[5];
@@ -61,7 +61,7 @@
   #pragma omp parallel private(ba)
   #pragma omp parallel private(ca) // expected-error {{shared variable cannot be private}}
   #pragma omp parallel private(da) // expected-error {{shared variable cannot be private}}
-  #pragma omp parallel private(S2::S2s) // expected-error {{shared variable cannot be private}}
+  #pragma omp parallel private(S2::S2s)
   #pragma omp parallel private(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}
   #pragma omp parallel private(threadvar) // expected-error {{threadprivate or thread local variable cannot be private}}
   #pragma omp parallel shared(i), private(i) // expected-error {{shared variable cannot be private}} expected-note {{defined as shared}}
diff --git a/test/OpenMP/parallel_reduction_messages.cpp b/test/OpenMP/parallel_reduction_messages.cpp
index 43ebc01..46bc7a5 100644
--- a/test/OpenMP/parallel_reduction_messages.cpp
+++ b/test/OpenMP/parallel_reduction_messages.cpp
@@ -16,7 +16,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note 2 {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note 2 {{'S2sc' defined here}}
@@ -115,7 +115,7 @@
   foo();
 #pragma omp parallel reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   foo();
-#pragma omp parallel reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel reduction(&& : S2::S2s)
   foo();
 #pragma omp parallel reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
   foo();
@@ -202,7 +202,7 @@
   foo();
 #pragma omp parallel reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   foo();
-#pragma omp parallel reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel reduction(&& : S2::S2s)
   foo();
 #pragma omp parallel reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
   foo();
diff --git a/test/OpenMP/parallel_sections_lastprivate_messages.cpp b/test/OpenMP/parallel_sections_lastprivate_messages.cpp
index c71c115..6d790e4 100644
--- a/test/OpenMP/parallel_sections_lastprivate_messages.cpp
+++ b/test/OpenMP/parallel_sections_lastprivate_messages.cpp
@@ -15,7 +15,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note {{static data member is predetermined as shared}}
@@ -211,7 +211,7 @@
   {
     foo();
   }
-#pragma omp parallel sections lastprivate(S2::S2s) // expected-error {{shared variable cannot be lastprivate}}
+#pragma omp parallel sections lastprivate(S2::S2s)
   {
     foo();
   }
diff --git a/test/OpenMP/parallel_sections_reduction_messages.cpp b/test/OpenMP/parallel_sections_reduction_messages.cpp
index 8b02f23..68f494f 100644
--- a/test/OpenMP/parallel_sections_reduction_messages.cpp
+++ b/test/OpenMP/parallel_sections_reduction_messages.cpp
@@ -16,7 +16,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note 2 {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note 2 {{'S2sc' defined here}}
@@ -155,7 +155,7 @@
   {
     foo();
   }
-#pragma omp parallel sections reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel sections reduction(&& : S2::S2s)
   {
     foo();
   }
@@ -300,7 +300,7 @@
   {
     foo();
   }
-#pragma omp parallel sections reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp parallel sections reduction(&& : S2::S2s)
   {
     foo();
   }
diff --git a/test/OpenMP/simd_codegen.cpp b/test/OpenMP/simd_codegen.cpp
index b8073c2..fac1427 100644
--- a/test/OpenMP/simd_codegen.cpp
+++ b/test/OpenMP/simd_codegen.cpp
@@ -403,5 +403,13 @@
 // CHECK: ret void
 }
 
+void parallel_simd(float *a) {
+#pragma omp parallel
+#pragma omp simd
+  // CHECK-NOT: __kmpc_global_thread_num
+  for (unsigned i = 131071; i <= 2147483647; i += 127)
+    a[i] += i;
+}
+
 #endif // HEADER
 
diff --git a/test/OpenMP/simd_metadata.c b/test/OpenMP/simd_metadata.c
index 9879d84..4552669 100644
--- a/test/OpenMP/simd_metadata.c
+++ b/test/OpenMP/simd_metadata.c
@@ -52,13 +52,13 @@
 }
 
 // Metadata for h1:
-// CHECK: [[LOOP_H1_HEADER:![0-9]+]] = metadata !{metadata [[LOOP_H1_HEADER]], metadata [[LOOP_WIDTH_16:![0-9]+]], metadata [[LOOP_VEC_ENABLE:![0-9]+]]}
-// CHECK: [[LOOP_WIDTH_16]] = metadata !{metadata !"llvm.loop.vectorize.width", i32 16}
-// CHECK: [[LOOP_VEC_ENABLE]] = metadata !{metadata !"llvm.loop.vectorize.enable", i1 true}
+// CHECK: [[LOOP_H1_HEADER:![0-9]+]] = distinct !{[[LOOP_H1_HEADER]], [[LOOP_WIDTH_16:![0-9]+]], [[LOOP_VEC_ENABLE:![0-9]+]]}
+// CHECK: [[LOOP_WIDTH_16]] = !{!"llvm.loop.vectorize.width", i32 16}
+// CHECK: [[LOOP_VEC_ENABLE]] = !{!"llvm.loop.vectorize.enable", i1 true}
 //
 // Metadata for h2:
-// CHECK: [[LOOP_H2_HEADER]] = metadata !{metadata [[LOOP_H2_HEADER]], metadata [[LOOP_VEC_ENABLE]]}
+// CHECK: [[LOOP_H2_HEADER]] = distinct !{[[LOOP_H2_HEADER]], [[LOOP_VEC_ENABLE]]}
 //
 // Metadata for h3:
-// CHECK: [[LOOP_H3_HEADER:![0-9]+]] = metadata !{metadata [[LOOP_H3_HEADER]], metadata [[LOOP_VEC_ENABLE]]}
+// CHECK: [[LOOP_H3_HEADER:![0-9]+]] = distinct !{[[LOOP_H3_HEADER]], [[LOOP_VEC_ENABLE]]}
 //
diff --git a/test/OpenMP/single_ast_print.cpp b/test/OpenMP/single_ast_print.cpp
index 65a007e..b9eba9d 100644
--- a/test/OpenMP/single_ast_print.cpp
+++ b/test/OpenMP/single_ast_print.cpp
@@ -14,10 +14,16 @@
   static T a;
 // CHECK: static T a;
 #pragma omp parallel private(g)
-#pragma omp single private(argc, b), firstprivate(c, d), nowait copyprivate(g)
+#pragma omp single private(argc, b), firstprivate(c, d), nowait
   foo();
   // CHECK-NEXT: #pragma omp parallel private(g)
-  // CHECK-NEXT: #pragma omp single private(argc,b) firstprivate(c,d) nowait copyprivate(g)
+  // CHECK-NEXT: #pragma omp single private(argc,b) firstprivate(c,d) nowait
+  // CHECK-NEXT: foo();
+#pragma omp parallel private(g)
+#pragma omp single private(argc, b), firstprivate(c, d), copyprivate(g)
+  foo();
+  // CHECK-NEXT: #pragma omp parallel private(g)
+  // CHECK-NEXT: #pragma omp single private(argc,b) firstprivate(c,d) copyprivate(g)
   // CHECK-NEXT: foo();
   return T();
 }
@@ -27,10 +33,16 @@
   static int a;
 // CHECK: static int a;
 #pragma omp parallel private(g)
-#pragma omp single private(argc, b), firstprivate(argv, c), nowait copyprivate(g)
+#pragma omp single private(argc, b), firstprivate(argv, c), nowait
   foo();
   // CHECK-NEXT: #pragma omp parallel private(g)
-  // CHECK-NEXT: #pragma omp single private(argc,b) firstprivate(argv,c) nowait copyprivate(g)
+  // CHECK-NEXT: #pragma omp single private(argc,b) firstprivate(argv,c) nowait
+  // CHECK-NEXT: foo();
+#pragma omp parallel private(g)
+#pragma omp single private(argc, b), firstprivate(c, d), copyprivate(g)
+  foo();
+  // CHECK-NEXT: #pragma omp parallel private(g)
+  // CHECK-NEXT: #pragma omp single private(argc,b) firstprivate(c,d) copyprivate(g)
   // CHECK-NEXT: foo();
   return (tmain<int, 5>(argc) + tmain<char, 1>(argv[0][0]));
 }
diff --git a/test/OpenMP/single_codegen.cpp b/test/OpenMP/single_codegen.cpp
new file mode 100644
index 0000000..b98da37
--- /dev/null
+++ b/test/OpenMP/single_codegen.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -emit-llvm %s -fexceptions -fcxx-exceptions -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+// CHECK:       [[IDENT_T_TY:%.+]] = type { i32, i32, i32, i32, i8* }
+
+// CHECK:       define void [[FOO:@.+]]()
+
+void foo() {}
+
+// CHECK-LABEL: @main
+int main() {
+  // CHECK:       [[A_ADDR:%.+]] = alloca i8
+  char a;
+
+// CHECK:       [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T_TY]]* [[DEFAULT_LOC:@.+]])
+// CHECK:       [[RES:%.+]] = call i32 @__kmpc_single([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  [[IS_SINGLE:%.+]] = icmp ne i32 [[RES]], 0
+// CHECK-NEXT:  br i1 [[IS_SINGLE]], label {{%?}}[[THEN:.+]], label {{%?}}[[EXIT:.+]]
+// CHECK:       [[THEN]]
+// CHECK-NEXT:  store i8 2, i8* [[A_ADDR]]
+// CHECK-NEXT:  call void @__kmpc_end_single([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  br label {{%?}}[[EXIT]]
+// CHECK:       [[EXIT]]
+#pragma omp single
+  a = 2;
+// CHECK:       [[RES:%.+]] = call i32 @__kmpc_single([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  [[IS_SINGLE:%.+]] = icmp ne i32 [[RES]], 0
+// CHECK-NEXT:  br i1 [[IS_SINGLE]], label {{%?}}[[THEN:.+]], label {{%?}}[[EXIT:.+]]
+// CHECK:       [[THEN]]
+// CHECK-NEXT:  call void [[FOO]]()
+// CHECK-NEXT:  call void @__kmpc_end_single([[IDENT_T_TY]]* [[DEFAULT_LOC]], i32 [[GTID]])
+// CHECK-NEXT:  br label {{%?}}[[EXIT]]
+// CHECK:       [[EXIT]]
+#pragma omp single
+  foo();
+// CHECK-NOT:   call i32 @__kmpc_single
+// CHECK-NOT:   call void @__kmpc_end_single
+  return a;
+}
+
+// CHECK-LABEL: parallel_single
+void parallel_single(float *a) {
+#pragma omp parallel
+#pragma omp single
+  // CHECK-NOT: __kmpc_global_thread_num
+  for (unsigned i = 131071; i <= 2147483647; i += 127)
+    a[i] += i;
+}
+
+#endif
diff --git a/test/OpenMP/single_copyprivate_messages.cpp b/test/OpenMP/single_copyprivate_messages.cpp
index 7bb145c..33d2428 100644
--- a/test/OpenMP/single_copyprivate_messages.cpp
+++ b/test/OpenMP/single_copyprivate_messages.cpp
@@ -44,6 +44,7 @@
 template <class T, class C>
 T tmain(T argc, C **argv) {
   T i;
+  static T TA;
 #pragma omp parallel
 #pragma omp single copyprivate // expected-error {{expected '(' after 'copyprivate'}}
 #pragma omp parallel
@@ -95,12 +96,18 @@
 #pragma omp parallel
 #pragma omp single firstprivate(i) copyprivate(i) // expected-error {{firstprivate variable cannot be copyprivate}} expected-note {{defined as firstprivate}}
   foo();
+#pragma omp parallel private(TA)
+  {
+#pragma omp single copyprivate(TA)
+    TA = 99;
+  }
 
   return T();
 }
 
 int main(int argc, char **argv) {
   int i;
+  static int intA;
 #pragma omp parallel
 #pragma omp single copyprivate // expected-error {{expected '(' after 'copyprivate'}}
 #pragma omp parallel
@@ -152,6 +159,13 @@
 #pragma omp parallel
 #pragma omp single firstprivate(i) copyprivate(i) // expected-error {{firstprivate variable cannot be copyprivate}} expected-note {{defined as firstprivate}}
   foo();
+#pragma omp single copyprivate(i) nowait // expected-error {{the 'copyprivate' clause must not be used with the 'nowait' clause}} expected-note {{'nowait' clause is here}}
+  foo();
+#pragma omp parallel private(intA)
+  {
+#pragma omp single copyprivate(intA)
+    intA = 99;
+  }
 
   return tmain(argc, argv); // expected-note {{in instantiation of function template specialization 'tmain<int, char>' requested here}}
 }
diff --git a/test/OpenMP/task_private_messages.cpp b/test/OpenMP/task_private_messages.cpp
index 9a3bb75..0352694 100644
--- a/test/OpenMP/task_private_messages.cpp
+++ b/test/OpenMP/task_private_messages.cpp
@@ -14,7 +14,7 @@
 
 public:
   S2() : a(0) {}
-  static float S2s; // expected-note {{static data member is predetermined as shared}}
+  static float S2s;
 };
 const S2 b;
 const S2 ba[5];
@@ -65,7 +65,7 @@
 #pragma omp task private(ba)
 #pragma omp task private(ca)           // expected-error {{shared variable cannot be private}}
 #pragma omp task private(da)           // expected-error {{shared variable cannot be private}}
-#pragma omp task private(S2::S2s)      // expected-error {{shared variable cannot be private}}
+#pragma omp task private(S2::S2s)
 #pragma omp task private(e, g)         // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}
 #pragma omp task private(threadvar)    // expected-error {{threadprivate or thread local variable cannot be private}}
 #pragma omp task shared(i), private(i) // expected-error {{shared variable cannot be private}} expected-note {{defined as shared}}
diff --git a/test/OpenMP/taskyield_codegen.cpp b/test/OpenMP/taskyield_codegen.cpp
new file mode 100644
index 0000000..7c02b52
--- /dev/null
+++ b/test/OpenMP/taskyield_codegen.cpp
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple x86_64-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+// CHECK: [[IDENT_T:%.+]] = type { i32, i32, i32, i32, i8* }
+
+void foo() {}
+
+template <class T>
+T tmain(T argc) {
+  static T a;
+#pragma omp taskyield
+  return a + argc;
+}
+
+// CHECK-LABEL: @main
+int main(int argc, char **argv) {
+  static int a;
+#pragma omp taskyield
+  // CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* @{{.+}})
+  // CHECK: call i32 @__kmpc_omp_taskyield([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i32 0)
+  // CHECK: call {{.+}} [[TMAIN_INT:@.+]](i{{[0-9][0-9]}}
+  // CHECK: call {{.+}} [[TMAIN_CHAR:@.+]](i{{[0-9]}}
+  return tmain(argc) + tmain(argv[0][0]) + a;
+}
+
+// CHECK: define {{.+}} [[TMAIN_INT]](
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* @{{.+}})
+// CHECK: call i32 @__kmpc_omp_taskyield([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i32 0)
+
+// CHECK: define {{.+}} [[TMAIN_CHAR]](
+// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* @{{.+}})
+// CHECK: call i32 @__kmpc_omp_taskyield([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i32 0)
+
+#endif
diff --git a/test/OpenMP/teams_private_messages.cpp b/test/OpenMP/teams_private_messages.cpp
index 16ecb74..65caaed 100644
--- a/test/OpenMP/teams_private_messages.cpp
+++ b/test/OpenMP/teams_private_messages.cpp
@@ -13,7 +13,7 @@
   mutable int a;
 public:
   S2():a(0) { }
-  static float S2s; // expected-note {{static data member is predetermined as shared}}
+  static float S2s;
 };
 const S2 b;
 const S2 ba[5];
@@ -88,7 +88,7 @@
   #pragma omp teams private(da) // expected-error {{shared variable cannot be private}}
   foo();
   #pragma omp target
-  #pragma omp teams private(S2::S2s) // expected-error {{shared variable cannot be private}}
+  #pragma omp teams private(S2::S2s)
   foo();
   #pragma omp target
   #pragma omp teams private(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}
diff --git a/test/OpenMP/teams_reduction_messages.cpp b/test/OpenMP/teams_reduction_messages.cpp
index afedfc3..18b7cd4 100644
--- a/test/OpenMP/teams_reduction_messages.cpp
+++ b/test/OpenMP/teams_reduction_messages.cpp
@@ -16,7 +16,7 @@
 public:
   S2() : a(0) {}
   S2(S2 &s2) : a(s2.a) {}
-  static float S2s; // expected-note 2 {{static data member is predetermined as shared}}
+  static float S2s;
   static const float S2sc;
 };
 const float S2::S2sc = 0; // expected-note 2 {{'S2sc' defined here}}
@@ -136,7 +136,7 @@
 #pragma omp teams reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   foo();
 #pragma omp target
-#pragma omp teams reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp teams reduction(&& : S2::S2s)
   foo();
 #pragma omp target
 #pragma omp teams reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
@@ -256,7 +256,7 @@
 #pragma omp teams reduction(^ : fl) // expected-error {{variable of type 'float' is not valid for specified reduction operation}}
   foo();
 #pragma omp target
-#pragma omp teams reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
+#pragma omp teams reduction(&& : S2::S2s)
   foo();
 #pragma omp target
 #pragma omp teams reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be reduction}}
diff --git a/test/OpenMP/threadprivate_messages.cpp b/test/OpenMP/threadprivate_messages.cpp
index 491f30a..27b36fb 100644
--- a/test/OpenMP/threadprivate_messages.cpp
+++ b/test/OpenMP/threadprivate_messages.cpp
@@ -96,6 +96,9 @@
 static __thread int t; // expected-note {{'t' defined here}}
 #pragma omp threadprivate (t) // expected-error {{variable 't' cannot be threadprivate because it is thread-local}}
 
+register int reg0 __asm__("0"); // expected-note {{'reg0' defined here}}
+#pragma omp threadprivate (reg0) // expected-error {{variable 'reg0' cannot be threadprivate because it is a global named register variable}}
+
 int o; // expected-note {{candidate found by name lookup is 'o'}}
 #pragma omp threadprivate (o)
 namespace {
diff --git a/test/PCH/Inputs/modules/Foo.h b/test/PCH/Inputs/modules/Foo.h
new file mode 100644
index 0000000..d661dbc
--- /dev/null
+++ b/test/PCH/Inputs/modules/Foo.h
@@ -0,0 +1 @@
+void make_foo(void);
diff --git a/test/PCH/Inputs/modules/module.modulemap b/test/PCH/Inputs/modules/module.modulemap
new file mode 100644
index 0000000..5590b43
--- /dev/null
+++ b/test/PCH/Inputs/modules/module.modulemap
@@ -0,0 +1,3 @@
+module Foo {
+  header "Foo.h"
+}
diff --git a/test/PCH/check-deserializations.cpp b/test/PCH/check-deserializations.cpp
index e4dafb7..e24d205 100644
--- a/test/PCH/check-deserializations.cpp
+++ b/test/PCH/check-deserializations.cpp
@@ -1,6 +1,9 @@
-// RUN: %clang_cc1 -emit-pch -o %t.1 %s
-// RUN: %clang_cc1 -error-on-deserialized-decl S1_keyfunc -error-on-deserialized-decl S3 -include-pch %t.1 -emit-pch -o %t.2 %s
-// RUN: %clang_cc1 -error-on-deserialized-decl S1_method -error-on-deserialized-decl S3 -include-pch %t.2 -emit-llvm-only %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-pch -o %t.1 %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -error-on-deserialized-decl S1_keyfunc -error-on-deserialized-decl S3 -include-pch %t.1 -emit-pch -o %t.2 %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -error-on-deserialized-decl S1_method -error-on-deserialized-decl S3 -include-pch %t.2 -emit-llvm-only %s
+
+// FIXME: Why does this require an x86 target?
+// REQUIRES: x86-registered-target
 
 #ifndef HEADER1
 #define HEADER1
diff --git a/test/PCH/cxx-templates.cpp b/test/PCH/cxx-templates.cpp
index 52ea875..d50eee0 100644
--- a/test/PCH/cxx-templates.cpp
+++ b/test/PCH/cxx-templates.cpp
@@ -10,7 +10,7 @@
 // Test with modules.
 // RUN: %clang_cc1 -std=c++11 -triple %itanium_abi_triple -fcxx-exceptions -fexceptions -fmodules -x c++-header -emit-pch -o %t %S/cxx-templates.h
 // RUN: %clang_cc1 -std=c++11 -triple %itanium_abi_triple -fcxx-exceptions -fexceptions -fmodules -include-pch %t -verify %s -ast-dump  -o -
-// RUN: %clang_cc1 -std=c++11 -triple %itanium_abi_triple -fcxx-exceptions -fexceptions -fmodules -include-pch %t %s -emit-llvm -o - -error-on-deserialized-decl doNotDeserialize -DNO_ERRORS | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -triple %itanium_abi_triple -fcxx-exceptions -fexceptions -fmodules -include-pch %t %s -emit-llvm -o - -error-on-deserialized-decl doNotDeserialize -DNO_ERRORS -fmodules-ignore-macro=NO_ERRORS | FileCheck %s
 
 // Test with pch and delayed template parsing.
 // RUN: %clang_cc1 -std=c++11 -triple %itanium_abi_triple -fcxx-exceptions -fdelayed-template-parsing -fexceptions -x c++-header -emit-pch -o %t %S/cxx-templates.h
diff --git a/test/PCH/cxx11-lambdas.mm b/test/PCH/cxx11-lambdas.mm
index c455051..5d3323a 100644
--- a/test/PCH/cxx11-lambdas.mm
+++ b/test/PCH/cxx11-lambdas.mm
@@ -52,6 +52,6 @@
 // CHECK-PRINT: lambda = [&] (int z)
 
 // CHECK-PRINT: init_capture
-// CHECK-PRINT: [&, x( t )]
+// CHECK-PRINT: [&, x(t)]
 
 #endif
diff --git a/test/PCH/cxx1y-lambdas.mm b/test/PCH/cxx1y-lambdas.mm
index ee4a2ba..1cd2706 100644
--- a/test/PCH/cxx1y-lambdas.mm
+++ b/test/PCH/cxx1y-lambdas.mm
@@ -50,9 +50,9 @@
 }

 

 // CHECK-PRINT: inline int add_int_slowly_twice 

-// CHECK-PRINT: lambda = [] ($auto-0-0 z

+// CHECK-PRINT: lambda = [] (type-parameter-0-0 z

 

 // CHECK-PRINT: init_capture

-// CHECK-PRINT: [&, x( t )]

+// CHECK-PRINT: [&, x(t)]

 

 #endif

diff --git a/test/PCH/headersearch.cpp b/test/PCH/headersearch.cpp
index 4b24ac6..736ba19 100644
--- a/test/PCH/headersearch.cpp
+++ b/test/PCH/headersearch.cpp
@@ -15,20 +15,23 @@
 // RUN: echo '#include "orig_sub2.h"' >> %t_orig/all.h
 // RUN: echo 'int all();' >> %t_orig/all.h
 
+// This test relies on -Wpadded, which is only implemented for Itanium record
+// layout.
+
 // Generate the PCH:
-// RUN: cd %t_orig && %clang_cc1 -x c++ -emit-pch -o all.h.pch -Isub2 all.h
+// RUN: cd %t_orig && %clang_cc1 -triple %itanium_abi_triple -x c++ -emit-pch -o all.h.pch -Isub2 all.h
 // RUN: cp -pR %t_orig %t_moved
 
 // Check diagnostic with location in original source:
-// RUN: %clang_cc1 -include-pch all.h.pch -I%t_moved -I%t_moved/sub2 -Wpadded -emit-llvm-only %s 2> %t.stderr
+// RUN: %clang_cc1 -triple %itanium_abi_triple -include-pch all.h.pch -I%t_moved -I%t_moved/sub2 -Wpadded -emit-llvm-only %s 2> %t.stderr
 // RUN: grep 'struct orig_sub' %t.stderr
 
 // Check diagnostic with 2nd location in original source:
-// RUN: not %clang_cc1 -DREDECL -include-pch all.h.pch -I%t_moved -I%t_moved/sub2 -emit-llvm-only %s 2> %t.stderr
+// RUN: not %clang_cc1 -triple %itanium_abi_triple -DREDECL -include-pch all.h.pch -I%t_moved -I%t_moved/sub2 -emit-llvm-only %s 2> %t.stderr
 // RUN: grep 'void foo' %t.stderr
 
 // Check diagnostic with instantiation location in original source:
-// RUN: not %clang_cc1 -DINSTANTIATION -include-pch all.h.pch -I%t_moved -I%t_moved/sub2 -emit-llvm-only %s 2> %t.stderr
+// RUN: not %clang_cc1 -triple %itanium_abi_triple -DINSTANTIATION -include-pch all.h.pch -I%t_moved -I%t_moved/sub2 -emit-llvm-only %s 2> %t.stderr
 // RUN: grep 'orig_sub2_1' %t.stderr
 
 void qq(orig_sub*) {all();}
diff --git a/test/PCH/implicitly-deleted.cpp b/test/PCH/implicitly-deleted.cpp
new file mode 100644
index 0000000..5238fd3
--- /dev/null
+++ b/test/PCH/implicitly-deleted.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -std=c++11 -x c++-header %s -emit-pch -o %t.pch
+// RUN: %clang_cc1 -std=c++11 -x c++ /dev/null -include-pch %t.pch
+class move_only { move_only(const move_only&) = delete; move_only(move_only&&); };
+struct sb {
+  move_only il;
+  sb();
+  sb(sb &&);
+};
+
+template<typename T> T make();
+template<typename T> void doit(decltype(T(make<const T&>()))*) { T(make<const T&>()); }
+template<typename T> void doit(...) { T(make<T&&>()); }
+template<typename T> void later() { doit<T>(0); }
+
+void fn1() {
+  sb x;
+  later<sb>();
+}
diff --git a/test/PCH/module-hash-difference.m b/test/PCH/module-hash-difference.m
new file mode 100644
index 0000000..073540e
--- /dev/null
+++ b/test/PCH/module-hash-difference.m
@@ -0,0 +1,8 @@
+// RUN: rm -rf %t.mcp
+// RUN: rm -rf %t.err
+// RUN: %clang_cc1 -emit-pch -o %t.pch %s -I %S/Inputs/modules -fmodules -fmodules-cache-path=%t.mcp
+// RUN: not %clang_cc1 -fsyntax-only -include-pch %t.pch %s -I %S/Inputs/modules -fmodules -fmodules-cache-path=%t.mcp -fdisable-module-hash 2> %t.err
+// RUN: FileCheck -input-file=%t.err %s
+
+// CHECK: error: PCH was compiled with module cache path {{.*}}, but the path is currently {{.*}}
+@import Foo;
diff --git a/test/Parser/DelayedTemplateParsing.cpp b/test/Parser/DelayedTemplateParsing.cpp
index eff3120..6ea245c 100644
--- a/test/Parser/DelayedTemplateParsing.cpp
+++ b/test/Parser/DelayedTemplateParsing.cpp
@@ -10,8 +10,8 @@
 
 template <class T>
 class B {
-   void foo4() { } // expected-note {{previous definition is here}}  expected-note {{previous definition is here}}
-   void foo4() { } // expected-error {{class member cannot be redeclared}} expected-error {{redefinition of 'foo4'}}
+   void foo4() { } // expected-note {{previous definition is here}}
+   void foo4() { } // expected-error {{class member cannot be redeclared}}
    void foo5() { } // expected-note {{previous definition is here}}
 
    friend void foo3() {
diff --git a/test/Parser/MicrosoftExtensions.c b/test/Parser/MicrosoftExtensions.c
index d7ea20b..83e0921 100644
--- a/test/Parser/MicrosoftExtensions.c
+++ b/test/Parser/MicrosoftExtensions.c
@@ -5,7 +5,7 @@
 void (*__fastcall fastpfunc)(void);
 extern __declspec(dllimport) void __stdcall VarR4FromDec(void);
 __declspec(deprecated) __declspec(deprecated) char * __cdecl ltoa( long _Val, char * _DstBuf, int _Radix);
-__declspec(safebuffers) __declspec(noalias) __declspec(restrict) void * __cdecl xxx(void *_Memory); /* expected-warning{{__declspec attribute 'safebuffers' is not supported}} expected-warning{{__declspec attribute 'noalias' is not supported}} expected-warning{{__declspec attribute 'restrict' is not supported}} */
+__declspec(safebuffers) __declspec(noalias) __declspec(restrict) void * __cdecl xxx(void *_Memory); /* expected-warning{{__declspec attribute 'safebuffers' is not supported}} expected-warning{{__declspec attribute 'noalias' is not supported}} */
 typedef __w64 unsigned long ULONG_PTR, *PULONG_PTR;
 
 void * __ptr64 PtrToPtr64(const void *p) {
@@ -85,3 +85,11 @@
 
 /* Legal to have nested pointer attributes */
 int * __sptr * __ptr32 ppsp32;
+
+// Ignored type qualifiers after comma in declarator lists
+typedef int ignored_quals_dummy1, const volatile __ptr32 __ptr64 __w64 __unaligned __sptr __uptr ignored_quals1; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy2)(), __fastcall ignored_quals2; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy3)(), __stdcall ignored_quals3; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy4)(), __thiscall ignored_quals4; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy5)(), __cdecl ignored_quals5; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy6)(), __vectorcall ignored_quals6; // expected-warning {{qualifiers after comma in declarator list are ignored}}
diff --git a/test/Parser/MicrosoftExtensions.cpp b/test/Parser/MicrosoftExtensions.cpp
index 85ccdc5..736e69a 100644
--- a/test/Parser/MicrosoftExtensions.cpp
+++ b/test/Parser/MicrosoftExtensions.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -triple i386-mingw32 -std=c++11 -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-extensions -fms-compatibility -fdelayed-template-parsing
+// RUN: %clang_cc1 %s -triple i386-mingw32 -std=c++14 -fsyntax-only -Wno-unused-getter-return-value -Wno-unused-value -Wmicrosoft -verify -fms-extensions -fms-compatibility -fdelayed-template-parsing
 
 /* Microsoft attribute tests */
 [repeatable][source_annotation_attribute( Parameter|ReturnValue )]
@@ -320,6 +320,7 @@
   __declspec(property(get=GetV,)) int V10; // expected-error {{expected 'get' or 'put' in property declaration}}
   __declspec(property(get=GetV,put=SetV)) int V11; // no-warning
   __declspec(property(get=GetV,put=SetV,get=GetV)) int V12; // expected-error {{property declaration specifies 'get' accessor twice}}
+  __declspec(property(get=GetV)) int V13 = 3; // expected-error {{property declaration cannot have an in-class initializer}}
 
   int GetV() { return 123; }
   void SetV(int v) {}
@@ -338,7 +339,7 @@
 //expected-warning@+1 {{C++ operator 'and' (aka '&&') used as a macro name}}
 #define and foo
 
-struct __declspec(uuid("00000000-0000-0000-C000-000000000046")) __declspec(novtable) IUnknown {}; // expected-warning{{__declspec attribute 'novtable' is not supported}}
+struct __declspec(uuid("00000000-0000-0000-C000-000000000046")) __declspec(novtable) IUnknown {};
 
 typedef bool (__stdcall __stdcall *blarg)(int);
 
@@ -366,3 +367,27 @@
 template <int *>
 struct NullptrArg {};
 NullptrArg<nullptr> a;
+
+// Ignored type qualifiers after comma in declarator lists
+typedef int ignored_quals_dummy1, const volatile __ptr32 __ptr64 __w64 __unaligned __sptr __uptr ignored_quals1; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy2)(), __fastcall ignored_quals2; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy3)(), __stdcall ignored_quals3; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy4)(), __thiscall ignored_quals4; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy5)(), __cdecl ignored_quals5; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+typedef void(*ignored_quals_dummy6)(), __vectorcall ignored_quals6; // expected-warning {{qualifiers after comma in declarator list are ignored}}
+
+namespace {
+bool f(int);
+template <typename T>
+struct A {
+  constexpr A(T t) {
+    __assume(f(t)); // expected-warning{{the argument to '__assume' has side effects that will be discarded}}
+  }
+  constexpr bool g() { return false; }
+};
+constexpr A<int> h() {
+  A<int> b(0); // expected-note {{in instantiation of member function}}
+  return b;
+}
+static_assert(h().g() == false, "");
+}
diff --git a/test/Parser/PR21872.cpp b/test/Parser/PR21872.cpp
new file mode 100644
index 0000000..ae0a13d
--- /dev/null
+++ b/test/Parser/PR21872.cpp
@@ -0,0 +1,4 @@
+// RUN: not %clang_cc1 -fsyntax-only %s
+template <typename T> struct S {
+    int k = ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
+int f;
diff --git a/test/Parser/access-spec-attrs.cpp b/test/Parser/access-spec-attrs.cpp
index 4fa5975..2958e38 100644
--- a/test/Parser/access-spec-attrs.cpp
+++ b/test/Parser/access-spec-attrs.cpp
@@ -5,6 +5,7 @@
   void foo();
 private __attribute__((annotate("foobar"))):
     void bar();
+private __attribute__((annotate())): // expected-error {{'annotate' attribute takes one argument}}
 };
 
 void f(X x) {
diff --git a/test/Parser/altivec.c b/test/Parser/altivec.c
index 7adca61..d852511 100644
--- a/test/Parser/altivec.c
+++ b/test/Parser/altivec.c
@@ -18,6 +18,9 @@
 __vector bool char vv_bc;
 __vector bool short vv_bs;
 __vector bool int vv_bi;
+__vector __bool char vv___bc;
+__vector __bool short vv___bs;
+__vector __bool int vv_bi;
 __vector __pixel vv_p;
 __vector pixel vv__p;
 __vector int vf__r();
@@ -40,6 +43,9 @@
 vector bool char v_bc;
 vector bool short v_bs;
 vector bool int v_bi;
+vector __bool char v___bc;
+vector __bool short v___bs;
+vector __bool int v___bi;
 vector __pixel v_p;
 vector pixel v__p;
 vector int f__r();
@@ -64,6 +70,7 @@
 __vector long double  vv_ld;        // expected-error {{cannot use 'long double' with '__vector'}}
 vector long double  v_ld;           // expected-error {{cannot use 'long double' with '__vector'}}
 vector bool v_b;                    // expected-warning {{type specifier missing, defaults to 'int'}}
+vector __bool v___b;                // expected-warning {{type specifier missing, defaults to 'int'}}
 
 // These should have errors.
 __vector double vv_d1;               // expected-error {{use of 'double' with '__vector' requires VSX support to be enabled (available on the POWER7 or later)}}
@@ -77,6 +84,13 @@
 vector bool unsigned int v_bsc2;     // expected-error {{cannot use 'unsigned' with '__vector bool'}}
 vector bool long v_bl;               // expected-error {{cannot use 'long' with '__vector bool'}}
 vector bool long long v_bll;         // expected-error {{cannot use 'long long' with '__vector bool'}}
+vector __bool float v___bf;          // expected-error {{cannot use 'float' with '__vector bool'}}
+vector __bool double v___bd;         // expected-error {{cannot use 'double' with '__vector bool'}}
+vector __bool pixel v___bp;          // expected-error {{cannot use '__pixel' with '__vector bool'}}
+vector __bool signed char v___bsc;   // expected-error {{cannot use 'signed' with '__vector bool'}}
+vector __bool unsigned int v___bsc2; // expected-error {{cannot use 'unsigned' with '__vector bool'}}
+vector __bool long v___bl;           // expected-error {{cannot use 'long' with '__vector bool'}}
+vector __bool long long v___bll;     // expected-error {{cannot use 'long long' with '__vector bool'}}
 
 // vector long is deprecated, but vector long long is not.
 vector long long v_ll;
diff --git a/test/Parser/asm.cpp b/test/Parser/asm.cpp
index 35a497c..9f64dfe 100644
--- a/test/Parser/asm.cpp
+++ b/test/Parser/asm.cpp
@@ -6,3 +6,4 @@
 int foo4 asm (u"bar4"); // expected-error {{cannot use unicode string literal in 'asm'}}
 int foo5 asm (U"bar5"); // expected-error {{cannot use unicode string literal in 'asm'}}
 int foo6 asm ("bar6"_x); // expected-error {{string literal with user-defined suffix cannot be used here}}
+int foo6 asm ("" L"bar7"); // expected-error {{cannot use wide string literal in 'asm'}}
diff --git a/test/Parser/colon-colon-parentheses.cpp b/test/Parser/colon-colon-parentheses.cpp
index 55948fd..e031ce2 100644
--- a/test/Parser/colon-colon-parentheses.cpp
+++ b/test/Parser/colon-colon-parentheses.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -fsyntax-only -verify -DPR21815
 // RUN: cp %s %t
 // RUN: not %clang_cc1 -x c++ -fixit %t
 // RUN: %clang_cc1 -x c++ %t
@@ -20,3 +20,11 @@
   a = ::(h;  // expected-error{{unexpected parenthesis after '::'}}
   a = ::i;
 }
+
+#ifdef PR21815
+// expected-error@+4{{C++ requires a type specifier for all declarations}}
+// expected-error@+3{{expected unqualified-id}}
+// expected-error@+3{{expected expression}}
+// expected-error@+1{{expected ';' after top level declarator}}
+a (::(
+#endif
diff --git a/test/Parser/crash-report.c b/test/Parser/crash-report.c
index 6f37062..ef65b88 100644
--- a/test/Parser/crash-report.c
+++ b/test/Parser/crash-report.c
@@ -1,6 +1,10 @@
 // RUN: not --crash %clang_cc1 %s 2>&1 | FileCheck %s
 // REQUIRES: crash-recovery
 
+// FIXME: CHECKs might be incompatible to win32.
+// Stack traces also require back traces.
+// REQUIRES: shell, backtrace
+
 #prag\
 ma clang __debug crash
 
diff --git a/test/Parser/cxx-attributes.cpp b/test/Parser/cxx-attributes.cpp
index 6fd7f4f..6591532 100644
--- a/test/Parser/cxx-attributes.cpp
+++ b/test/Parser/cxx-attributes.cpp
@@ -20,3 +20,5 @@
   typedef int __attribute__((aligned(int(1)))) T1;
   typedef int __attribute__((aligned(int))) T2; // expected-error {{expected '(' for function-style cast}}
 }
+
+__attribute((typename)) int x; // expected-warning {{unknown attribute 'typename' ignored}}
diff --git a/test/Parser/cxx-class.cpp b/test/Parser/cxx-class.cpp
index b6eb1b4..215c941 100644
--- a/test/Parser/cxx-class.cpp
+++ b/test/Parser/cxx-class.cpp
@@ -140,8 +140,8 @@
 }
 
 namespace DtorErrors {
-  struct A { ~A(); } a;
-  ~A::A() {} // expected-error {{'~' in destructor name should be after nested name specifier}} expected-note {{previous}}
+  struct A { ~A(); int n; } a;
+  ~A::A() { n = 0; } // expected-error {{'~' in destructor name should be after nested name specifier}} expected-note {{previous}}
   A::~A() {} // expected-error {{redefinition}}
 
   struct B { ~B(); } *b;
@@ -151,6 +151,34 @@
     a.~A::A(); // expected-error {{'~' in destructor name should be after nested name specifier}}
     b->~DtorErrors::~B::B(); // expected-error {{'~' in destructor name should be after nested name specifier}}
   }
+
+  struct C; // expected-note {{forward decl}}
+  ~C::C() {} // expected-error {{incomplete}} expected-error {{'~' in destructor name should be after nested name specifier}}
+
+  struct D { struct X {}; ~D() throw(X); };
+  ~D::D() throw(X) {} // expected-error {{'~' in destructor name should be after nested name specifier}}
+
+  ~Undeclared::Undeclared() {} // expected-error {{use of undeclared identifier 'Undeclared'}} expected-error {{'~' in destructor name should be after nested name specifier}}
+
+  struct S {
+    // For another struct's destructor, emit the same diagnostic like for
+    // A::~A() in addition to the "~ in the wrong place" one.
+    ~A::A() {} // expected-error {{'~' in destructor name should be after nested name specifier}} expected-error {{non-friend class member '~A' cannot have a qualified name}}
+    A::~A() {} // expected-error {{non-friend class member '~A' cannot have a qualified name}}
+
+    // An inline destructor with a redundant class name should also get the
+    // same diagnostic as S::~S.
+    ~S::S() {} // expected-error {{'~' in destructor name should be after nested name specifier}} expected-error {{extra qualification on member '~S'}}
+
+    // This just shouldn't crash.
+    int I; // expected-note {{declared here}}
+    ~I::I() {} // expected-error {{'I' is not a class, namespace, or enumeration}} expected-error {{'~' in destructor name should be after nested name specifier}}
+  };
+
+  struct T {};
+  T t1 = t1.T::~T<int>; // expected-error {{destructor name 'T' does not refer to a template}} expected-error {{expected '(' for function-style cast or type construction}} expected-error {{expected expression}}
+  // Emit the same diagnostic as for the previous case, plus something about ~.
+  T t2 = t2.~T::T<int>; // expected-error {{'~' in destructor name should be after nested name specifier}} expected-error {{destructor name 'T' does not refer to a template}} expected-error {{expected '(' for function-style cast or type construction}} expected-error {{expected expression}}
 }
 
 namespace BadFriend {
@@ -179,6 +207,14 @@
 class X2 { a::a; }; // expected-error {{undeclared identifier 'a'}}
 }
 
+class BadExceptionSpec {
+  void f() throw(int; // expected-error {{expected ')'}} expected-note {{to match}}
+  void g() throw( // expected-note {{to match}}
+      int( // expected-note {{to match}}
+          ; // expected-error 2{{expected ')'}} expected-error {{unexpected end of exception specification}}
+          ));
+};
+
 // PR11109 must appear at the end of the source file
 class pr11109r3 { // expected-note{{to match this '{'}}
   public // expected-error{{expected ':'}} expected-error{{expected '}'}} expected-error{{expected ';' after class}}
diff --git a/test/Parser/cxx-default-args.cpp b/test/Parser/cxx-default-args.cpp
index f0e2e69..0095a2f 100644
--- a/test/Parser/cxx-default-args.cpp
+++ b/test/Parser/cxx-default-args.cpp
@@ -36,3 +36,8 @@
 struct S { 
   void f(int &r = error);  // expected-error {{use of undeclared identifier 'error'}}
 };
+
+struct U {
+  void i(int x = ) {} // expected-error{{expected expression}}
+  typedef int *fp(int x = ); // expected-error{{default arguments can only be specified for parameters in a function declaration}}
+};
diff --git a/test/Parser/cxx-member-initializers.cpp b/test/Parser/cxx-member-initializers.cpp
index ff8c880..8e52adb 100644
--- a/test/Parser/cxx-member-initializers.cpp
+++ b/test/Parser/cxx-member-initializers.cpp
@@ -66,12 +66,12 @@
 
     struct T { int n; };
     template<typename> struct A { int n; };
-  }; // expected-error +{{}}
+  };
 
   // FIXME: This is valid now, but may be made ill-formed by DR1607.
   struct G : X<0> {
     G() : X<0 && [](){return 0;}()>{} // expected-error +{{}}
-  }; // expected-error +{{}}
+  };
 
   struct Errs : X<0> {
     Errs(X<0>) : decltype X<0>() {} // expected-error {{expected '(' after 'decltype'}}
@@ -79,3 +79,29 @@
     Errs(X<2>) : decltype(X<0> // expected-note {{to match this '('}}
   }; // expected-error {{expected ')'}}
 }
+
+template <class U, class V> struct C {
+  int f() { return 4; }
+  class C1 {};
+};
+
+class D {};
+namespace N {
+struct E {
+  class F {};
+};
+}
+
+class G {
+  // These are all valid:
+  void f(int x = C<int, D>().f()) {}
+  void g(int x = C<int, ::D>().f()) {}
+  void h(int x = C<int, N::E>().f()) {}
+  void i(int x = C<int, ::N::E>().f()) {}
+  void j(int x = C<int, decltype(N::E())::F>().f()) {}
+  void k(int x = C<int, C<int, int>>().f()) {}
+  void l(int x = C<int, C<int, int>::C1>().f()) {}
+
+  // This isn't, but it shouldn't crash. The diagnostics don't matter much.
+  void m(int x = C<int, union int>().f()) {} // expected-error {{declaration of anonymous union must be a definition}} expected-error {{expected a type}}
+};
diff --git a/test/Parser/cxx-template-decl.cpp b/test/Parser/cxx-template-decl.cpp
index bce1b7c..efa42ad 100644
--- a/test/Parser/cxx-template-decl.cpp
+++ b/test/Parser/cxx-template-decl.cpp
@@ -211,6 +211,19 @@
 
 }
 
+namespace func_tmpl_spec_def_in_func {
+// We failed to diagnose function template specialization definitions inside
+// functions during recovery previously.
+template <class> void FuncTemplate() {}
+void TopLevelFunc() {
+  // expected-error@+2 {{expected a qualified name after 'typename'}}
+  // expected-error@+1 {{function definition is not allowed here}}
+  typename template <> void FuncTemplate<void>() { }
+  // expected-error@+1 {{function definition is not allowed here}}
+  void NonTemplateInner() { }
+}
+}
+
 namespace broken_baseclause {
 template<typename T>
 struct base { };
diff --git a/test/Parser/cxx0x-ambig.cpp b/test/Parser/cxx0x-ambig.cpp
index b06f432..a47585f 100644
--- a/test/Parser/cxx0x-ambig.cpp
+++ b/test/Parser/cxx0x-ambig.cpp
@@ -110,8 +110,8 @@
   template<typename...T>
   struct S {
     void e(S::S());
-    void f(S(...args[sizeof(T)])); // expected-note {{here}}
-    void f(S(...args)[sizeof(T)]); // expected-error {{redeclared}} expected-note {{here}}
+    void f(S(...args[sizeof(T)])); // expected-note {{here}} expected-note {{here}}
+    void f(S(...args)[sizeof(T)]); // expected-error {{redeclared}}
     void f(S ...args[sizeof(T)]); // expected-error {{redeclared}}
     void g(S(...[sizeof(T)])); // expected-note {{here}} expected-warning {{ISO C++11 requires a parenthesized pack declaration to have a name}}
     void g(S(...)[sizeof(T)]); // expected-error {{function cannot return array type}}
diff --git a/test/Parser/cxx0x-attributes.cpp b/test/Parser/cxx0x-attributes.cpp
index e366d85..33987f9 100644
--- a/test/Parser/cxx0x-attributes.cpp
+++ b/test/Parser/cxx0x-attributes.cpp
@@ -86,6 +86,10 @@
   [[]] [[]] alignas(16) final // expected-error {{an attribute list cannot appear here}}
   [[]] [[]] alignas(16) [[]]{}; // expected-error {{an attribute list cannot appear here}}
 
+// The diagnostics here don't matter much, this just shouldn't crash:
+class C final [[deprecated(l]] {}); // expected-error {{use of undeclared identifier}} expected-error {{expected ']'}} expected-error {{an attribute list cannot appear here}} expected-error {{expected unqualified-id}}
+class D final alignas ([l) {}]{}); // expected-error {{expected ',' or ']' in lambda capture list}} expected-error {{an attribute list cannot appear here}}
+
 [[]] struct with_init_declarators {} init_declarator;
 [[]] struct no_init_declarators; // expected-error {{an attribute list cannot appear here}}
 template<typename> [[]] struct no_init_declarators_template; // expected-error {{an attribute list cannot appear here}}
@@ -284,6 +288,7 @@
   void f[[gnu::format(printf, 1, 2)]](const char*, ...);
   void g() [[unknown::foo(ignore arguments for unknown attributes, even with symbols!)]]; // expected-warning {{unknown attribute 'foo' ignored}}
   [[deprecated("with argument")]] int i;
+  // expected-warning@-1 {{use of the 'deprecated' attribute is a C++14 extension}}
 }
 
 // Forbid attributes on decl specifiers.
@@ -326,7 +331,18 @@
 
 namespace {
   [[deprecated]] void bar();
+  // expected-warning@-1 {{use of the 'deprecated' attribute is a C++14 extension}}
   [[deprecated("hello")]] void baz();
-  [[deprecated()]] void foo(); // expected-error {{parentheses must be omitted if 'deprecated' attribute's argument list is empty}}
+  // expected-warning@-1 {{use of the 'deprecated' attribute is a C++14 extension}}
+  [[deprecated()]] void foo();
+  // expected-error@-1 {{parentheses must be omitted if 'deprecated' attribute's argument list is empty}}
+  // expected-warning@-2 {{use of the 'deprecated' attribute is a C++14 extension}}
   [[gnu::deprecated()]] void quux();
 }
+
+namespace {
+[[ // expected-error {{expected ']'}}
+#pragma pack(pop)
+deprecated
+]] void bad();
+}
diff --git a/test/Parser/cxx0x-lambda-expressions.cpp b/test/Parser/cxx0x-lambda-expressions.cpp
index 8cfe7f3..c2bf6fd 100644
--- a/test/Parser/cxx0x-lambda-expressions.cpp
+++ b/test/Parser/cxx0x-lambda-expressions.cpp
@@ -61,7 +61,7 @@
   int z;
   void init_capture() {
     [n(0)] () mutable -> int { return ++n; }; // expected-warning{{extension}}
-    [n{0}] { return; }; // expected-error {{<initializer_list>}} expected-warning{{extension}}
+    [n{0}] { return; }; // expected-error {{<initializer_list>}} expected-warning{{extension}} expected-warning{{will change meaning in a future version}}
     [n = 0] { return ++n; }; // expected-error {{captured by copy in a non-mutable}} expected-warning{{extension}}
     [n = {0}] { return; }; // expected-error {{<initializer_list>}} expected-warning{{extension}}
     [a([&b = z]{})](){}; // expected-warning 2{{extension}}
@@ -91,3 +91,20 @@
       __attribute__((noreturn)) { while(1); }; // expected-error {{expected body of lambda expression}}
   }
 };
+
+template <typename>
+void PR22122() {
+  [](int) -> {}; // expected-error {{expected a type}}
+}
+
+template void PR22122<int>();
+
+struct S {
+  template <typename T>
+  void m (T x =[0); // expected-error{{expected variable name or 'this' in lambda capture list}}
+} s;
+
+struct U {
+  template <typename T>
+  void m_fn1(T x = 0[0); // expected-error{{expected ']'}} expected-note{{to match this '['}}
+} *U;
diff --git a/test/Parser/debugger-import-module.m b/test/Parser/debugger-import-module.m
new file mode 100644
index 0000000..b6001ae
--- /dev/null
+++ b/test/Parser/debugger-import-module.m
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -fdebugger-support -verify %s
+// expected-no-diagnostics
+
+void importAModule() {
+  @import AModuleThatDoesntExist
+}
diff --git a/test/Parser/ms-if-exists.c b/test/Parser/ms-if-exists.c
new file mode 100644
index 0000000..7dd2054
--- /dev/null
+++ b/test/Parser/ms-if-exists.c
@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
+// expected-no-diagnostics
+
+struct Type {
+};
+
+void test_if_exists_stmts() {
+  int b = 0;
+  __if_exists(Type) {
+    b++;
+    b++;
+  }
+  __if_exists(Type_not) {
+    this will not compile.
+  }
+  __if_not_exists(Type) {
+    this will not compile.
+  }
+  __if_not_exists(Type_not) {
+    b++;
+    b++;
+  }
+}
+
+int if_exists_creates_no_scope() {
+  __if_exists(Type) {
+    int x;  // 'x' is declared in the parent scope.
+  }
+  __if_not_exists(Type_not) {
+    x++;
+  }
+  return x;
+}
+
+__if_exists(Type) {
+  int var23;
+}
+
+__if_exists(Type_not) {
+  this will not compile.
+}
+
+__if_not_exists(Type) {
+  this will not compile.
+}
+
+__if_not_exists(Type_not) {
+  int var244;
+}
+
+void test_if_exists_init_list() {
+
+  int array1[] = {
+    0,
+    __if_exists(Type) {2, }
+    3
+  };
+
+  int array2[] = {
+    0,
+    __if_exists(Type_not) { this will not compile }
+    3
+  };
+
+  int array3[] = {
+    0,
+    __if_not_exists(Type_not) {2, }
+    3
+  };
+
+  int array4[] = {
+    0,
+    __if_not_exists(Type) { this will not compile }
+    3
+  };
+
+}
+
+
+void test_nested_if_exists() {
+  __if_exists(Type) {
+    int x = 42;
+    __if_not_exists(Type_not) {
+      x++;
+    }
+  }
+}
diff --git a/test/Parser/ms-inline-asm.c b/test/Parser/ms-inline-asm.c
index 72c96c3..6dde5f5 100644
--- a/test/Parser/ms-inline-asm.c
+++ b/test/Parser/ms-inline-asm.c
@@ -1,5 +1,7 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 %s -triple i386-apple-darwin10 -verify -fasm-blocks
+// Disabling gnu inline assembly should have no effect on this testcase
+// RUN: %clang_cc1 %s -triple i386-apple-darwin10 -verify -fasm-blocks -fno-gnu-inline-asm
 
 #define M __asm int 0x2c
 #define M2 int
diff --git a/test/Parser/ms-seh.c b/test/Parser/ms-seh.c
new file mode 100644
index 0000000..68c2e30
--- /dev/null
+++ b/test/Parser/ms-seh.c
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
+
+void f() {
+  int a;
+
+  __try a; // expected-error {{expected '{'}} expected-warning {{expression result unused}}
+
+  __try {
+  }
+} // expected-error {{expected '__except' or '__finally' block}}
+
+void g() {
+  int a;
+
+  __try {
+  } __except(1) a; // expected-error {{expected '{'}} expected-warning {{expression result unused}}
+}
+
+void h() {
+  int a;
+
+  __try {
+  } __finally a; // expected-error {{expected '{'}} expected-warning {{expression result unused}}
+}
diff --git a/test/Parser/namespaces.cpp b/test/Parser/namespaces.cpp
index 6491cfd..25ff73b 100644
--- a/test/Parser/namespaces.cpp
+++ b/test/Parser/namespaces.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
 
 // PR6596
 namespace g { enum { o = 0 }; }
@@ -10,3 +10,7 @@
 // PR14085
 namespace PR14085 {}
 namespace = PR14085; // expected-error {{expected identifier}}
+
+struct namespace_nested_in_record {
+  int k = ({namespace {}}); // expected-error {{statement expression not allowed at file scope}}
+};
diff --git a/test/Parser/no-gnu-inline-asm.c b/test/Parser/no-gnu-inline-asm.c
new file mode 100644
index 0000000..78f470f
--- /dev/null
+++ b/test/Parser/no-gnu-inline-asm.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 %s -triple i686-apple-darwin -verify -fsyntax-only -fno-gnu-inline-asm
+
+void f (void) {
+  long long foo = 0, bar;
+  asm volatile("INST %0, %1" : "=r"(foo) : "r"(bar)); // expected-error {{GNU-style inline assembly is disabled}}
+  return;
+}
diff --git a/test/Parser/objcxx0x-lambda-expressions.mm b/test/Parser/objcxx0x-lambda-expressions.mm
index bef576a..3954a80 100644
--- a/test/Parser/objcxx0x-lambda-expressions.mm
+++ b/test/Parser/objcxx0x-lambda-expressions.mm
@@ -21,7 +21,7 @@
 
     [foo(bar)] () {};
     [foo = bar] () {};
-    [foo{bar}] () {}; // expected-error {{<initializer_list>}}
+    [foo{bar}] () {}; // expected-error {{<initializer_list>}} expected-warning {{will change meaning}}
     [foo = {bar}] () {}; // expected-error {{<initializer_list>}}
 
     [foo(bar) baz] () {}; // expected-error {{called object type 'int' is not a function}}
diff --git a/test/Parser/opencl-cl20.cl b/test/Parser/opencl-cl20.cl
new file mode 100644
index 0000000..b718699
--- /dev/null
+++ b/test/Parser/opencl-cl20.cl
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL2.0 -DCL20
+
+#ifdef CL20
+// expected-no-diagnostics
+#endif
+
+__generic int * __generic_test(__generic int *arg) {
+  __generic int *var;
+  return var;  
+}
+#ifndef CL20
+// expected-error@-5 {{OpenCL does not support the '__generic' type qualifier}}
+// expected-error@-6 {{OpenCL does not support the '__generic' type qualifier}}
+// expected-error@-6 {{OpenCL does not support the '__generic' type qualifier}}
+#endif
+
+generic int * generic_test(generic int *arg) {
+  generic int *var;
+  return var;  
+}
+#ifndef CL20
+// expected-error@-5 {{OpenCL does not support the 'generic' type qualifier}}
+// expected-error@-6 {{OpenCL does not support the 'generic' type qualifier}}
+// expected-error@-6 {{OpenCL does not support the 'generic' type qualifier}}
+#endif
diff --git a/test/Parser/recovery.cpp b/test/Parser/recovery.cpp
index 5608b50..2d5b518 100644
--- a/test/Parser/recovery.cpp
+++ b/test/Parser/recovery.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -verify -std=c++11 %s
+// RUN: %clang_cc1 -verify -std=c++11 -fms-extensions %s
 
 8gi///===--- recovery.cpp ---===// // expected-error {{unqualified-id}}
 namespace Std { // expected-note {{here}}
@@ -154,17 +154,17 @@
   void func_1(int x) {
     switch(x) {
     case 0: break;
-    case ns::V1:: break; // expected-error{{'V1' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
-    case C1::V2:: break; // expected-error{{'V2' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
-    case C1::V3:: break; // expected-error{{'V3' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
-    case V4:: break; // expected-error{{'V4' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
-    case V6:: func_3();   // expected-error{{'V6' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
+    case ns::V1:: break; // expected-error{{'V1' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
+    case C1::V2:: break; // expected-error{{'V2' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
+    case C1::V3:: break; // expected-error{{'V3' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
+    case V4:: break; // expected-error{{'V4' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
+    case V6:: func_3();   // expected-error{{'V6' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
     }
   }
   void func_2(EC3 x) {
     switch(x) {
     case EC3::V0:  break;
-    case EC3::V5:: break; // expected-error{{'V5' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
+    case EC3::V5:: break; // expected-error{{'V5' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
     }
   }
 
@@ -186,13 +186,13 @@
   };
 
   int func_3(int x) {
-    return x ? S::n :: 0;  // expected-error{{'n' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
+    return x ? S::n :: 0;  // expected-error{{'n' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
   }
   int func_4(int x, S &s) {
-    return x ? s.nn :: x;  // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
+    return x ? s.nn :: x;  // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
   }
   int func_5(int x, S &s) {
-    return x ? s.nn :: S::n;  // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or scoped enumeration; did you mean ':'?}}
+    return x ? s.nn :: S::n;  // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
   }
 
   struct S2 {
@@ -202,3 +202,13 @@
   struct S2 :: S3 :: public S2 {  // expected-error{{'public' cannot be a part of nested name specifier; did you mean ':'?}}
   };
 }
+
+namespace InvalidEmptyNames {
+// These shouldn't crash, the diagnostics aren't important.
+struct ::, struct ::; // expected-error 2 {{expected identifier}} expected-error 2 {{declaration of anonymous struct must be a definition}} expected-warning {{declaration does not declare anything}}
+enum ::, enum ::; // expected-error 2 {{expected identifier}} expected-warning {{declaration does not declare anything}}
+struct ::__super, struct ::__super; // expected-error 2 {{expected identifier}} expected-error 2 {{expected '::' after '__super'}}
+struct ::template foo, struct ::template bar; // expected-error 2 {{expected identifier}} expected-error 2 {{declaration of anonymous struct must be a definition}} expected-warning {{declaration does not declare anything}}
+struct ::foo struct::; // expected-error {{no struct named 'foo' in the global namespace}} expected-error {{expected identifier}} expected-error {{declaration of anonymous struct must be a definition}}
+class :: : {} a;  // expected-error {{expected identifier}} expected-error {{expected class name}}
+}
diff --git a/test/Parser/switch-recovery.cpp b/test/Parser/switch-recovery.cpp
index 5345170..4b06d55 100644
--- a/test/Parser/switch-recovery.cpp
+++ b/test/Parser/switch-recovery.cpp
@@ -220,3 +220,12 @@
   case bar5: ;  // expected-error{{use of undeclared identifier 'bar5'}}
 }
 }
+
+namespace pr21841 {
+void fn1() {
+  switch (0)
+    switch (0  // expected-note{{to match this '('}}
+    {  // expected-error{{expected ')'}}
+    }
+} // expected-error{{expected statement}}
+}
diff --git a/test/Preprocessor/_Pragma-location.c b/test/Preprocessor/_Pragma-location.c
index 5031ee4..a523c26 100644
--- a/test/Preprocessor/_Pragma-location.c
+++ b/test/Preprocessor/_Pragma-location.c
@@ -10,9 +10,9 @@
 
 push_p _Pragma("pack(push)") __pragma(pack(push))
 // CHECK: #pragma pack(push)
-// CHECK-NEXT: #line 11 "{{.*}}_Pragma-location.c"
+// CHECK-NEXT: # 11 "{{.*}}_Pragma-location.c"
 // CHECK-NEXT: #pragma pack(push)
-// CHECK-NEXT: #line 11 "{{.*}}_Pragma-location.c"
+// CHECK-NEXT: # 11 "{{.*}}_Pragma-location.c"
 // CHECK-NEXT: #pragma pack(push)
 
 
@@ -31,17 +31,17 @@
 
 // CHECK: void test () {
 // CHECK-NEXT:   1;
-// CHECK-NEXT: #line 24 "{{.*}}_Pragma-location.c"
+// CHECK-NEXT: # 24 "{{.*}}_Pragma-location.c"
 // CHECK-NEXT: #pragma clang diagnostic push
 // CHECK-NEXT: #pragma clang diagnostic ignored "-Wformat-extra-args"
 // CHECK-NEXT: #pragma clang diagnostic pop
 
 // CHECK:   2;
-// CHECK-NEXT: #line 28 "{{.*}}_Pragma-location.c"
+// CHECK-NEXT: # 28 "{{.*}}_Pragma-location.c"
 // CHECK-NEXT: #pragma clang diagnostic push
-// CHECK-NEXT: #line 28 "{{.*}}_Pragma-location.c"
+// CHECK-NEXT: # 28 "{{.*}}_Pragma-location.c"
 // CHECK-NEXT: #pragma clang diagnostic ignored "-Wformat-extra-args"
 // CHECK-NEXT:   3;
-// CHECK-NEXT: #line 29 "{{.*}}_Pragma-location.c"
+// CHECK-NEXT: # 29 "{{.*}}_Pragma-location.c"
 // CHECK-NEXT: #pragma clang diagnostic pop
 // CHECK-NEXT: }
diff --git a/test/Preprocessor/aarch64-target-features.c b/test/Preprocessor/aarch64-target-features.c
index 4e9e6c7..45a6c89 100644
--- a/test/Preprocessor/aarch64-target-features.c
+++ b/test/Preprocessor/aarch64-target-features.c
@@ -69,9 +69,11 @@
 // RUN: %clang -target aarch64 -mcpu=cyclone -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-CYCLONE %s
 // RUN: %clang -target aarch64 -mcpu=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A53 %s
 // RUN: %clang -target aarch64 -mcpu=cortex-a57 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A57 %s
+// RUN: %clang -target aarch64 -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A72 %s
 // CHECK-MCPU-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+zcm" "-target-feature" "+zcz"
 // CHECK-MCPU-A53: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto"
 // CHECK-MCPU-A57: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto"
+// CHECK-MCPU-A72: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto"
 
 // RUN: %clang -target x86_64-apple-macosx -arch arm64 -### -c %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH-ARM64 %s
 // CHECK-ARCH-ARM64: "-target-cpu" "cyclone" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+zcm" "-target-feature" "+zcz"
diff --git a/test/Preprocessor/arm-target-features.c b/test/Preprocessor/arm-target-features.c
index 8155e02..926a753 100644
--- a/test/Preprocessor/arm-target-features.c
+++ b/test/Preprocessor/arm-target-features.c
@@ -143,12 +143,22 @@
 // NONEON-A5:#define __ARM_VFPV4__ 1
 
 // FIXME: add check for further predefines
+// Test whether predefines are as expected when targeting ep9312.
+// RUN: %clang -target armv4t -mcpu=ep9312 -x c -E -dM %s -o - | FileCheck --check-prefix=A4T %s
+// A4T-NOT:#define __ARM_FEATURE_DSP
+
+// Test whether predefines are as expected when targeting arm10tdmi.
+// RUN: %clang -target armv5 -mcpu=arm10tdmi -x c -E -dM %s -o - | FileCheck --check-prefix=A5T %s
+// A5T-NOT:#define __ARM_FEATURE_DSP
+
 // Test whether predefines are as expected when targeting cortex-a5.
 // RUN: %clang -target armv7 -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck --check-prefix=A5-ARM %s
 // A5-ARM-NOT:#define __ARM_ARCH_EXT_IDIV__
+// A5-ARM:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck --check-prefix=A5-THUMB %s
 // A5-THUMB-NOT:#define __ARM_ARCH_EXT_IDIV__
+// A5-THUMB:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7 -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck --check-prefix=A5 %s
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-a5 -x c -E -dM %s -o - | FileCheck --check-prefix=A5 %s
@@ -157,6 +167,7 @@
 // A5:#define __ARM_ARCH_PROFILE 'A'
 // A5-NOT: #define __ARM_FEATURE_NUMERIC_MAXMIN
 // A5-NOT: #define __ARM_FEATURE_DIRECTED_ROUNDING
+// A5:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-a7.
 // RUN: %clang -target armv7 -mcpu=cortex-a7 -x c -E -dM %s -o - | FileCheck --check-prefix=A7 %s
@@ -165,20 +176,25 @@
 // A7:#define __ARM_ARCH_7A__ 1
 // A7:#define __ARM_ARCH_EXT_IDIV__ 1
 // A7:#define __ARM_ARCH_PROFILE 'A'
+// A7:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-a8.
 // RUN: %clang -target armv7 -mcpu=cortex-a8 -x c -E -dM %s -o - | FileCheck --check-prefix=A8-ARM %s
 // A8-ARM-NOT:#define __ARM_ARCH_EXT_IDIV__
+// A8-ARM:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-a8 -x c -E -dM %s -o - | FileCheck --check-prefix=A8-THUMB %s
 // A8-THUMB-NOT:#define __ARM_ARCH_EXT_IDIV__
+// A8-THUMB:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-a9.
 // RUN: %clang -target armv7 -mcpu=cortex-a9 -x c -E -dM %s -o - | FileCheck --check-prefix=A9-ARM %s
 // A9-ARM-NOT:#define __ARM_ARCH_EXT_IDIV__
+// A9-ARM:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-a9 -x c -E -dM %s -o - | FileCheck --check-prefix=A9-THUMB %s
 // A9-THUMB-NOT:#define __ARM_ARCH_EXT_IDIV__
+// A9-THUMB:#define __ARM_FEATURE_DSP
 
 
 // Check that -mfpu works properly for Cortex-A12 (enabled by default).
@@ -199,13 +215,16 @@
 // A12:#define __ARM_ARCH_7A__ 1
 // A12:#define __ARM_ARCH_EXT_IDIV__ 1
 // A12:#define __ARM_ARCH_PROFILE 'A'
+// A12:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-a15.
 // RUN: %clang -target armv7 -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck --check-prefix=A15-ARM %s
 // A15-ARM:#define __ARM_ARCH_EXT_IDIV__ 1
+// A15-ARM:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-a15 -x c -E -dM %s -o - | FileCheck --check-prefix=A15-THUMB %s
 // A15-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// A15-THUMB:#define __ARM_FEATURE_DSP
 
 // Check that -mfpu works properly for Cortex-A17 (enabled by default).
 // RUN: %clang -target armv7-none-linux-gnueabi -mcpu=cortex-a17 -x c -E -dM %s -o - | FileCheck --check-prefix=DEFAULTFPU-A17 %s
@@ -225,50 +244,75 @@
 // A17:#define __ARM_ARCH_7A__ 1
 // A17:#define __ARM_ARCH_EXT_IDIV__ 1
 // A17:#define __ARM_ARCH_PROFILE 'A'
+// A17:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting swift.
 // RUN: %clang -target armv7s -mcpu=swift -x c -E -dM %s -o - | FileCheck --check-prefix=SWIFT-ARM %s
 // SWIFT-ARM:#define __ARM_ARCH_EXT_IDIV__ 1
+// SWIFT:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7s -mthumb -mcpu=swift -x c -E -dM %s -o - | FileCheck --check-prefix=SWIFT-THUMB %s
 // SWIFT-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// SWIFT-THUMB:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-a53.
 // RUN: %clang -target armv8 -mcpu=cortex-a53 -x c -E -dM %s -o - | FileCheck --check-prefix=A53-ARM %s
 // A53-ARM:#define __ARM_ARCH_EXT_IDIV__ 1
+// A53-ARM:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv8 -mthumb -mcpu=cortex-a53 -x c -E -dM %s -o - | FileCheck --check-prefix=A53-THUMB %s
 // A53-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// A53-THUMB:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-r5.
 // RUN: %clang -target armv7 -mcpu=cortex-r5 -x c -E -dM %s -o - | FileCheck --check-prefix=R5-ARM %s
 // R5-ARM:#define __ARM_ARCH_EXT_IDIV__ 1
+// R5-ARM:#define __ARM_FEATURE_DSP
 
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-r5 -x c -E -dM %s -o - | FileCheck --check-prefix=R5-THUMB %s
 // R5-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// R5-THUMB:#define __ARM_FEATURE_DSP
+
+// Test whether predefines are as expected when targeting cortex-r7.
+// RUN: %clang -target armv7 -mcpu=cortex-r7 -x c -E -dM %s -o - | FileCheck --check-prefix=R7-ARM %s
+// R7-ARM:#define __ARM_ARCH_EXT_IDIV__ 1
+// R7-ARM:#define __ARM_FEATURE_DSP
+
+// RUN: %clang -target armv7 -mthumb -mcpu=cortex-r7 -x c -E -dM %s -o - | FileCheck --check-prefix=R7-THUMB %s
+// R7-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// R7-THUMB:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-m0.
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-m0 -x c -E -dM %s -o - | FileCheck --check-prefix=M0-THUMB %s
+// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m0plus -x c -E -dM %s -o - | FileCheck --check-prefix=M0-THUMB %s
+// RUN: %clang -target armv7 -mthumb -mcpu=cortex-m1 -x c -E -dM %s -o - | FileCheck --check-prefix=M0-THUMB %s
+// RUN: %clang -target armv7 -mthumb -mcpu=sc000 -x c -E -dM %s -o - | FileCheck --check-prefix=M0-THUMB %s
 // M0-THUMB-NOT:#define __ARM_ARCH_EXT_IDIV__
+// M0-THUMB-NOT:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-m3.
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-m3 -x c -E -dM %s -o - | FileCheck --check-prefix=M3-THUMB %s
+// RUN: %clang -target armv7 -mthumb -mcpu=sc300 -x c -E -dM %s -o - | FileCheck --check-prefix=M3-THUMB %s
 // M3-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// M3-THUMB-NOT:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-m4.
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-m4 -x c -E -dM %s -o - | FileCheck --check-prefix=M4-THUMB %s
 // M4-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// M4-THUMB:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting cortex-m7.
 // RUN: %clang -target armv7 -mthumb -mcpu=cortex-m7 -x c -E -dM %s -o - | FileCheck --check-prefix=M7-THUMB %s
 // M7-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// M7-THUMB:#define __ARM_FEATURE_DSP
 
 // Test whether predefines are as expected when targeting krait.
 // RUN: %clang -target armv7 -mcpu=krait -x c -E -dM %s -o - | FileCheck --check-prefix=KRAIT-ARM %s
 // KRAIT-ARM:#define __ARM_ARCH_EXT_IDIV__ 1
+// KRAIT-ARM:#define __ARM_FEATURE_DSP
 // KRAIT-ARM:#define  __ARM_VFPV4__ 1
 
 // RUN: %clang -target armv7 -mthumb -mcpu=krait -x c -E -dM %s -o - | FileCheck --check-prefix=KRAIT-THUMB %s
 // KRAIT-THUMB:#define __ARM_ARCH_EXT_IDIV__ 1
+// KRAIT-THUMB:#define __ARM_FEATURE_DSP
 // KRAIT-THUMB:#define  __ARM_VFPV4__ 1
-
diff --git a/test/Preprocessor/cxx_oper_keyword_ms_compat.cpp b/test/Preprocessor/cxx_oper_keyword_ms_compat.cpp
index 8e1351e..24a3898 100644
--- a/test/Preprocessor/cxx_oper_keyword_ms_compat.cpp
+++ b/test/Preprocessor/cxx_oper_keyword_ms_compat.cpp
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 %s -E -verify -fms-extensions
 // expected-no-diagnostics
 
+#pragma clang diagnostic ignored "-Wkeyword-macro"
+
 bool f() {
   // Check that operators still work before redefining them.
 #if compl 0 bitand 1
diff --git a/test/Preprocessor/feature_tests.c b/test/Preprocessor/feature_tests.c
index 5a2c300..fbde6a6 100644
--- a/test/Preprocessor/feature_tests.c
+++ b/test/Preprocessor/feature_tests.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -triple=i686-apple-darwin9
+// RUN: %clang_cc1 %s -triple=i686-apple-darwin9 -verify -DVERIFY
 // RUN: %clang_cc1 %s -E -triple=i686-apple-darwin9
 #ifndef __has_feature
 #error Should have __has_feature
@@ -53,3 +53,10 @@
 #if !HAS_BUILTIN(MY_ALIAS_BUILTIN) || !HAS_FEATURE(MY_ALIAS_FEATURE)
 #error Expansion should have occurred
 #endif
+
+#ifdef VERIFY
+// expected-error@+2 {{builtin feature check macro requires a parenthesized identifier}}
+// expected-error@+1 {{expected value in expression}}
+#if __has_feature('x')
+#endif
+#endif
diff --git a/test/Preprocessor/has_attribute.c b/test/Preprocessor/has_attribute.c
index 5fe060e..0ef5b48 100644
--- a/test/Preprocessor/has_attribute.c
+++ b/test/Preprocessor/has_attribute.c
@@ -48,3 +48,8 @@
 #if !__has_attribute(dllexport)
   int does_not_have_dllexport();
 #endif
+
+// CHECK: does_not_have_uuid
+#if !__has_attribute(uuid)
+  int does_not_have_uuid
+#endif
diff --git a/test/Preprocessor/has_attribute.cpp b/test/Preprocessor/has_attribute.cpp
index 75f72c7..1ab4502 100644
--- a/test/Preprocessor/has_attribute.cpp
+++ b/test/Preprocessor/has_attribute.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple i386-unknown-unknown -std=c++11 -E %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple i386-unknown-unknown -fms-compatibility -std=c++11 -E %s -o - | FileCheck %s
 
 // CHECK: has_cxx11_carries_dep
 #if __has_cpp_attribute(carries_dependency)
@@ -51,3 +51,18 @@
 #if __has_cpp_attribute(deprecated) == 201309
   int has_cxx14_deprecated_vers();
 #endif
+
+// CHECK: has_declspec_uuid
+#if __has_declspec_attribute(uuid)
+  int has_declspec_uuid();
+#endif
+
+// CHECK: has_declspec_uuid2
+#if __has_declspec_attribute(__uuid__)
+  int has_declspec_uuid2();
+#endif
+
+// CHECK: does_not_have_declspec_fallthrough
+#if !__has_declspec_attribute(fallthrough)
+  int does_not_have_declspec_fallthrough();
+#endif
diff --git a/test/Preprocessor/init.c b/test/Preprocessor/init.c
index 43492f8..e31b3bd 100644
--- a/test/Preprocessor/init.c
+++ b/test/Preprocessor/init.c
@@ -241,6 +241,7 @@
 // AARCH64:#define __ARM_ARCH 8
 // AARCH64:#define __ARM_ARCH_ISA_A64 1
 // AARCH64-NOT:#define __ARM_BIG_ENDIAN 1
+// AARCH64:#define __BIGGEST_ALIGNMENT__ 16
 // AARCH64:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // AARCH64:#define __CHAR16_TYPE__ unsigned short
 // AARCH64:#define __CHAR32_TYPE__ unsigned int
@@ -258,7 +259,7 @@
 // AARCH64:#define __DBL_MIN_10_EXP__ (-307)
 // AARCH64:#define __DBL_MIN_EXP__ (-1021)
 // AARCH64:#define __DBL_MIN__ 2.2250738585072014e-308
-// AARCH64:#define __DECIMAL_DIG__ 36
+// AARCH64:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // AARCH64:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // AARCH64:#define __FLT_DIG__ 6
 // AARCH64:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -431,6 +432,7 @@
 // AARCH64-BE:#define __ARM_ARCH 8
 // AARCH64-BE:#define __ARM_ARCH_ISA_A64 1
 // AARCH64-BE:#define __ARM_BIG_ENDIAN 1
+// AARCH64-BE:#define __BIGGEST_ALIGNMENT__ 16
 // AARCH64-BE:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // AARCH64-BE:#define __CHAR16_TYPE__ unsigned short
 // AARCH64-BE:#define __CHAR32_TYPE__ unsigned int
@@ -448,7 +450,7 @@
 // AARCH64-BE:#define __DBL_MIN_10_EXP__ (-307)
 // AARCH64-BE:#define __DBL_MIN_EXP__ (-1021)
 // AARCH64-BE:#define __DBL_MIN__ 2.2250738585072014e-308
-// AARCH64-BE:#define __DECIMAL_DIG__ 36
+// AARCH64-BE:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // AARCH64-BE:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // AARCH64-BE:#define __FLT_DIG__ 6
 // AARCH64-BE:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -621,6 +623,7 @@
 // AARCH64-NETBSD:#define __ARM_ARCH 8
 // AARCH64-NETBSD:#define __ARM_ARCH_ISA_A64 1
 // AARCH64-NETBSD-NOT:#define __ARM_BIG_ENDIAN 1
+// AARCH64-NETBSD:#define __BIGGEST_ALIGNMENT__ 16
 // AARCH64-NETBSD:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // AARCH64-NETBSD:#define __CHAR16_TYPE__ unsigned short
 // AARCH64-NETBSD:#define __CHAR32_TYPE__ unsigned int
@@ -638,7 +641,7 @@
 // AARCH64-NETBSD:#define __DBL_MIN_10_EXP__ (-307)
 // AARCH64-NETBSD:#define __DBL_MIN_EXP__ (-1021)
 // AARCH64-NETBSD:#define __DBL_MIN__ 2.2250738585072014e-308
-// AARCH64-NETBSD:#define __DECIMAL_DIG__ 36
+// AARCH64-NETBSD:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // AARCH64-NETBSD:#define __ELF__ 1
 // AARCH64-NETBSD:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // AARCH64-NETBSD:#define __FLT_DIG__ 6
@@ -812,6 +815,7 @@
 // AARCH64-FREEBSD:#define __ARM_ARCH 8
 // AARCH64-FREEBSD:#define __ARM_ARCH_ISA_A64 1
 // AARCH64-FREEBSD-NOT:#define __ARM_BIG_ENDIAN 1
+// AARCH64-FREEBSD:#define __BIGGEST_ALIGNMENT__ 16
 // AARCH64-FREEBSD:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // AARCH64-FREEBSD:#define __CHAR16_TYPE__ unsigned short
 // AARCH64-FREEBSD:#define __CHAR32_TYPE__ unsigned int
@@ -829,7 +833,7 @@
 // AARCH64-FREEBSD:#define __DBL_MIN_10_EXP__ (-307)
 // AARCH64-FREEBSD:#define __DBL_MIN_EXP__ (-1021)
 // AARCH64-FREEBSD:#define __DBL_MIN__ 2.2250738585072014e-308
-// AARCH64-FREEBSD:#define __DECIMAL_DIG__ 36
+// AARCH64-FREEBSD:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // AARCH64-FREEBSD:#define __ELF__ 1
 // AARCH64-FREEBSD:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // AARCH64-FREEBSD:#define __FLT_DIG__ 6
@@ -995,6 +999,197 @@
 // AARCH64-FREEBSD:#define __WINT_WIDTH__ 32
 // AARCH64-FREEBSD:#define __aarch64__ 1
 
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=aarch64-apple-ios7.0 < /dev/null | FileCheck -check-prefix AARCH64-DARWIN %s
+//
+// AARCH64-DARWIN: #define _LP64 1
+// AARCH64-NOT: #define __AARCH64EB__ 1
+// AARCH64-DARWIN: #define __AARCH64EL__ 1
+// AARCH64-NOT: #define __AARCH_BIG_ENDIAN 1
+// AARCH64-DARWIN: #define __ARM_64BIT_STATE 1
+// AARCH64-DARWIN: #define __ARM_ARCH 8
+// AARCH64-DARWIN: #define __ARM_ARCH_ISA_A64 1
+// AARCH64-NOT: #define __ARM_BIG_ENDIAN 1
+// AARCH64-DARWIN: #define __BIGGEST_ALIGNMENT__ 8
+// AARCH64-DARWIN: #define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
+// AARCH64-DARWIN: #define __CHAR16_TYPE__ unsigned short
+// AARCH64-DARWIN: #define __CHAR32_TYPE__ unsigned int
+// AARCH64-DARWIN: #define __CHAR_BIT__ 8
+// AARCH64-DARWIN: #define __DBL_DENORM_MIN__ 4.9406564584124654e-324
+// AARCH64-DARWIN: #define __DBL_DIG__ 15
+// AARCH64-DARWIN: #define __DBL_EPSILON__ 2.2204460492503131e-16
+// AARCH64-DARWIN: #define __DBL_HAS_DENORM__ 1
+// AARCH64-DARWIN: #define __DBL_HAS_INFINITY__ 1
+// AARCH64-DARWIN: #define __DBL_HAS_QUIET_NAN__ 1
+// AARCH64-DARWIN: #define __DBL_MANT_DIG__ 53
+// AARCH64-DARWIN: #define __DBL_MAX_10_EXP__ 308
+// AARCH64-DARWIN: #define __DBL_MAX_EXP__ 1024
+// AARCH64-DARWIN: #define __DBL_MAX__ 1.7976931348623157e+308
+// AARCH64-DARWIN: #define __DBL_MIN_10_EXP__ (-307)
+// AARCH64-DARWIN: #define __DBL_MIN_EXP__ (-1021)
+// AARCH64-DARWIN: #define __DBL_MIN__ 2.2250738585072014e-308
+// AARCH64-DARWIN: #define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
+// AARCH64-DARWIN: #define __FLT_DENORM_MIN__ 1.40129846e-45F
+// AARCH64-DARWIN: #define __FLT_DIG__ 6
+// AARCH64-DARWIN: #define __FLT_EPSILON__ 1.19209290e-7F
+// AARCH64-DARWIN: #define __FLT_EVAL_METHOD__ 0
+// AARCH64-DARWIN: #define __FLT_HAS_DENORM__ 1
+// AARCH64-DARWIN: #define __FLT_HAS_INFINITY__ 1
+// AARCH64-DARWIN: #define __FLT_HAS_QUIET_NAN__ 1
+// AARCH64-DARWIN: #define __FLT_MANT_DIG__ 24
+// AARCH64-DARWIN: #define __FLT_MAX_10_EXP__ 38
+// AARCH64-DARWIN: #define __FLT_MAX_EXP__ 128
+// AARCH64-DARWIN: #define __FLT_MAX__ 3.40282347e+38F
+// AARCH64-DARWIN: #define __FLT_MIN_10_EXP__ (-37)
+// AARCH64-DARWIN: #define __FLT_MIN_EXP__ (-125)
+// AARCH64-DARWIN: #define __FLT_MIN__ 1.17549435e-38F
+// AARCH64-DARWIN: #define __FLT_RADIX__ 2
+// AARCH64-DARWIN: #define __INT16_C_SUFFIX__ {{$}}
+// AARCH64-DARWIN: #define __INT16_FMTd__ "hd"
+// AARCH64-DARWIN: #define __INT16_FMTi__ "hi"
+// AARCH64-DARWIN: #define __INT16_MAX__ 32767
+// AARCH64-DARWIN: #define __INT16_TYPE__ short
+// AARCH64-DARWIN: #define __INT32_C_SUFFIX__ {{$}}
+// AARCH64-DARWIN: #define __INT32_FMTd__ "d"
+// AARCH64-DARWIN: #define __INT32_FMTi__ "i"
+// AARCH64-DARWIN: #define __INT32_MAX__ 2147483647
+// AARCH64-DARWIN: #define __INT32_TYPE__ int
+// AARCH64-DARWIN: #define __INT64_C_SUFFIX__ L
+// AARCH64-DARWIN: #define __INT64_FMTd__ "lld"
+// AARCH64-DARWIN: #define __INT64_FMTi__ "lli"
+// AARCH64-DARWIN: #define __INT64_MAX__ 9223372036854775807L
+// AARCH64-DARWIN: #define __INT64_TYPE__ long long int
+// AARCH64-DARWIN: #define __INT8_C_SUFFIX__ {{$}}
+// AARCH64-DARWIN: #define __INT8_FMTd__ "hhd"
+// AARCH64-DARWIN: #define __INT8_FMTi__ "hhi"
+// AARCH64-DARWIN: #define __INT8_MAX__ 127
+// AARCH64-DARWIN: #define __INT8_TYPE__ signed char
+// AARCH64-DARWIN: #define __INTMAX_C_SUFFIX__ L
+// AARCH64-DARWIN: #define __INTMAX_FMTd__ "ld"
+// AARCH64-DARWIN: #define __INTMAX_FMTi__ "li"
+// AARCH64-DARWIN: #define __INTMAX_MAX__ 9223372036854775807L
+// AARCH64-DARWIN: #define __INTMAX_TYPE__ long int
+// AARCH64-DARWIN: #define __INTMAX_WIDTH__ 64
+// AARCH64-DARWIN: #define __INTPTR_FMTd__ "ld"
+// AARCH64-DARWIN: #define __INTPTR_FMTi__ "li"
+// AARCH64-DARWIN: #define __INTPTR_MAX__ 9223372036854775807L
+// AARCH64-DARWIN: #define __INTPTR_TYPE__ long int
+// AARCH64-DARWIN: #define __INTPTR_WIDTH__ 64
+// AARCH64-DARWIN: #define __INT_FAST16_FMTd__ "hd"
+// AARCH64-DARWIN: #define __INT_FAST16_FMTi__ "hi"
+// AARCH64-DARWIN: #define __INT_FAST16_MAX__ 32767
+// AARCH64-DARWIN: #define __INT_FAST16_TYPE__ short
+// AARCH64-DARWIN: #define __INT_FAST32_FMTd__ "d"
+// AARCH64-DARWIN: #define __INT_FAST32_FMTi__ "i"
+// AARCH64-DARWIN: #define __INT_FAST32_MAX__ 2147483647
+// AARCH64-DARWIN: #define __INT_FAST32_TYPE__ int
+// AARCH64-DARWIN: #define __INT_FAST64_FMTd__ "ld"
+// AARCH64-DARWIN: #define __INT_FAST64_FMTi__ "li"
+// AARCH64-DARWIN: #define __INT_FAST64_MAX__ 9223372036854775807L
+// AARCH64-DARWIN: #define __INT_FAST64_TYPE__ long int
+// AARCH64-DARWIN: #define __INT_FAST8_FMTd__ "hhd"
+// AARCH64-DARWIN: #define __INT_FAST8_FMTi__ "hhi"
+// AARCH64-DARWIN: #define __INT_FAST8_MAX__ 127
+// AARCH64-DARWIN: #define __INT_FAST8_TYPE__ signed char
+// AARCH64-DARWIN: #define __INT_LEAST16_FMTd__ "hd"
+// AARCH64-DARWIN: #define __INT_LEAST16_FMTi__ "hi"
+// AARCH64-DARWIN: #define __INT_LEAST16_MAX__ 32767
+// AARCH64-DARWIN: #define __INT_LEAST16_TYPE__ short
+// AARCH64-DARWIN: #define __INT_LEAST32_FMTd__ "d"
+// AARCH64-DARWIN: #define __INT_LEAST32_FMTi__ "i"
+// AARCH64-DARWIN: #define __INT_LEAST32_MAX__ 2147483647
+// AARCH64-DARWIN: #define __INT_LEAST32_TYPE__ int
+// AARCH64-DARWIN: #define __INT_LEAST64_FMTd__ "ld"
+// AARCH64-DARWIN: #define __INT_LEAST64_FMTi__ "li"
+// AARCH64-DARWIN: #define __INT_LEAST64_MAX__ 9223372036854775807L
+// AARCH64-DARWIN: #define __INT_LEAST64_TYPE__ long int
+// AARCH64-DARWIN: #define __INT_LEAST8_FMTd__ "hhd"
+// AARCH64-DARWIN: #define __INT_LEAST8_FMTi__ "hhi"
+// AARCH64-DARWIN: #define __INT_LEAST8_MAX__ 127
+// AARCH64-DARWIN: #define __INT_LEAST8_TYPE__ signed char
+// AARCH64-DARWIN: #define __INT_MAX__ 2147483647
+// AARCH64-DARWIN: #define __LDBL_DENORM_MIN__ 4.9406564584124654e-324L
+// AARCH64-DARWIN: #define __LDBL_DIG__ 15
+// AARCH64-DARWIN: #define __LDBL_EPSILON__ 2.2204460492503131e-16L
+// AARCH64-DARWIN: #define __LDBL_HAS_DENORM__ 1
+// AARCH64-DARWIN: #define __LDBL_HAS_INFINITY__ 1
+// AARCH64-DARWIN: #define __LDBL_HAS_QUIET_NAN__ 1
+// AARCH64-DARWIN: #define __LDBL_MANT_DIG__ 53
+// AARCH64-DARWIN: #define __LDBL_MAX_10_EXP__ 308
+// AARCH64-DARWIN: #define __LDBL_MAX_EXP__ 1024
+// AARCH64-DARWIN: #define __LDBL_MAX__ 1.7976931348623157e+308L
+// AARCH64-DARWIN: #define __LDBL_MIN_10_EXP__ (-307)
+// AARCH64-DARWIN: #define __LDBL_MIN_EXP__ (-1021)
+// AARCH64-DARWIN: #define __LDBL_MIN__ 2.2250738585072014e-308L
+// AARCH64-DARWIN: #define __LONG_LONG_MAX__ 9223372036854775807LL
+// AARCH64-DARWIN: #define __LONG_MAX__ 9223372036854775807L
+// AARCH64-DARWIN: #define __LP64__ 1
+// AARCH64-DARWIN: #define __POINTER_WIDTH__ 64
+// AARCH64-DARWIN: #define __PTRDIFF_TYPE__ long int
+// AARCH64-DARWIN: #define __PTRDIFF_WIDTH__ 64
+// AARCH64-DARWIN: #define __SCHAR_MAX__ 127
+// AARCH64-DARWIN: #define __SHRT_MAX__ 32767
+// AARCH64-DARWIN: #define __SIG_ATOMIC_MAX__ 2147483647
+// AARCH64-DARWIN: #define __SIG_ATOMIC_WIDTH__ 32
+// AARCH64-DARWIN: #define __SIZEOF_DOUBLE__ 8
+// AARCH64-DARWIN: #define __SIZEOF_FLOAT__ 4
+// AARCH64-DARWIN: #define __SIZEOF_INT128__ 16
+// AARCH64-DARWIN: #define __SIZEOF_INT__ 4
+// AARCH64-DARWIN: #define __SIZEOF_LONG_DOUBLE__ 8
+// AARCH64-DARWIN: #define __SIZEOF_LONG_LONG__ 8
+// AARCH64-DARWIN: #define __SIZEOF_LONG__ 8
+// AARCH64-DARWIN: #define __SIZEOF_POINTER__ 8
+// AARCH64-DARWIN: #define __SIZEOF_PTRDIFF_T__ 8
+// AARCH64-DARWIN: #define __SIZEOF_SHORT__ 2
+// AARCH64-DARWIN: #define __SIZEOF_SIZE_T__ 8
+// AARCH64-DARWIN: #define __SIZEOF_WCHAR_T__ 4
+// AARCH64-DARWIN: #define __SIZEOF_WINT_T__ 4
+// AARCH64-DARWIN: #define __SIZE_MAX__ 18446744073709551615UL
+// AARCH64-DARWIN: #define __SIZE_TYPE__ long unsigned int
+// AARCH64-DARWIN: #define __SIZE_WIDTH__ 64
+// AARCH64-DARWIN: #define __UINT16_C_SUFFIX__ {{$}}
+// AARCH64-DARWIN: #define __UINT16_MAX__ 65535
+// AARCH64-DARWIN: #define __UINT16_TYPE__ unsigned short
+// AARCH64-DARWIN: #define __UINT32_C_SUFFIX__ U
+// AARCH64-DARWIN: #define __UINT32_MAX__ 4294967295U
+// AARCH64-DARWIN: #define __UINT32_TYPE__ unsigned int
+// AARCH64-DARWIN: #define __UINT64_C_SUFFIX__ UL
+// AARCH64-DARWIN: #define __UINT64_MAX__ 18446744073709551615UL
+// AARCH64-DARWIN: #define __UINT64_TYPE__ long long unsigned int
+// AARCH64-DARWIN: #define __UINT8_C_SUFFIX__ {{$}}
+// AARCH64-DARWIN: #define __UINT8_MAX__ 255
+// AARCH64-DARWIN: #define __UINT8_TYPE__ unsigned char
+// AARCH64-DARWIN: #define __UINTMAX_C_SUFFIX__ UL
+// AARCH64-DARWIN: #define __UINTMAX_MAX__ 18446744073709551615UL
+// AARCH64-DARWIN: #define __UINTMAX_TYPE__ long unsigned int
+// AARCH64-DARWIN: #define __UINTMAX_WIDTH__ 64
+// AARCH64-DARWIN: #define __UINTPTR_MAX__ 18446744073709551615UL
+// AARCH64-DARWIN: #define __UINTPTR_TYPE__ long unsigned int
+// AARCH64-DARWIN: #define __UINTPTR_WIDTH__ 64
+// AARCH64-DARWIN: #define __UINT_FAST16_MAX__ 65535
+// AARCH64-DARWIN: #define __UINT_FAST16_TYPE__ unsigned short
+// AARCH64-DARWIN: #define __UINT_FAST32_MAX__ 4294967295U
+// AARCH64-DARWIN: #define __UINT_FAST32_TYPE__ unsigned int
+// AARCH64-DARWIN: #define __UINT_FAST64_MAX__ 18446744073709551615UL
+// AARCH64-DARWIN: #define __UINT_FAST64_TYPE__ long unsigned int
+// AARCH64-DARWIN: #define __UINT_FAST8_MAX__ 255
+// AARCH64-DARWIN: #define __UINT_FAST8_TYPE__ unsigned char
+// AARCH64-DARWIN: #define __UINT_LEAST16_MAX__ 65535
+// AARCH64-DARWIN: #define __UINT_LEAST16_TYPE__ unsigned short
+// AARCH64-DARWIN: #define __UINT_LEAST32_MAX__ 4294967295U
+// AARCH64-DARWIN: #define __UINT_LEAST32_TYPE__ unsigned int
+// AARCH64-DARWIN: #define __UINT_LEAST64_MAX__ 18446744073709551615UL
+// AARCH64-DARWIN: #define __UINT_LEAST64_TYPE__ long unsigned int
+// AARCH64-DARWIN: #define __UINT_LEAST8_MAX__ 255
+// AARCH64-DARWIN: #define __UINT_LEAST8_TYPE__ unsigned char
+// AARCH64-DARWIN: #define __USER_LABEL_PREFIX__ _
+// AARCH64-DARWIN: #define __WCHAR_MAX__ 2147483647
+// AARCH64-DARWIN: #define __WCHAR_TYPE__ int
+// AARCH64-DARWIN-NOT: #define __WCHAR_UNSIGNED__
+// AARCH64-DARWIN: #define __WCHAR_WIDTH__ 32
+// AARCH64-DARWIN: #define __WINT_TYPE__ int
+// AARCH64-DARWIN: #define __WINT_WIDTH__ 32
+// AARCH64-DARWIN: #define __aarch64__ 1
+
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=arm-none-none < /dev/null | FileCheck -check-prefix ARM %s
 //
 // ARM-NOT:#define _LP64
@@ -1003,6 +1198,7 @@
 // ARM:#define __ARMEL__ 1
 // ARM:#define __ARM_ARCH_6J__ 1
 // ARM-NOT:#define __ARM_BIG_ENDIAN 1
+// ARM:#define __BIGGEST_ALIGNMENT__ 8
 // ARM:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // ARM:#define __CHAR16_TYPE__ unsigned short
 // ARM:#define __CHAR32_TYPE__ unsigned int
@@ -1020,7 +1216,7 @@
 // ARM:#define __DBL_MIN_10_EXP__ (-307)
 // ARM:#define __DBL_MIN_EXP__ (-1021)
 // ARM:#define __DBL_MIN__ 2.2250738585072014e-308
-// ARM:#define __DECIMAL_DIG__ 17
+// ARM:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // ARM:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // ARM:#define __FLT_DIG__ 6
 // ARM:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -1193,6 +1389,7 @@
 // ARM-BE-NOT:#define __ARMEL__ 1
 // ARM-BE:#define __ARM_ARCH_6J__ 1
 // ARM-BE:#define __ARM_BIG_ENDIAN 1
+// ARM-BE:#define __BIGGEST_ALIGNMENT__ 8
 // ARM-BE:#define __BIG_ENDIAN__ 1
 // ARM-BE:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // ARM-BE:#define __CHAR16_TYPE__ unsigned short
@@ -1211,7 +1408,7 @@
 // ARM-BE:#define __DBL_MIN_10_EXP__ (-307)
 // ARM-BE:#define __DBL_MIN_EXP__ (-1021)
 // ARM-BE:#define __DBL_MIN__ 2.2250738585072014e-308
-// ARM-BE:#define __DECIMAL_DIG__ 17
+// ARM-BE:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // ARM-BE:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // ARM-BE:#define __FLT_DIG__ 6
 // ARM-BE:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -1387,6 +1584,7 @@
 // ARMEABISOFTFP:#define __ARM_EABI__ 1
 // ARMEABISOFTFP:#define __ARM_PCS 1
 // ARMEABISOFTFP-NOT:#define __ARM_PCS_VFP 1
+// ARMEABISOFTFP:#define __BIGGEST_ALIGNMENT__ 8
 // ARMEABISOFTFP:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // ARMEABISOFTFP:#define __CHAR16_TYPE__ unsigned short
 // ARMEABISOFTFP:#define __CHAR32_TYPE__ unsigned int
@@ -1404,7 +1602,7 @@
 // ARMEABISOFTFP:#define __DBL_MIN_10_EXP__ (-307)
 // ARMEABISOFTFP:#define __DBL_MIN_EXP__ (-1021)
 // ARMEABISOFTFP:#define __DBL_MIN__ 2.2250738585072014e-308
-// ARMEABISOFTFP:#define __DECIMAL_DIG__ 17
+// ARMEABISOFTFP:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // ARMEABISOFTFP:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // ARMEABISOFTFP:#define __FLT_DIG__ 6
 // ARMEABISOFTFP:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -1582,6 +1780,7 @@
 // ARMEABIHARDFP:#define __ARM_EABI__ 1
 // ARMEABIHARDFP:#define __ARM_PCS 1
 // ARMEABIHARDFP:#define __ARM_PCS_VFP 1
+// ARMEABIHARDFP:#define __BIGGEST_ALIGNMENT__ 8
 // ARMEABIHARDFP:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // ARMEABIHARDFP:#define __CHAR16_TYPE__ unsigned short
 // ARMEABIHARDFP:#define __CHAR32_TYPE__ unsigned int
@@ -1599,7 +1798,7 @@
 // ARMEABIHARDFP:#define __DBL_MIN_10_EXP__ (-307)
 // ARMEABIHARDFP:#define __DBL_MIN_EXP__ (-1021)
 // ARMEABIHARDFP:#define __DBL_MIN__ 2.2250738585072014e-308
-// ARMEABIHARDFP:#define __DECIMAL_DIG__ 17
+// ARMEABIHARDFP:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // ARMEABIHARDFP:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // ARMEABIHARDFP:#define __FLT_DIG__ 6
 // ARMEABIHARDFP:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -1775,6 +1974,7 @@
 // ARM-NETBSD:#define __ARM_DWARF_EH__ 1
 // ARM-NETBSD:#define __ARM_EABI__ 1
 // ARM-NETBSD-NOT:#define __ARM_BIG_ENDIAN 1
+// ARM-NETBSD:#define __BIGGEST_ALIGNMENT__ 8
 // ARM-NETBSD:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // ARM-NETBSD:#define __CHAR16_TYPE__ unsigned short
 // ARM-NETBSD:#define __CHAR32_TYPE__ unsigned int
@@ -1792,7 +1992,7 @@
 // ARM-NETBSD:#define __DBL_MIN_10_EXP__ (-307)
 // ARM-NETBSD:#define __DBL_MIN_EXP__ (-1021)
 // ARM-NETBSD:#define __DBL_MIN__ 2.2250738585072014e-308
-// ARM-NETBSD:#define __DECIMAL_DIG__ 17
+// ARM-NETBSD:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // ARM-NETBSD:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // ARM-NETBSD:#define __FLT_DIG__ 6
 // ARM-NETBSD:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -2021,6 +2221,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=i386-none-none < /dev/null | FileCheck -check-prefix I386 %s
 //
 // I386-NOT:#define _LP64
+// I386:#define __BIGGEST_ALIGNMENT__ 16
 // I386:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // I386:#define __CHAR16_TYPE__ unsigned short
 // I386:#define __CHAR32_TYPE__ unsigned int
@@ -2038,7 +2239,7 @@
 // I386:#define __DBL_MIN_10_EXP__ (-307)
 // I386:#define __DBL_MIN_EXP__ (-1021)
 // I386:#define __DBL_MIN__ 2.2250738585072014e-308
-// I386:#define __DECIMAL_DIG__ 21
+// I386:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // I386:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // I386:#define __FLT_DIG__ 6
 // I386:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -2207,6 +2408,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=i386-pc-linux-gnu -target-cpu pentium4 < /dev/null | FileCheck -check-prefix I386-LINUX %s
 //
 // I386-LINUX-NOT:#define _LP64
+// I386-LINUX:#define __BIGGEST_ALIGNMENT__ 16
 // I386-LINUX:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // I386-LINUX:#define __CHAR16_TYPE__ unsigned short
 // I386-LINUX:#define __CHAR32_TYPE__ unsigned int
@@ -2224,7 +2426,7 @@
 // I386-LINUX:#define __DBL_MIN_10_EXP__ (-307)
 // I386-LINUX:#define __DBL_MIN_EXP__ (-1021)
 // I386-LINUX:#define __DBL_MIN__ 2.2250738585072014e-308
-// I386-LINUX:#define __DECIMAL_DIG__ 21
+// I386-LINUX:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // I386-LINUX:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // I386-LINUX:#define __FLT_DIG__ 6
 // I386-LINUX:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -2393,6 +2595,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=i386-netbsd < /dev/null | FileCheck -check-prefix I386-NETBSD %s
 //
 // I386-NETBSD-NOT:#define _LP64
+// I386-NETBSD:#define __BIGGEST_ALIGNMENT__ 16
 // I386-NETBSD:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // I386-NETBSD:#define __CHAR16_TYPE__ unsigned short
 // I386-NETBSD:#define __CHAR32_TYPE__ unsigned int
@@ -2410,7 +2613,7 @@
 // I386-NETBSD:#define __DBL_MIN_10_EXP__ (-307)
 // I386-NETBSD:#define __DBL_MIN_EXP__ (-1021)
 // I386-NETBSD:#define __DBL_MIN__ 2.2250738585072014e-308
-// I386-NETBSD:#define __DECIMAL_DIG__ 21
+// I386-NETBSD:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // I386-NETBSD:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // I386-NETBSD:#define __FLT_DIG__ 6
 // I386-NETBSD:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -2597,6 +2800,7 @@
 // MIPS32BE:#define _MIPS_SZINT 32
 // MIPS32BE:#define _MIPS_SZLONG 32
 // MIPS32BE:#define _MIPS_SZPTR 32
+// MIPS32BE:#define __BIGGEST_ALIGNMENT__ 8
 // MIPS32BE:#define __BIG_ENDIAN__ 1
 // MIPS32BE:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // MIPS32BE:#define __CHAR16_TYPE__ unsigned short
@@ -2616,7 +2820,7 @@
 // MIPS32BE:#define __DBL_MIN_10_EXP__ (-307)
 // MIPS32BE:#define __DBL_MIN_EXP__ (-1021)
 // MIPS32BE:#define __DBL_MIN__ 2.2250738585072014e-308
-// MIPS32BE:#define __DECIMAL_DIG__ 17
+// MIPS32BE:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // MIPS32BE:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // MIPS32BE:#define __FLT_DIG__ 6
 // MIPS32BE:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -2805,6 +3009,7 @@
 // MIPS32EL:#define _MIPS_SZINT 32
 // MIPS32EL:#define _MIPS_SZLONG 32
 // MIPS32EL:#define _MIPS_SZPTR 32
+// MIPS32EL:#define __BIGGEST_ALIGNMENT__ 8
 // MIPS32EL:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // MIPS32EL:#define __CHAR16_TYPE__ unsigned short
 // MIPS32EL:#define __CHAR32_TYPE__ unsigned int
@@ -2823,7 +3028,7 @@
 // MIPS32EL:#define __DBL_MIN_10_EXP__ (-307)
 // MIPS32EL:#define __DBL_MIN_EXP__ (-1021)
 // MIPS32EL:#define __DBL_MIN__ 2.2250738585072014e-308
-// MIPS32EL:#define __DECIMAL_DIG__ 17
+// MIPS32EL:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // MIPS32EL:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // MIPS32EL:#define __FLT_DIG__ 6
 // MIPS32EL:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -2997,6 +3202,620 @@
 // MIPS32EL:#define _mips 1
 // MIPS32EL:#define mips 1
 //
+// RUN: %clang_cc1 -E -dM -ffreestanding \
+// RUN:            -triple=mips64-none-none -target-abi n32 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPSN32BE %s
+//
+// MIPSN32BE: #define MIPSEB 1
+// MIPSN32BE: #define _ABIN32 2
+// MIPSN32BE: #define _ILP32 1
+// MIPSN32BE: #define _MIPSEB 1
+// MIPSN32BE: #define _MIPS_ARCH "mips64r2"
+// MIPSN32BE: #define _MIPS_ARCH_MIPS64R2 1
+// MIPSN32BE: #define _MIPS_FPSET 32
+// MIPSN32BE: #define _MIPS_ISA _MIPS_ISA_MIPS64
+// MIPSN32BE: #define _MIPS_SIM _ABIN32
+// MIPSN32BE: #define _MIPS_SZINT 32
+// MIPSN32BE: #define _MIPS_SZLONG 32
+// MIPSN32BE: #define _MIPS_SZPTR 32
+// MIPSN32BE: #define __ATOMIC_ACQUIRE 2
+// MIPSN32BE: #define __ATOMIC_ACQ_REL 4
+// MIPSN32BE: #define __ATOMIC_CONSUME 1
+// MIPSN32BE: #define __ATOMIC_RELAXED 0
+// MIPSN32BE: #define __ATOMIC_RELEASE 3
+// MIPSN32BE: #define __ATOMIC_SEQ_CST 5
+// MIPSN32BE: #define __BIG_ENDIAN__ 1
+// MIPSN32BE: #define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
+// MIPSN32BE: #define __CHAR16_TYPE__ unsigned short
+// MIPSN32BE: #define __CHAR32_TYPE__ unsigned int
+// MIPSN32BE: #define __CHAR_BIT__ 8
+// MIPSN32BE: #define __CONSTANT_CFSTRINGS__ 1
+// MIPSN32BE: #define __DBL_DENORM_MIN__ 4.9406564584124654e-324
+// MIPSN32BE: #define __DBL_DIG__ 15
+// MIPSN32BE: #define __DBL_EPSILON__ 2.2204460492503131e-16
+// MIPSN32BE: #define __DBL_HAS_DENORM__ 1
+// MIPSN32BE: #define __DBL_HAS_INFINITY__ 1
+// MIPSN32BE: #define __DBL_HAS_QUIET_NAN__ 1
+// MIPSN32BE: #define __DBL_MANT_DIG__ 53
+// MIPSN32BE: #define __DBL_MAX_10_EXP__ 308
+// MIPSN32BE: #define __DBL_MAX_EXP__ 1024
+// MIPSN32BE: #define __DBL_MAX__ 1.7976931348623157e+308
+// MIPSN32BE: #define __DBL_MIN_10_EXP__ (-307)
+// MIPSN32BE: #define __DBL_MIN_EXP__ (-1021)
+// MIPSN32BE: #define __DBL_MIN__ 2.2250738585072014e-308
+// MIPSN32BE: #define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
+// MIPSN32BE: #define __FINITE_MATH_ONLY__ 0
+// MIPSN32BE: #define __FLT_DENORM_MIN__ 1.40129846e-45F
+// MIPSN32BE: #define __FLT_DIG__ 6
+// MIPSN32BE: #define __FLT_EPSILON__ 1.19209290e-7F
+// MIPSN32BE: #define __FLT_EVAL_METHOD__ 0
+// MIPSN32BE: #define __FLT_HAS_DENORM__ 1
+// MIPSN32BE: #define __FLT_HAS_INFINITY__ 1
+// MIPSN32BE: #define __FLT_HAS_QUIET_NAN__ 1
+// MIPSN32BE: #define __FLT_MANT_DIG__ 24
+// MIPSN32BE: #define __FLT_MAX_10_EXP__ 38
+// MIPSN32BE: #define __FLT_MAX_EXP__ 128
+// MIPSN32BE: #define __FLT_MAX__ 3.40282347e+38F
+// MIPSN32BE: #define __FLT_MIN_10_EXP__ (-37)
+// MIPSN32BE: #define __FLT_MIN_EXP__ (-125)
+// MIPSN32BE: #define __FLT_MIN__ 1.17549435e-38F
+// MIPSN32BE: #define __FLT_RADIX__ 2
+// MIPSN32BE: #define __GCC_ATOMIC_BOOL_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_CHAR_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_INT_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_LLONG_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_LONG_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_POINTER_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_SHORT_LOCK_FREE 2
+// MIPSN32BE: #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
+// MIPSN32BE: #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
+// MIPSN32BE: #define __GNUC_MINOR__ 2
+// MIPSN32BE: #define __GNUC_PATCHLEVEL__ 1
+// MIPSN32BE: #define __GNUC_STDC_INLINE__ 1
+// MIPSN32BE: #define __GNUC__ 4
+// MIPSN32BE: #define __GXX_ABI_VERSION 1002
+// MIPSN32BE: #define __GXX_RTTI 1
+// MIPSN32BE: #define __ILP32__ 1
+// MIPSN32BE: #define __INT16_C_SUFFIX__
+// MIPSN32BE: #define __INT16_FMTd__ "hd"
+// MIPSN32BE: #define __INT16_FMTi__ "hi"
+// MIPSN32BE: #define __INT16_MAX__ 32767
+// MIPSN32BE: #define __INT16_TYPE__ short
+// MIPSN32BE: #define __INT32_C_SUFFIX__
+// MIPSN32BE: #define __INT32_FMTd__ "d"
+// MIPSN32BE: #define __INT32_FMTi__ "i"
+// MIPSN32BE: #define __INT32_MAX__ 2147483647
+// MIPSN32BE: #define __INT32_TYPE__ int
+// MIPSN32BE: #define __INT64_C_SUFFIX__ LL
+// MIPSN32BE: #define __INT64_FMTd__ "lld"
+// MIPSN32BE: #define __INT64_FMTi__ "lli"
+// MIPSN32BE: #define __INT64_MAX__ 9223372036854775807LL
+// MIPSN32BE: #define __INT64_TYPE__ long long int
+// MIPSN32BE: #define __INT8_C_SUFFIX__
+// MIPSN32BE: #define __INT8_FMTd__ "hhd"
+// MIPSN32BE: #define __INT8_FMTi__ "hhi"
+// MIPSN32BE: #define __INT8_MAX__ 127
+// MIPSN32BE: #define __INT8_TYPE__ signed char
+// MIPSN32BE: #define __INTMAX_C_SUFFIX__ LL
+// MIPSN32BE: #define __INTMAX_FMTd__ "lld"
+// MIPSN32BE: #define __INTMAX_FMTi__ "lli"
+// MIPSN32BE: #define __INTMAX_MAX__ 9223372036854775807LL
+// MIPSN32BE: #define __INTMAX_TYPE__ long long int
+// MIPSN32BE: #define __INTMAX_WIDTH__ 64
+// MIPSN32BE: #define __INTPTR_FMTd__ "ld"
+// MIPSN32BE: #define __INTPTR_FMTi__ "li"
+// MIPSN32BE: #define __INTPTR_MAX__ 2147483647L
+// MIPSN32BE: #define __INTPTR_TYPE__ long int
+// MIPSN32BE: #define __INTPTR_WIDTH__ 32
+// MIPSN32BE: #define __INT_FAST16_FMTd__ "hd"
+// MIPSN32BE: #define __INT_FAST16_FMTi__ "hi"
+// MIPSN32BE: #define __INT_FAST16_MAX__ 32767
+// MIPSN32BE: #define __INT_FAST16_TYPE__ short
+// MIPSN32BE: #define __INT_FAST32_FMTd__ "d"
+// MIPSN32BE: #define __INT_FAST32_FMTi__ "i"
+// MIPSN32BE: #define __INT_FAST32_MAX__ 2147483647
+// MIPSN32BE: #define __INT_FAST32_TYPE__ int
+// MIPSN32BE: #define __INT_FAST64_FMTd__ "lld"
+// MIPSN32BE: #define __INT_FAST64_FMTi__ "lli"
+// MIPSN32BE: #define __INT_FAST64_MAX__ 9223372036854775807LL
+// MIPSN32BE: #define __INT_FAST64_TYPE__ long long int
+// MIPSN32BE: #define __INT_FAST8_FMTd__ "hhd"
+// MIPSN32BE: #define __INT_FAST8_FMTi__ "hhi"
+// MIPSN32BE: #define __INT_FAST8_MAX__ 127
+// MIPSN32BE: #define __INT_FAST8_TYPE__ signed char
+// MIPSN32BE: #define __INT_LEAST16_FMTd__ "hd"
+// MIPSN32BE: #define __INT_LEAST16_FMTi__ "hi"
+// MIPSN32BE: #define __INT_LEAST16_MAX__ 32767
+// MIPSN32BE: #define __INT_LEAST16_TYPE__ short
+// MIPSN32BE: #define __INT_LEAST32_FMTd__ "d"
+// MIPSN32BE: #define __INT_LEAST32_FMTi__ "i"
+// MIPSN32BE: #define __INT_LEAST32_MAX__ 2147483647
+// MIPSN32BE: #define __INT_LEAST32_TYPE__ int
+// MIPSN32BE: #define __INT_LEAST64_FMTd__ "lld"
+// MIPSN32BE: #define __INT_LEAST64_FMTi__ "lli"
+// MIPSN32BE: #define __INT_LEAST64_MAX__ 9223372036854775807LL
+// MIPSN32BE: #define __INT_LEAST64_TYPE__ long long int
+// MIPSN32BE: #define __INT_LEAST8_FMTd__ "hhd"
+// MIPSN32BE: #define __INT_LEAST8_FMTi__ "hhi"
+// MIPSN32BE: #define __INT_LEAST8_MAX__ 127
+// MIPSN32BE: #define __INT_LEAST8_TYPE__ signed char
+// MIPSN32BE: #define __INT_MAX__ 2147483647
+// MIPSN32BE: #define __LDBL_DENORM_MIN__ 6.47517511943802511092443895822764655e-4966L
+// MIPSN32BE: #define __LDBL_DIG__ 33
+// MIPSN32BE: #define __LDBL_EPSILON__ 1.92592994438723585305597794258492732e-34L
+// MIPSN32BE: #define __LDBL_HAS_DENORM__ 1
+// MIPSN32BE: #define __LDBL_HAS_INFINITY__ 1
+// MIPSN32BE: #define __LDBL_HAS_QUIET_NAN__ 1
+// MIPSN32BE: #define __LDBL_MANT_DIG__ 113
+// MIPSN32BE: #define __LDBL_MAX_10_EXP__ 4932
+// MIPSN32BE: #define __LDBL_MAX_EXP__ 16384
+// MIPSN32BE: #define __LDBL_MAX__ 1.18973149535723176508575932662800702e+4932L
+// MIPSN32BE: #define __LDBL_MIN_10_EXP__ (-4931)
+// MIPSN32BE: #define __LDBL_MIN_EXP__ (-16381)
+// MIPSN32BE: #define __LDBL_MIN__ 3.36210314311209350626267781732175260e-4932L
+// MIPSN32BE: #define __LONG_LONG_MAX__ 9223372036854775807LL
+// MIPSN32BE: #define __LONG_MAX__ 2147483647L
+// MIPSN32BE: #define __MIPSEB 1
+// MIPSN32BE: #define __MIPSEB__ 1
+// MIPSN32BE: #define __NO_INLINE__ 1
+// MIPSN32BE: #define __ORDER_BIG_ENDIAN__ 4321
+// MIPSN32BE: #define __ORDER_LITTLE_ENDIAN__ 1234
+// MIPSN32BE: #define __ORDER_PDP_ENDIAN__ 3412
+// MIPSN32BE: #define __POINTER_WIDTH__ 32
+// MIPSN32BE: #define __PRAGMA_REDEFINE_EXTNAME 1
+// MIPSN32BE: #define __PTRDIFF_FMTd__ "d"
+// MIPSN32BE: #define __PTRDIFF_FMTi__ "i"
+// MIPSN32BE: #define __PTRDIFF_MAX__ 2147483647
+// MIPSN32BE: #define __PTRDIFF_TYPE__ int
+// MIPSN32BE: #define __PTRDIFF_WIDTH__ 32
+// MIPSN32BE: #define __REGISTER_PREFIX__
+// MIPSN32BE: #define __SCHAR_MAX__ 127
+// MIPSN32BE: #define __SHRT_MAX__ 32767
+// MIPSN32BE: #define __SIG_ATOMIC_MAX__ 2147483647
+// MIPSN32BE: #define __SIG_ATOMIC_WIDTH__ 32
+// MIPSN32BE: #define __SIZEOF_DOUBLE__ 8
+// MIPSN32BE: #define __SIZEOF_FLOAT__ 4
+// MIPSN32BE: #define __SIZEOF_INT__ 4
+// MIPSN32BE: #define __SIZEOF_LONG_DOUBLE__ 16
+// MIPSN32BE: #define __SIZEOF_LONG_LONG__ 8
+// MIPSN32BE: #define __SIZEOF_LONG__ 4
+// MIPSN32BE: #define __SIZEOF_POINTER__ 4
+// MIPSN32BE: #define __SIZEOF_PTRDIFF_T__ 4
+// MIPSN32BE: #define __SIZEOF_SHORT__ 2
+// MIPSN32BE: #define __SIZEOF_SIZE_T__ 4
+// MIPSN32BE: #define __SIZEOF_WCHAR_T__ 4
+// MIPSN32BE: #define __SIZEOF_WINT_T__ 4
+// MIPSN32BE: #define __SIZE_FMTX__ "X"
+// MIPSN32BE: #define __SIZE_FMTo__ "o"
+// MIPSN32BE: #define __SIZE_FMTu__ "u"
+// MIPSN32BE: #define __SIZE_FMTx__ "x"
+// MIPSN32BE: #define __SIZE_MAX__ 4294967295U
+// MIPSN32BE: #define __SIZE_TYPE__ unsigned int
+// MIPSN32BE: #define __SIZE_WIDTH__ 32
+// MIPSN32BE: #define __STDC_HOSTED__ 0
+// MIPSN32BE: #define __STDC_UTF_16__ 1
+// MIPSN32BE: #define __STDC_UTF_32__ 1
+// MIPSN32BE: #define __STDC_VERSION__ 201112L
+// MIPSN32BE: #define __STDC__ 1
+// MIPSN32BE: #define __UINT16_C_SUFFIX__
+// MIPSN32BE: #define __UINT16_FMTX__ "hX"
+// MIPSN32BE: #define __UINT16_FMTo__ "ho"
+// MIPSN32BE: #define __UINT16_FMTu__ "hu"
+// MIPSN32BE: #define __UINT16_FMTx__ "hx"
+// MIPSN32BE: #define __UINT16_MAX__ 65535
+// MIPSN32BE: #define __UINT16_TYPE__ unsigned short
+// MIPSN32BE: #define __UINT32_C_SUFFIX__ U
+// MIPSN32BE: #define __UINT32_FMTX__ "X"
+// MIPSN32BE: #define __UINT32_FMTo__ "o"
+// MIPSN32BE: #define __UINT32_FMTu__ "u"
+// MIPSN32BE: #define __UINT32_FMTx__ "x"
+// MIPSN32BE: #define __UINT32_MAX__ 4294967295U
+// MIPSN32BE: #define __UINT32_TYPE__ unsigned int
+// MIPSN32BE: #define __UINT64_C_SUFFIX__ ULL
+// MIPSN32BE: #define __UINT64_FMTX__ "llX"
+// MIPSN32BE: #define __UINT64_FMTo__ "llo"
+// MIPSN32BE: #define __UINT64_FMTu__ "llu"
+// MIPSN32BE: #define __UINT64_FMTx__ "llx"
+// MIPSN32BE: #define __UINT64_MAX__ 18446744073709551615ULL
+// MIPSN32BE: #define __UINT64_TYPE__ long long unsigned int
+// MIPSN32BE: #define __UINT8_C_SUFFIX__
+// MIPSN32BE: #define __UINT8_FMTX__ "hhX"
+// MIPSN32BE: #define __UINT8_FMTo__ "hho"
+// MIPSN32BE: #define __UINT8_FMTu__ "hhu"
+// MIPSN32BE: #define __UINT8_FMTx__ "hhx"
+// MIPSN32BE: #define __UINT8_MAX__ 255
+// MIPSN32BE: #define __UINT8_TYPE__ unsigned char
+// MIPSN32BE: #define __UINTMAX_C_SUFFIX__ ULL
+// MIPSN32BE: #define __UINTMAX_FMTX__ "llX"
+// MIPSN32BE: #define __UINTMAX_FMTo__ "llo"
+// MIPSN32BE: #define __UINTMAX_FMTu__ "llu"
+// MIPSN32BE: #define __UINTMAX_FMTx__ "llx"
+// MIPSN32BE: #define __UINTMAX_MAX__ 18446744073709551615ULL
+// MIPSN32BE: #define __UINTMAX_TYPE__ long long unsigned int
+// MIPSN32BE: #define __UINTMAX_WIDTH__ 64
+// MIPSN32BE: #define __UINTPTR_FMTX__ "lX"
+// MIPSN32BE: #define __UINTPTR_FMTo__ "lo"
+// MIPSN32BE: #define __UINTPTR_FMTu__ "lu"
+// MIPSN32BE: #define __UINTPTR_FMTx__ "lx"
+// MIPSN32BE: #define __UINTPTR_MAX__ 4294967295UL
+// MIPSN32BE: #define __UINTPTR_TYPE__ long unsigned int
+// MIPSN32BE: #define __UINTPTR_WIDTH__ 32
+// MIPSN32BE: #define __UINT_FAST16_FMTX__ "hX"
+// MIPSN32BE: #define __UINT_FAST16_FMTo__ "ho"
+// MIPSN32BE: #define __UINT_FAST16_FMTu__ "hu"
+// MIPSN32BE: #define __UINT_FAST16_FMTx__ "hx"
+// MIPSN32BE: #define __UINT_FAST16_MAX__ 65535
+// MIPSN32BE: #define __UINT_FAST16_TYPE__ unsigned short
+// MIPSN32BE: #define __UINT_FAST32_FMTX__ "X"
+// MIPSN32BE: #define __UINT_FAST32_FMTo__ "o"
+// MIPSN32BE: #define __UINT_FAST32_FMTu__ "u"
+// MIPSN32BE: #define __UINT_FAST32_FMTx__ "x"
+// MIPSN32BE: #define __UINT_FAST32_MAX__ 4294967295U
+// MIPSN32BE: #define __UINT_FAST32_TYPE__ unsigned int
+// MIPSN32BE: #define __UINT_FAST64_FMTX__ "llX"
+// MIPSN32BE: #define __UINT_FAST64_FMTo__ "llo"
+// MIPSN32BE: #define __UINT_FAST64_FMTu__ "llu"
+// MIPSN32BE: #define __UINT_FAST64_FMTx__ "llx"
+// MIPSN32BE: #define __UINT_FAST64_MAX__ 18446744073709551615ULL
+// MIPSN32BE: #define __UINT_FAST64_TYPE__ long long unsigned int
+// MIPSN32BE: #define __UINT_FAST8_FMTX__ "hhX"
+// MIPSN32BE: #define __UINT_FAST8_FMTo__ "hho"
+// MIPSN32BE: #define __UINT_FAST8_FMTu__ "hhu"
+// MIPSN32BE: #define __UINT_FAST8_FMTx__ "hhx"
+// MIPSN32BE: #define __UINT_FAST8_MAX__ 255
+// MIPSN32BE: #define __UINT_FAST8_TYPE__ unsigned char
+// MIPSN32BE: #define __UINT_LEAST16_FMTX__ "hX"
+// MIPSN32BE: #define __UINT_LEAST16_FMTo__ "ho"
+// MIPSN32BE: #define __UINT_LEAST16_FMTu__ "hu"
+// MIPSN32BE: #define __UINT_LEAST16_FMTx__ "hx"
+// MIPSN32BE: #define __UINT_LEAST16_MAX__ 65535
+// MIPSN32BE: #define __UINT_LEAST16_TYPE__ unsigned short
+// MIPSN32BE: #define __UINT_LEAST32_FMTX__ "X"
+// MIPSN32BE: #define __UINT_LEAST32_FMTo__ "o"
+// MIPSN32BE: #define __UINT_LEAST32_FMTu__ "u"
+// MIPSN32BE: #define __UINT_LEAST32_FMTx__ "x"
+// MIPSN32BE: #define __UINT_LEAST32_MAX__ 4294967295U
+// MIPSN32BE: #define __UINT_LEAST32_TYPE__ unsigned int
+// MIPSN32BE: #define __UINT_LEAST64_FMTX__ "llX"
+// MIPSN32BE: #define __UINT_LEAST64_FMTo__ "llo"
+// MIPSN32BE: #define __UINT_LEAST64_FMTu__ "llu"
+// MIPSN32BE: #define __UINT_LEAST64_FMTx__ "llx"
+// MIPSN32BE: #define __UINT_LEAST64_MAX__ 18446744073709551615ULL
+// MIPSN32BE: #define __UINT_LEAST64_TYPE__ long long unsigned int
+// MIPSN32BE: #define __UINT_LEAST8_FMTX__ "hhX"
+// MIPSN32BE: #define __UINT_LEAST8_FMTo__ "hho"
+// MIPSN32BE: #define __UINT_LEAST8_FMTu__ "hhu"
+// MIPSN32BE: #define __UINT_LEAST8_FMTx__ "hhx"
+// MIPSN32BE: #define __UINT_LEAST8_MAX__ 255
+// MIPSN32BE: #define __UINT_LEAST8_TYPE__ unsigned char
+// MIPSN32BE: #define __USER_LABEL_PREFIX__ _
+// MIPSN32BE: #define __WCHAR_MAX__ 2147483647
+// MIPSN32BE: #define __WCHAR_TYPE__ int
+// MIPSN32BE: #define __WCHAR_WIDTH__ 32
+// MIPSN32BE: #define __WINT_TYPE__ int
+// MIPSN32BE: #define __WINT_WIDTH__ 32
+// MIPSN32BE: #define __clang__ 1
+// MIPSN32BE: #define __llvm__ 1
+// MIPSN32BE: #define __mips 64
+// MIPSN32BE: #define __mips64 1
+// MIPSN32BE: #define __mips64__ 1
+// MIPSN32BE: #define __mips__ 1
+// MIPSN32BE: #define __mips_fpr 64
+// MIPSN32BE: #define __mips_hard_float 1
+// MIPSN32BE: #define __mips_isa_rev 2
+// MIPSN32BE: #define __mips_n32 1
+// MIPSN32BE: #define _mips 1
+// MIPSN32BE: #define mips 1
+//
+// RUN: %clang_cc1 -E -dM -ffreestanding \
+// RUN:            -triple=mips64el-none-none -target-abi n32 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPSN32EL %s
+//
+// MIPSN32EL: #define MIPSEL 1
+// MIPSN32EL: #define _ABIN32 2
+// MIPSN32EL: #define _ILP32 1
+// MIPSN32EL: #define _MIPSEL 1
+// MIPSN32EL: #define _MIPS_ARCH "mips64r2"
+// MIPSN32EL: #define _MIPS_ARCH_MIPS64R2 1
+// MIPSN32EL: #define _MIPS_FPSET 32
+// MIPSN32EL: #define _MIPS_ISA _MIPS_ISA_MIPS64
+// MIPSN32EL: #define _MIPS_SIM _ABIN32
+// MIPSN32EL: #define _MIPS_SZINT 32
+// MIPSN32EL: #define _MIPS_SZLONG 32
+// MIPSN32EL: #define _MIPS_SZPTR 32
+// MIPSN32EL: #define __ATOMIC_ACQUIRE 2
+// MIPSN32EL: #define __ATOMIC_ACQ_REL 4
+// MIPSN32EL: #define __ATOMIC_CONSUME 1
+// MIPSN32EL: #define __ATOMIC_RELAXED 0
+// MIPSN32EL: #define __ATOMIC_RELEASE 3
+// MIPSN32EL: #define __ATOMIC_SEQ_CST 5
+// MIPSN32EL: #define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
+// MIPSN32EL: #define __CHAR16_TYPE__ unsigned short
+// MIPSN32EL: #define __CHAR32_TYPE__ unsigned int
+// MIPSN32EL: #define __CHAR_BIT__ 8
+// MIPSN32EL: #define __CONSTANT_CFSTRINGS__ 1
+// MIPSN32EL: #define __DBL_DENORM_MIN__ 4.9406564584124654e-324
+// MIPSN32EL: #define __DBL_DIG__ 15
+// MIPSN32EL: #define __DBL_EPSILON__ 2.2204460492503131e-16
+// MIPSN32EL: #define __DBL_HAS_DENORM__ 1
+// MIPSN32EL: #define __DBL_HAS_INFINITY__ 1
+// MIPSN32EL: #define __DBL_HAS_QUIET_NAN__ 1
+// MIPSN32EL: #define __DBL_MANT_DIG__ 53
+// MIPSN32EL: #define __DBL_MAX_10_EXP__ 308
+// MIPSN32EL: #define __DBL_MAX_EXP__ 1024
+// MIPSN32EL: #define __DBL_MAX__ 1.7976931348623157e+308
+// MIPSN32EL: #define __DBL_MIN_10_EXP__ (-307)
+// MIPSN32EL: #define __DBL_MIN_EXP__ (-1021)
+// MIPSN32EL: #define __DBL_MIN__ 2.2250738585072014e-308
+// MIPSN32EL: #define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
+// MIPSN32EL: #define __FINITE_MATH_ONLY__ 0
+// MIPSN32EL: #define __FLT_DENORM_MIN__ 1.40129846e-45F
+// MIPSN32EL: #define __FLT_DIG__ 6
+// MIPSN32EL: #define __FLT_EPSILON__ 1.19209290e-7F
+// MIPSN32EL: #define __FLT_EVAL_METHOD__ 0
+// MIPSN32EL: #define __FLT_HAS_DENORM__ 1
+// MIPSN32EL: #define __FLT_HAS_INFINITY__ 1
+// MIPSN32EL: #define __FLT_HAS_QUIET_NAN__ 1
+// MIPSN32EL: #define __FLT_MANT_DIG__ 24
+// MIPSN32EL: #define __FLT_MAX_10_EXP__ 38
+// MIPSN32EL: #define __FLT_MAX_EXP__ 128
+// MIPSN32EL: #define __FLT_MAX__ 3.40282347e+38F
+// MIPSN32EL: #define __FLT_MIN_10_EXP__ (-37)
+// MIPSN32EL: #define __FLT_MIN_EXP__ (-125)
+// MIPSN32EL: #define __FLT_MIN__ 1.17549435e-38F
+// MIPSN32EL: #define __FLT_RADIX__ 2
+// MIPSN32EL: #define __GCC_ATOMIC_BOOL_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_CHAR_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_INT_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_LLONG_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_LONG_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_POINTER_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_SHORT_LOCK_FREE 2
+// MIPSN32EL: #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
+// MIPSN32EL: #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
+// MIPSN32EL: #define __GNUC_MINOR__ 2
+// MIPSN32EL: #define __GNUC_PATCHLEVEL__ 1
+// MIPSN32EL: #define __GNUC_STDC_INLINE__ 1
+// MIPSN32EL: #define __GNUC__ 4
+// MIPSN32EL: #define __GXX_ABI_VERSION 1002
+// MIPSN32EL: #define __GXX_RTTI 1
+// MIPSN32EL: #define __ILP32__ 1
+// MIPSN32EL: #define __INT16_C_SUFFIX__
+// MIPSN32EL: #define __INT16_FMTd__ "hd"
+// MIPSN32EL: #define __INT16_FMTi__ "hi"
+// MIPSN32EL: #define __INT16_MAX__ 32767
+// MIPSN32EL: #define __INT16_TYPE__ short
+// MIPSN32EL: #define __INT32_C_SUFFIX__
+// MIPSN32EL: #define __INT32_FMTd__ "d"
+// MIPSN32EL: #define __INT32_FMTi__ "i"
+// MIPSN32EL: #define __INT32_MAX__ 2147483647
+// MIPSN32EL: #define __INT32_TYPE__ int
+// MIPSN32EL: #define __INT64_C_SUFFIX__ LL
+// MIPSN32EL: #define __INT64_FMTd__ "lld"
+// MIPSN32EL: #define __INT64_FMTi__ "lli"
+// MIPSN32EL: #define __INT64_MAX__ 9223372036854775807LL
+// MIPSN32EL: #define __INT64_TYPE__ long long int
+// MIPSN32EL: #define __INT8_C_SUFFIX__
+// MIPSN32EL: #define __INT8_FMTd__ "hhd"
+// MIPSN32EL: #define __INT8_FMTi__ "hhi"
+// MIPSN32EL: #define __INT8_MAX__ 127
+// MIPSN32EL: #define __INT8_TYPE__ signed char
+// MIPSN32EL: #define __INTMAX_C_SUFFIX__ LL
+// MIPSN32EL: #define __INTMAX_FMTd__ "lld"
+// MIPSN32EL: #define __INTMAX_FMTi__ "lli"
+// MIPSN32EL: #define __INTMAX_MAX__ 9223372036854775807LL
+// MIPSN32EL: #define __INTMAX_TYPE__ long long int
+// MIPSN32EL: #define __INTMAX_WIDTH__ 64
+// MIPSN32EL: #define __INTPTR_FMTd__ "ld"
+// MIPSN32EL: #define __INTPTR_FMTi__ "li"
+// MIPSN32EL: #define __INTPTR_MAX__ 2147483647L
+// MIPSN32EL: #define __INTPTR_TYPE__ long int
+// MIPSN32EL: #define __INTPTR_WIDTH__ 32
+// MIPSN32EL: #define __INT_FAST16_FMTd__ "hd"
+// MIPSN32EL: #define __INT_FAST16_FMTi__ "hi"
+// MIPSN32EL: #define __INT_FAST16_MAX__ 32767
+// MIPSN32EL: #define __INT_FAST16_TYPE__ short
+// MIPSN32EL: #define __INT_FAST32_FMTd__ "d"
+// MIPSN32EL: #define __INT_FAST32_FMTi__ "i"
+// MIPSN32EL: #define __INT_FAST32_MAX__ 2147483647
+// MIPSN32EL: #define __INT_FAST32_TYPE__ int
+// MIPSN32EL: #define __INT_FAST64_FMTd__ "lld"
+// MIPSN32EL: #define __INT_FAST64_FMTi__ "lli"
+// MIPSN32EL: #define __INT_FAST64_MAX__ 9223372036854775807LL
+// MIPSN32EL: #define __INT_FAST64_TYPE__ long long int
+// MIPSN32EL: #define __INT_FAST8_FMTd__ "hhd"
+// MIPSN32EL: #define __INT_FAST8_FMTi__ "hhi"
+// MIPSN32EL: #define __INT_FAST8_MAX__ 127
+// MIPSN32EL: #define __INT_FAST8_TYPE__ signed char
+// MIPSN32EL: #define __INT_LEAST16_FMTd__ "hd"
+// MIPSN32EL: #define __INT_LEAST16_FMTi__ "hi"
+// MIPSN32EL: #define __INT_LEAST16_MAX__ 32767
+// MIPSN32EL: #define __INT_LEAST16_TYPE__ short
+// MIPSN32EL: #define __INT_LEAST32_FMTd__ "d"
+// MIPSN32EL: #define __INT_LEAST32_FMTi__ "i"
+// MIPSN32EL: #define __INT_LEAST32_MAX__ 2147483647
+// MIPSN32EL: #define __INT_LEAST32_TYPE__ int
+// MIPSN32EL: #define __INT_LEAST64_FMTd__ "lld"
+// MIPSN32EL: #define __INT_LEAST64_FMTi__ "lli"
+// MIPSN32EL: #define __INT_LEAST64_MAX__ 9223372036854775807LL
+// MIPSN32EL: #define __INT_LEAST64_TYPE__ long long int
+// MIPSN32EL: #define __INT_LEAST8_FMTd__ "hhd"
+// MIPSN32EL: #define __INT_LEAST8_FMTi__ "hhi"
+// MIPSN32EL: #define __INT_LEAST8_MAX__ 127
+// MIPSN32EL: #define __INT_LEAST8_TYPE__ signed char
+// MIPSN32EL: #define __INT_MAX__ 2147483647
+// MIPSN32EL: #define __LDBL_DENORM_MIN__ 6.47517511943802511092443895822764655e-4966L
+// MIPSN32EL: #define __LDBL_DIG__ 33
+// MIPSN32EL: #define __LDBL_EPSILON__ 1.92592994438723585305597794258492732e-34L
+// MIPSN32EL: #define __LDBL_HAS_DENORM__ 1
+// MIPSN32EL: #define __LDBL_HAS_INFINITY__ 1
+// MIPSN32EL: #define __LDBL_HAS_QUIET_NAN__ 1
+// MIPSN32EL: #define __LDBL_MANT_DIG__ 113
+// MIPSN32EL: #define __LDBL_MAX_10_EXP__ 4932
+// MIPSN32EL: #define __LDBL_MAX_EXP__ 16384
+// MIPSN32EL: #define __LDBL_MAX__ 1.18973149535723176508575932662800702e+4932L
+// MIPSN32EL: #define __LDBL_MIN_10_EXP__ (-4931)
+// MIPSN32EL: #define __LDBL_MIN_EXP__ (-16381)
+// MIPSN32EL: #define __LDBL_MIN__ 3.36210314311209350626267781732175260e-4932L
+// MIPSN32EL: #define __LITTLE_ENDIAN__ 1
+// MIPSN32EL: #define __LONG_LONG_MAX__ 9223372036854775807LL
+// MIPSN32EL: #define __LONG_MAX__ 2147483647L
+// MIPSN32EL: #define __MIPSEL 1
+// MIPSN32EL: #define __MIPSEL__ 1
+// MIPSN32EL: #define __NO_INLINE__ 1
+// MIPSN32EL: #define __ORDER_BIG_ENDIAN__ 4321
+// MIPSN32EL: #define __ORDER_LITTLE_ENDIAN__ 1234
+// MIPSN32EL: #define __ORDER_PDP_ENDIAN__ 3412
+// MIPSN32EL: #define __POINTER_WIDTH__ 32
+// MIPSN32EL: #define __PRAGMA_REDEFINE_EXTNAME 1
+// MIPSN32EL: #define __PTRDIFF_FMTd__ "d"
+// MIPSN32EL: #define __PTRDIFF_FMTi__ "i"
+// MIPSN32EL: #define __PTRDIFF_MAX__ 2147483647
+// MIPSN32EL: #define __PTRDIFF_TYPE__ int
+// MIPSN32EL: #define __PTRDIFF_WIDTH__ 32
+// MIPSN32EL: #define __REGISTER_PREFIX__
+// MIPSN32EL: #define __SCHAR_MAX__ 127
+// MIPSN32EL: #define __SHRT_MAX__ 32767
+// MIPSN32EL: #define __SIG_ATOMIC_MAX__ 2147483647
+// MIPSN32EL: #define __SIG_ATOMIC_WIDTH__ 32
+// MIPSN32EL: #define __SIZEOF_DOUBLE__ 8
+// MIPSN32EL: #define __SIZEOF_FLOAT__ 4
+// MIPSN32EL: #define __SIZEOF_INT__ 4
+// MIPSN32EL: #define __SIZEOF_LONG_DOUBLE__ 16
+// MIPSN32EL: #define __SIZEOF_LONG_LONG__ 8
+// MIPSN32EL: #define __SIZEOF_LONG__ 4
+// MIPSN32EL: #define __SIZEOF_POINTER__ 4
+// MIPSN32EL: #define __SIZEOF_PTRDIFF_T__ 4
+// MIPSN32EL: #define __SIZEOF_SHORT__ 2
+// MIPSN32EL: #define __SIZEOF_SIZE_T__ 4
+// MIPSN32EL: #define __SIZEOF_WCHAR_T__ 4
+// MIPSN32EL: #define __SIZEOF_WINT_T__ 4
+// MIPSN32EL: #define __SIZE_FMTX__ "X"
+// MIPSN32EL: #define __SIZE_FMTo__ "o"
+// MIPSN32EL: #define __SIZE_FMTu__ "u"
+// MIPSN32EL: #define __SIZE_FMTx__ "x"
+// MIPSN32EL: #define __SIZE_MAX__ 4294967295U
+// MIPSN32EL: #define __SIZE_TYPE__ unsigned int
+// MIPSN32EL: #define __SIZE_WIDTH__ 32
+// MIPSN32EL: #define __STDC_HOSTED__ 0
+// MIPSN32EL: #define __STDC_UTF_16__ 1
+// MIPSN32EL: #define __STDC_UTF_32__ 1
+// MIPSN32EL: #define __STDC_VERSION__ 201112L
+// MIPSN32EL: #define __STDC__ 1
+// MIPSN32EL: #define __UINT16_C_SUFFIX__
+// MIPSN32EL: #define __UINT16_FMTX__ "hX"
+// MIPSN32EL: #define __UINT16_FMTo__ "ho"
+// MIPSN32EL: #define __UINT16_FMTu__ "hu"
+// MIPSN32EL: #define __UINT16_FMTx__ "hx"
+// MIPSN32EL: #define __UINT16_MAX__ 65535
+// MIPSN32EL: #define __UINT16_TYPE__ unsigned short
+// MIPSN32EL: #define __UINT32_C_SUFFIX__ U
+// MIPSN32EL: #define __UINT32_FMTX__ "X"
+// MIPSN32EL: #define __UINT32_FMTo__ "o"
+// MIPSN32EL: #define __UINT32_FMTu__ "u"
+// MIPSN32EL: #define __UINT32_FMTx__ "x"
+// MIPSN32EL: #define __UINT32_MAX__ 4294967295U
+// MIPSN32EL: #define __UINT32_TYPE__ unsigned int
+// MIPSN32EL: #define __UINT64_C_SUFFIX__ ULL
+// MIPSN32EL: #define __UINT64_FMTX__ "llX"
+// MIPSN32EL: #define __UINT64_FMTo__ "llo"
+// MIPSN32EL: #define __UINT64_FMTu__ "llu"
+// MIPSN32EL: #define __UINT64_FMTx__ "llx"
+// MIPSN32EL: #define __UINT64_MAX__ 18446744073709551615ULL
+// MIPSN32EL: #define __UINT64_TYPE__ long long unsigned int
+// MIPSN32EL: #define __UINT8_C_SUFFIX__
+// MIPSN32EL: #define __UINT8_FMTX__ "hhX"
+// MIPSN32EL: #define __UINT8_FMTo__ "hho"
+// MIPSN32EL: #define __UINT8_FMTu__ "hhu"
+// MIPSN32EL: #define __UINT8_FMTx__ "hhx"
+// MIPSN32EL: #define __UINT8_MAX__ 255
+// MIPSN32EL: #define __UINT8_TYPE__ unsigned char
+// MIPSN32EL: #define __UINTMAX_C_SUFFIX__ ULL
+// MIPSN32EL: #define __UINTMAX_FMTX__ "llX"
+// MIPSN32EL: #define __UINTMAX_FMTo__ "llo"
+// MIPSN32EL: #define __UINTMAX_FMTu__ "llu"
+// MIPSN32EL: #define __UINTMAX_FMTx__ "llx"
+// MIPSN32EL: #define __UINTMAX_MAX__ 18446744073709551615ULL
+// MIPSN32EL: #define __UINTMAX_TYPE__ long long unsigned int
+// MIPSN32EL: #define __UINTMAX_WIDTH__ 64
+// MIPSN32EL: #define __UINTPTR_FMTX__ "lX"
+// MIPSN32EL: #define __UINTPTR_FMTo__ "lo"
+// MIPSN32EL: #define __UINTPTR_FMTu__ "lu"
+// MIPSN32EL: #define __UINTPTR_FMTx__ "lx"
+// MIPSN32EL: #define __UINTPTR_MAX__ 4294967295UL
+// MIPSN32EL: #define __UINTPTR_TYPE__ long unsigned int
+// MIPSN32EL: #define __UINTPTR_WIDTH__ 32
+// MIPSN32EL: #define __UINT_FAST16_FMTX__ "hX"
+// MIPSN32EL: #define __UINT_FAST16_FMTo__ "ho"
+// MIPSN32EL: #define __UINT_FAST16_FMTu__ "hu"
+// MIPSN32EL: #define __UINT_FAST16_FMTx__ "hx"
+// MIPSN32EL: #define __UINT_FAST16_MAX__ 65535
+// MIPSN32EL: #define __UINT_FAST16_TYPE__ unsigned short
+// MIPSN32EL: #define __UINT_FAST32_FMTX__ "X"
+// MIPSN32EL: #define __UINT_FAST32_FMTo__ "o"
+// MIPSN32EL: #define __UINT_FAST32_FMTu__ "u"
+// MIPSN32EL: #define __UINT_FAST32_FMTx__ "x"
+// MIPSN32EL: #define __UINT_FAST32_MAX__ 4294967295U
+// MIPSN32EL: #define __UINT_FAST32_TYPE__ unsigned int
+// MIPSN32EL: #define __UINT_FAST64_FMTX__ "llX"
+// MIPSN32EL: #define __UINT_FAST64_FMTo__ "llo"
+// MIPSN32EL: #define __UINT_FAST64_FMTu__ "llu"
+// MIPSN32EL: #define __UINT_FAST64_FMTx__ "llx"
+// MIPSN32EL: #define __UINT_FAST64_MAX__ 18446744073709551615ULL
+// MIPSN32EL: #define __UINT_FAST64_TYPE__ long long unsigned int
+// MIPSN32EL: #define __UINT_FAST8_FMTX__ "hhX"
+// MIPSN32EL: #define __UINT_FAST8_FMTo__ "hho"
+// MIPSN32EL: #define __UINT_FAST8_FMTu__ "hhu"
+// MIPSN32EL: #define __UINT_FAST8_FMTx__ "hhx"
+// MIPSN32EL: #define __UINT_FAST8_MAX__ 255
+// MIPSN32EL: #define __UINT_FAST8_TYPE__ unsigned char
+// MIPSN32EL: #define __UINT_LEAST16_FMTX__ "hX"
+// MIPSN32EL: #define __UINT_LEAST16_FMTo__ "ho"
+// MIPSN32EL: #define __UINT_LEAST16_FMTu__ "hu"
+// MIPSN32EL: #define __UINT_LEAST16_FMTx__ "hx"
+// MIPSN32EL: #define __UINT_LEAST16_MAX__ 65535
+// MIPSN32EL: #define __UINT_LEAST16_TYPE__ unsigned short
+// MIPSN32EL: #define __UINT_LEAST32_FMTX__ "X"
+// MIPSN32EL: #define __UINT_LEAST32_FMTo__ "o"
+// MIPSN32EL: #define __UINT_LEAST32_FMTu__ "u"
+// MIPSN32EL: #define __UINT_LEAST32_FMTx__ "x"
+// MIPSN32EL: #define __UINT_LEAST32_MAX__ 4294967295U
+// MIPSN32EL: #define __UINT_LEAST32_TYPE__ unsigned int
+// MIPSN32EL: #define __UINT_LEAST64_FMTX__ "llX"
+// MIPSN32EL: #define __UINT_LEAST64_FMTo__ "llo"
+// MIPSN32EL: #define __UINT_LEAST64_FMTu__ "llu"
+// MIPSN32EL: #define __UINT_LEAST64_FMTx__ "llx"
+// MIPSN32EL: #define __UINT_LEAST64_MAX__ 18446744073709551615ULL
+// MIPSN32EL: #define __UINT_LEAST64_TYPE__ long long unsigned int
+// MIPSN32EL: #define __UINT_LEAST8_FMTX__ "hhX"
+// MIPSN32EL: #define __UINT_LEAST8_FMTo__ "hho"
+// MIPSN32EL: #define __UINT_LEAST8_FMTu__ "hhu"
+// MIPSN32EL: #define __UINT_LEAST8_FMTx__ "hhx"
+// MIPSN32EL: #define __UINT_LEAST8_MAX__ 255
+// MIPSN32EL: #define __UINT_LEAST8_TYPE__ unsigned char
+// MIPSN32EL: #define __USER_LABEL_PREFIX__ _
+// MIPSN32EL: #define __WCHAR_MAX__ 2147483647
+// MIPSN32EL: #define __WCHAR_TYPE__ int
+// MIPSN32EL: #define __WCHAR_WIDTH__ 32
+// MIPSN32EL: #define __WINT_TYPE__ int
+// MIPSN32EL: #define __WINT_WIDTH__ 32
+// MIPSN32EL: #define __clang__ 1
+// MIPSN32EL: #define __llvm__ 1
+// MIPSN32EL: #define __mips 64
+// MIPSN32EL: #define __mips64 1
+// MIPSN32EL: #define __mips64__ 1
+// MIPSN32EL: #define __mips__ 1
+// MIPSN32EL: #define __mips_fpr 64
+// MIPSN32EL: #define __mips_hard_float 1
+// MIPSN32EL: #define __mips_isa_rev 2
+// MIPSN32EL: #define __mips_n32 1
+// MIPSN32EL: #define _mips 1
+// MIPSN32EL: #define mips 1
+//
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips64-none-none < /dev/null | FileCheck -check-prefix MIPS64BE %s
 //
 // MIPS64BE:#define MIPSEB 1
@@ -3010,6 +3829,7 @@
 // MIPS64BE:#define _MIPS_SZINT 32
 // MIPS64BE:#define _MIPS_SZLONG 64
 // MIPS64BE:#define _MIPS_SZPTR 64
+// MIPS64BE:#define __BIGGEST_ALIGNMENT__ 16
 // MIPS64BE:#define __BIG_ENDIAN__ 1
 // MIPS64BE:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // MIPS64BE:#define __CHAR16_TYPE__ unsigned short
@@ -3029,7 +3849,7 @@
 // MIPS64BE:#define __DBL_MIN_10_EXP__ (-307)
 // MIPS64BE:#define __DBL_MIN_EXP__ (-1021)
 // MIPS64BE:#define __DBL_MIN__ 2.2250738585072014e-308
-// MIPS64BE:#define __DECIMAL_DIG__ 36
+// MIPS64BE:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // MIPS64BE:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // MIPS64BE:#define __FLT_DIG__ 6
 // MIPS64BE:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -3055,21 +3875,21 @@
 // MIPS64BE:#define __INT32_FMTi__ "i"
 // MIPS64BE:#define __INT32_MAX__ 2147483647
 // MIPS64BE:#define __INT32_TYPE__ int
-// MIPS64BE:#define __INT64_C_SUFFIX__ LL
-// MIPS64BE:#define __INT64_FMTd__ "lld"
-// MIPS64BE:#define __INT64_FMTi__ "lli"
+// MIPS64BE:#define __INT64_C_SUFFIX__ L
+// MIPS64BE:#define __INT64_FMTd__ "ld"
+// MIPS64BE:#define __INT64_FMTi__ "li"
 // MIPS64BE:#define __INT64_MAX__ 9223372036854775807L
-// MIPS64BE:#define __INT64_TYPE__ long long int
+// MIPS64BE:#define __INT64_TYPE__ long int
 // MIPS64BE:#define __INT8_C_SUFFIX__ {{$}}
 // MIPS64BE:#define __INT8_FMTd__ "hhd"
 // MIPS64BE:#define __INT8_FMTi__ "hhi"
 // MIPS64BE:#define __INT8_MAX__ 127
 // MIPS64BE:#define __INT8_TYPE__ signed char
-// MIPS64BE:#define __INTMAX_C_SUFFIX__ LL
-// MIPS64BE:#define __INTMAX_FMTd__ "lld"
-// MIPS64BE:#define __INTMAX_FMTi__ "lli"
-// MIPS64BE:#define __INTMAX_MAX__ 9223372036854775807LL
-// MIPS64BE:#define __INTMAX_TYPE__ long long int
+// MIPS64BE:#define __INTMAX_C_SUFFIX__ L
+// MIPS64BE:#define __INTMAX_FMTd__ "ld"
+// MIPS64BE:#define __INTMAX_FMTi__ "li"
+// MIPS64BE:#define __INTMAX_MAX__ 9223372036854775807L
+// MIPS64BE:#define __INTMAX_TYPE__ long int
 // MIPS64BE:#define __INTMAX_WIDTH__ 64
 // MIPS64BE:#define __INTPTR_FMTd__ "ld"
 // MIPS64BE:#define __INTPTR_FMTi__ "li"
@@ -3138,6 +3958,7 @@
 // MIPS64BE:#define __SIG_ATOMIC_WIDTH__ 32
 // MIPS64BE:#define __SIZEOF_DOUBLE__ 8
 // MIPS64BE:#define __SIZEOF_FLOAT__ 4
+// MIPS64BE:#define __SIZEOF_INT128__ 16
 // MIPS64BE:#define __SIZEOF_INT__ 4
 // MIPS64BE:#define __SIZEOF_LONG_DOUBLE__ 16
 // MIPS64BE:#define __SIZEOF_LONG_LONG__ 8
@@ -3157,15 +3978,15 @@
 // MIPS64BE:#define __UINT32_C_SUFFIX__ U
 // MIPS64BE:#define __UINT32_MAX__ 4294967295U
 // MIPS64BE:#define __UINT32_TYPE__ unsigned int
-// MIPS64BE:#define __UINT64_C_SUFFIX__ ULL
-// MIPS64BE:#define __UINT64_MAX__ 18446744073709551615ULL
-// MIPS64BE:#define __UINT64_TYPE__ long long unsigned int
+// MIPS64BE:#define __UINT64_C_SUFFIX__ UL
+// MIPS64BE:#define __UINT64_MAX__ 18446744073709551615UL
+// MIPS64BE:#define __UINT64_TYPE__ long unsigned int
 // MIPS64BE:#define __UINT8_C_SUFFIX__ {{$}}
 // MIPS64BE:#define __UINT8_MAX__ 255
 // MIPS64BE:#define __UINT8_TYPE__ unsigned char
-// MIPS64BE:#define __UINTMAX_C_SUFFIX__ ULL
-// MIPS64BE:#define __UINTMAX_MAX__ 18446744073709551615ULL
-// MIPS64BE:#define __UINTMAX_TYPE__ long long unsigned int
+// MIPS64BE:#define __UINTMAX_C_SUFFIX__ UL
+// MIPS64BE:#define __UINTMAX_MAX__ 18446744073709551615UL
+// MIPS64BE:#define __UINTMAX_TYPE__ long unsigned int
 // MIPS64BE:#define __UINTMAX_WIDTH__ 64
 // MIPS64BE:#define __UINTPTR_MAX__ 18446744073709551615UL
 // MIPS64BE:#define __UINTPTR_TYPE__ long unsigned int
@@ -3217,6 +4038,7 @@
 // MIPS64EL:#define _MIPS_SZINT 32
 // MIPS64EL:#define _MIPS_SZLONG 64
 // MIPS64EL:#define _MIPS_SZPTR 64
+// MIPS64EL:#define __BIGGEST_ALIGNMENT__ 16
 // MIPS64EL:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // MIPS64EL:#define __CHAR16_TYPE__ unsigned short
 // MIPS64EL:#define __CHAR32_TYPE__ unsigned int
@@ -3235,7 +4057,7 @@
 // MIPS64EL:#define __DBL_MIN_10_EXP__ (-307)
 // MIPS64EL:#define __DBL_MIN_EXP__ (-1021)
 // MIPS64EL:#define __DBL_MIN__ 2.2250738585072014e-308
-// MIPS64EL:#define __DECIMAL_DIG__ 36
+// MIPS64EL:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // MIPS64EL:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // MIPS64EL:#define __FLT_DIG__ 6
 // MIPS64EL:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -3261,21 +4083,21 @@
 // MIPS64EL:#define __INT32_FMTi__ "i"
 // MIPS64EL:#define __INT32_MAX__ 2147483647
 // MIPS64EL:#define __INT32_TYPE__ int
-// MIPS64EL:#define __INT64_C_SUFFIX__ LL
-// MIPS64EL:#define __INT64_FMTd__ "lld"
-// MIPS64EL:#define __INT64_FMTi__ "lli"
+// MIPS64EL:#define __INT64_C_SUFFIX__ L
+// MIPS64EL:#define __INT64_FMTd__ "ld"
+// MIPS64EL:#define __INT64_FMTi__ "li"
 // MIPS64EL:#define __INT64_MAX__ 9223372036854775807L
-// MIPS64EL:#define __INT64_TYPE__ long long int
+// MIPS64EL:#define __INT64_TYPE__ long int
 // MIPS64EL:#define __INT8_C_SUFFIX__ {{$}}
 // MIPS64EL:#define __INT8_FMTd__ "hhd"
 // MIPS64EL:#define __INT8_FMTi__ "hhi"
 // MIPS64EL:#define __INT8_MAX__ 127
 // MIPS64EL:#define __INT8_TYPE__ signed char
-// MIPS64EL:#define __INTMAX_C_SUFFIX__ LL
-// MIPS64EL:#define __INTMAX_FMTd__ "lld"
-// MIPS64EL:#define __INTMAX_FMTi__ "lli"
-// MIPS64EL:#define __INTMAX_MAX__ 9223372036854775807LL
-// MIPS64EL:#define __INTMAX_TYPE__ long long int
+// MIPS64EL:#define __INTMAX_C_SUFFIX__ L
+// MIPS64EL:#define __INTMAX_FMTd__ "ld"
+// MIPS64EL:#define __INTMAX_FMTi__ "li"
+// MIPS64EL:#define __INTMAX_MAX__ 9223372036854775807L
+// MIPS64EL:#define __INTMAX_TYPE__ long int
 // MIPS64EL:#define __INTMAX_WIDTH__ 64
 // MIPS64EL:#define __INTPTR_FMTd__ "ld"
 // MIPS64EL:#define __INTPTR_FMTi__ "li"
@@ -3345,6 +4167,7 @@
 // MIPS64EL:#define __SIG_ATOMIC_WIDTH__ 32
 // MIPS64EL:#define __SIZEOF_DOUBLE__ 8
 // MIPS64EL:#define __SIZEOF_FLOAT__ 4
+// MIPS64EL:#define __SIZEOF_INT128__ 16
 // MIPS64EL:#define __SIZEOF_INT__ 4
 // MIPS64EL:#define __SIZEOF_LONG_DOUBLE__ 16
 // MIPS64EL:#define __SIZEOF_LONG_LONG__ 8
@@ -3364,15 +4187,15 @@
 // MIPS64EL:#define __UINT32_C_SUFFIX__ U
 // MIPS64EL:#define __UINT32_MAX__ 4294967295U
 // MIPS64EL:#define __UINT32_TYPE__ unsigned int
-// MIPS64EL:#define __UINT64_C_SUFFIX__ ULL
-// MIPS64EL:#define __UINT64_MAX__ 18446744073709551615ULL
-// MIPS64EL:#define __UINT64_TYPE__ long long unsigned int
+// MIPS64EL:#define __UINT64_C_SUFFIX__ UL
+// MIPS64EL:#define __UINT64_MAX__ 18446744073709551615UL
+// MIPS64EL:#define __UINT64_TYPE__ long unsigned int
 // MIPS64EL:#define __UINT8_C_SUFFIX__ {{$}}
 // MIPS64EL:#define __UINT8_MAX__ 255
 // MIPS64EL:#define __UINT8_TYPE__ unsigned char
-// MIPS64EL:#define __UINTMAX_C_SUFFIX__ ULL
-// MIPS64EL:#define __UINTMAX_MAX__ 18446744073709551615ULL
-// MIPS64EL:#define __UINTMAX_TYPE__ long long unsigned int
+// MIPS64EL:#define __UINTMAX_C_SUFFIX__ UL
+// MIPS64EL:#define __UINTMAX_MAX__ 18446744073709551615UL
+// MIPS64EL:#define __UINTMAX_TYPE__ long unsigned int
 // MIPS64EL:#define __UINTMAX_WIDTH__ 64
 // MIPS64EL:#define __UINTPTR_MAX__ 18446744073709551615UL
 // MIPS64EL:#define __UINTPTR_TYPE__ long unsigned int
@@ -3440,6 +4263,33 @@
 // MIPS-ARCH-32R2:#define _MIPS_ISA _MIPS_ISA_MIPS32
 // MIPS-ARCH-32R2:#define __mips_isa_rev 2
 //
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips-none-none \
+// RUN:            -target-cpu mips32r3 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPS-ARCH-32R3 %s
+//
+// MIPS-ARCH-32R3:#define _MIPS_ARCH "mips32r3"
+// MIPS-ARCH-32R3:#define _MIPS_ARCH_MIPS32R3 1
+// MIPS-ARCH-32R3:#define _MIPS_ISA _MIPS_ISA_MIPS32
+// MIPS-ARCH-32R3:#define __mips_isa_rev 3
+//
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips-none-none \
+// RUN:            -target-cpu mips32r5 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPS-ARCH-32R5 %s
+//
+// MIPS-ARCH-32R5:#define _MIPS_ARCH "mips32r5"
+// MIPS-ARCH-32R5:#define _MIPS_ARCH_MIPS32R5 1
+// MIPS-ARCH-32R5:#define _MIPS_ISA _MIPS_ISA_MIPS32
+// MIPS-ARCH-32R5:#define __mips_isa_rev 5
+//
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips-none-none \
+// RUN:            -target-cpu mips32r6 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPS-ARCH-32R6 %s
+//
+// MIPS-ARCH-32R6:#define _MIPS_ARCH "mips32r6"
+// MIPS-ARCH-32R6:#define _MIPS_ARCH_MIPS32R6 1
+// MIPS-ARCH-32R6:#define _MIPS_ISA _MIPS_ISA_MIPS32
+// MIPS-ARCH-32R6:#define __mips_isa_rev 6
+//
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips64-none-none \
 // RUN:            < /dev/null \
 // RUN:   | FileCheck -check-prefix MIPS-ARCH-DEF64 %s
@@ -3467,6 +4317,33 @@
 // MIPS-ARCH-64R2:#define _MIPS_ISA _MIPS_ISA_MIPS64
 // MIPS-ARCH-64R2:#define __mips_isa_rev 2
 //
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips64-none-none \
+// RUN:            -target-cpu mips64r3 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPS-ARCH-64R3 %s
+//
+// MIPS-ARCH-64R3:#define _MIPS_ARCH "mips64r3"
+// MIPS-ARCH-64R3:#define _MIPS_ARCH_MIPS64R3 1
+// MIPS-ARCH-64R3:#define _MIPS_ISA _MIPS_ISA_MIPS64
+// MIPS-ARCH-64R3:#define __mips_isa_rev 3
+//
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips64-none-none \
+// RUN:            -target-cpu mips64r5 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPS-ARCH-64R5 %s
+//
+// MIPS-ARCH-64R5:#define _MIPS_ARCH "mips64r5"
+// MIPS-ARCH-64R5:#define _MIPS_ARCH_MIPS64R5 1
+// MIPS-ARCH-64R5:#define _MIPS_ISA _MIPS_ISA_MIPS64
+// MIPS-ARCH-64R5:#define __mips_isa_rev 5
+//
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=mips64-none-none \
+// RUN:            -target-cpu mips64r6 < /dev/null \
+// RUN:   | FileCheck -check-prefix MIPS-ARCH-64R6 %s
+//
+// MIPS-ARCH-64R6:#define _MIPS_ARCH "mips64r6"
+// MIPS-ARCH-64R6:#define _MIPS_ARCH_MIPS64R6 1
+// MIPS-ARCH-64R6:#define _MIPS_ISA _MIPS_ISA_MIPS64
+// MIPS-ARCH-64R6:#define __mips_isa_rev 6
+//
 // Check MIPS float ABI macros
 //
 // RUN: %clang_cc1 -E -dM -ffreestanding \
@@ -3581,6 +4458,7 @@
 //
 // MSP430:#define MSP430 1
 // MSP430-NOT:#define _LP64
+// MSP430:#define __BIGGEST_ALIGNMENT__ 2
 // MSP430:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // MSP430:#define __CHAR16_TYPE__ unsigned short
 // MSP430:#define __CHAR32_TYPE__ unsigned int
@@ -3598,7 +4476,7 @@
 // MSP430:#define __DBL_MIN_10_EXP__ (-307)
 // MSP430:#define __DBL_MIN_EXP__ (-1021)
 // MSP430:#define __DBL_MIN__ 2.2250738585072014e-308
-// MSP430:#define __DECIMAL_DIG__ 17
+// MSP430:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // MSP430:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // MSP430:#define __FLT_DIG__ 6
 // MSP430:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -3764,6 +4642,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=nvptx-none-none < /dev/null | FileCheck -check-prefix NVPTX32 %s
 //
 // NVPTX32-NOT:#define _LP64
+// NVPTX32:#define __BIGGEST_ALIGNMENT__ 8
 // NVPTX32:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // NVPTX32:#define __CHAR16_TYPE__ unsigned short
 // NVPTX32:#define __CHAR32_TYPE__ unsigned int
@@ -3782,7 +4661,7 @@
 // NVPTX32:#define __DBL_MIN_10_EXP__ (-307)
 // NVPTX32:#define __DBL_MIN_EXP__ (-1021)
 // NVPTX32:#define __DBL_MIN__ 2.2250738585072014e-308
-// NVPTX32:#define __DECIMAL_DIG__ 17
+// NVPTX32:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // NVPTX32:#define __FINITE_MATH_ONLY__ 0
 // NVPTX32:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // NVPTX32:#define __FLT_DIG__ 6
@@ -3950,6 +4829,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=nvptx64-none-none < /dev/null | FileCheck -check-prefix NVPTX64 %s
 //
 // NVPTX64:#define _LP64 1
+// NVPTX64:#define __BIGGEST_ALIGNMENT__ 8
 // NVPTX64:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // NVPTX64:#define __CHAR16_TYPE__ unsigned short
 // NVPTX64:#define __CHAR32_TYPE__ unsigned int
@@ -3968,7 +4848,7 @@
 // NVPTX64:#define __DBL_MIN_10_EXP__ (-307)
 // NVPTX64:#define __DBL_MIN_EXP__ (-1021)
 // NVPTX64:#define __DBL_MIN__ 2.2250738585072014e-308
-// NVPTX64:#define __DECIMAL_DIG__ 17
+// NVPTX64:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // NVPTX64:#define __FINITE_MATH_ONLY__ 0
 // NVPTX64:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // NVPTX64:#define __FLT_DIG__ 6
@@ -4141,6 +5021,7 @@
 // PPC603E:#define _ARCH_PPCGR 1
 // PPC603E:#define _BIG_ENDIAN 1
 // PPC603E-NOT:#define _LP64
+// PPC603E:#define __BIGGEST_ALIGNMENT__ 8
 // PPC603E:#define __BIG_ENDIAN__ 1
 // PPC603E:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // PPC603E:#define __CHAR16_TYPE__ unsigned short
@@ -4159,7 +5040,7 @@
 // PPC603E:#define __DBL_MIN_10_EXP__ (-307)
 // PPC603E:#define __DBL_MIN_EXP__ (-1021)
 // PPC603E:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC603E:#define __DECIMAL_DIG__ 33
+// PPC603E:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC603E:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC603E:#define __FLT_DIG__ 6
 // PPC603E:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -4338,6 +5219,7 @@
 // PPC64:#define _ARCH_PWR7 1
 // PPC64:#define _BIG_ENDIAN 1
 // PPC64:#define _LP64 1
+// PPC64:#define __BIGGEST_ALIGNMENT__ 8
 // PPC64:#define __BIG_ENDIAN__ 1
 // PPC64:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // PPC64:#define __CHAR16_TYPE__ unsigned short
@@ -4357,7 +5239,7 @@
 // PPC64:#define __DBL_MIN_10_EXP__ (-307)
 // PPC64:#define __DBL_MIN_EXP__ (-1021)
 // PPC64:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC64:#define __DECIMAL_DIG__ 33
+// PPC64:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC64:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC64:#define __FLT_DIG__ 6
 // PPC64:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -4540,6 +5422,7 @@
 // PPC64LE:#define _CALL_ELF 2
 // PPC64LE:#define _LITTLE_ENDIAN 1
 // PPC64LE:#define _LP64 1
+// PPC64LE:#define __BIGGEST_ALIGNMENT__ 8
 // PPC64LE:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // PPC64LE:#define __CHAR16_TYPE__ unsigned short
 // PPC64LE:#define __CHAR32_TYPE__ unsigned int
@@ -4558,7 +5441,7 @@
 // PPC64LE:#define __DBL_MIN_10_EXP__ (-307)
 // PPC64LE:#define __DBL_MIN_EXP__ (-1021)
 // PPC64LE:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC64LE:#define __DECIMAL_DIG__ 33
+// PPC64LE:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC64LE:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC64LE:#define __FLT_DIG__ 6
 // PPC64LE:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -4921,6 +5804,7 @@
 // PPC64-LINUX:#define _ARCH_PPC64 1
 // PPC64-LINUX:#define _BIG_ENDIAN 1
 // PPC64-LINUX:#define _LP64 1
+// PPC64-LINUX:#define __BIGGEST_ALIGNMENT__ 8
 // PPC64-LINUX:#define __BIG_ENDIAN__ 1
 // PPC64-LINUX:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // PPC64-LINUX:#define __CHAR16_TYPE__ unsigned short
@@ -4940,7 +5824,7 @@
 // PPC64-LINUX:#define __DBL_MIN_10_EXP__ (-307)
 // PPC64-LINUX:#define __DBL_MIN_EXP__ (-1021)
 // PPC64-LINUX:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC64-LINUX:#define __DECIMAL_DIG__ 33
+// PPC64-LINUX:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC64-LINUX:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC64-LINUX:#define __FLT_DIG__ 6
 // PPC64-LINUX:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -5125,6 +6009,7 @@
 // PPC:#define _ARCH_PPC 1
 // PPC:#define _BIG_ENDIAN 1
 // PPC-NOT:#define _LP64
+// PPC:#define __BIGGEST_ALIGNMENT__ 8
 // PPC:#define __BIG_ENDIAN__ 1
 // PPC:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // PPC:#define __CHAR16_TYPE__ unsigned short
@@ -5144,7 +6029,7 @@
 // PPC:#define __DBL_MIN_10_EXP__ (-307)
 // PPC:#define __DBL_MIN_EXP__ (-1021)
 // PPC:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC:#define __DECIMAL_DIG__ 33
+// PPC:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC:#define __FLT_DIG__ 6
 // PPC:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -5315,6 +6200,7 @@
 // PPC-LINUX:#define _ARCH_PPC 1
 // PPC-LINUX:#define _BIG_ENDIAN 1
 // PPC-LINUX-NOT:#define _LP64
+// PPC-LINUX:#define __BIGGEST_ALIGNMENT__ 8
 // PPC-LINUX:#define __BIG_ENDIAN__ 1
 // PPC-LINUX:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // PPC-LINUX:#define __CHAR16_TYPE__ unsigned short
@@ -5334,7 +6220,7 @@
 // PPC-LINUX:#define __DBL_MIN_10_EXP__ (-307)
 // PPC-LINUX:#define __DBL_MIN_EXP__ (-1021)
 // PPC-LINUX:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC-LINUX:#define __DECIMAL_DIG__ 33
+// PPC-LINUX:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC-LINUX:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC-LINUX:#define __FLT_DIG__ 6
 // PPC-LINUX:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -5506,6 +6392,7 @@
 //
 // PPC-DARWIN:#define _ARCH_PPC 1
 // PPC-DARWIN:#define _BIG_ENDIAN 1
+// PPC-DARWIN:#define __BIGGEST_ALIGNMENT__ 16
 // PPC-DARWIN:#define __BIG_ENDIAN__ 1
 // PPC-DARWIN:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // PPC-DARWIN:#define __CHAR16_TYPE__ unsigned short
@@ -5524,7 +6411,7 @@
 // PPC-DARWIN:#define __DBL_MIN_10_EXP__ (-307)
 // PPC-DARWIN:#define __DBL_MIN_EXP__ (-1021)
 // PPC-DARWIN:#define __DBL_MIN__ 2.2250738585072014e-308
-// PPC-DARWIN:#define __DECIMAL_DIG__ 33
+// PPC-DARWIN:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // PPC-DARWIN:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // PPC-DARWIN:#define __FLT_DIG__ 6
 // PPC-DARWIN:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -5699,6 +6586,7 @@
 //
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=s390x-none-none -fno-signed-char < /dev/null | FileCheck -check-prefix S390X %s
 //
+// S390X:#define __BIGGEST_ALIGNMENT__ 8
 // S390X:#define __CHAR16_TYPE__ unsigned short
 // S390X:#define __CHAR32_TYPE__ unsigned int
 // S390X:#define __CHAR_BIT__ 8
@@ -5716,7 +6604,7 @@
 // S390X:#define __DBL_MIN_10_EXP__ (-307)
 // S390X:#define __DBL_MIN_EXP__ (-1021)
 // S390X:#define __DBL_MIN__ 2.2250738585072014e-308
-// S390X:#define __DECIMAL_DIG__ 36
+// S390X:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // S390X:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // S390X:#define __FLT_DIG__ 6
 // S390X:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -5880,6 +6768,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=sparc-none-none < /dev/null | FileCheck -check-prefix SPARC %s
 //
 // SPARC-NOT:#define _LP64
+// SPARC:#define __BIGGEST_ALIGNMENT__ 8
 // SPARC:#define __BIG_ENDIAN__ 1
 // SPARC:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // SPARC:#define __CHAR16_TYPE__ unsigned short
@@ -5898,7 +6787,7 @@
 // SPARC:#define __DBL_MIN_10_EXP__ (-307)
 // SPARC:#define __DBL_MIN_EXP__ (-1021)
 // SPARC:#define __DBL_MIN__ 2.2250738585072014e-308
-// SPARC:#define __DECIMAL_DIG__ 17
+// SPARC:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // SPARC:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // SPARC:#define __FLT_DIG__ 6
 // SPARC:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -6067,6 +6956,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=tce-none-none < /dev/null | FileCheck -check-prefix TCE %s
 //
 // TCE-NOT:#define _LP64
+// TCE:#define __BIGGEST_ALIGNMENT__ 4
 // TCE:#define __BIG_ENDIAN__ 1
 // TCE:#define __BYTE_ORDER__ __ORDER_BIG_ENDIAN__
 // TCE:#define __CHAR16_TYPE__ unsigned short
@@ -6085,7 +6975,7 @@
 // TCE:#define __DBL_MIN_10_EXP__ (-37)
 // TCE:#define __DBL_MIN_EXP__ (-125)
 // TCE:#define __DBL_MIN__ 1.17549435e-38
-// TCE:#define __DECIMAL_DIG__ -1
+// TCE:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // TCE:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // TCE:#define __FLT_DIG__ 6
 // TCE:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -6234,6 +7124,7 @@
 //
 // X86_64:#define _LP64 1
 // X86_64-NOT:#define _LP32 1
+// X86_64:#define __BIGGEST_ALIGNMENT__ 16
 // X86_64:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // X86_64:#define __CHAR16_TYPE__ unsigned short
 // X86_64:#define __CHAR32_TYPE__ unsigned int
@@ -6251,7 +7142,7 @@
 // X86_64:#define __DBL_MIN_10_EXP__ (-307)
 // X86_64:#define __DBL_MIN_EXP__ (-1021)
 // X86_64:#define __DBL_MIN__ 2.2250738585072014e-308
-// X86_64:#define __DECIMAL_DIG__ 21
+// X86_64:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // X86_64:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // X86_64:#define __FLT_DIG__ 6
 // X86_64:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -6435,6 +7326,7 @@
 //
 // X32:#define _ILP32 1
 // X32-NOT:#define _LP64 1
+// X32:#define __BIGGEST_ALIGNMENT__ 16
 // X32:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // X32:#define __CHAR16_TYPE__ unsigned short
 // X32:#define __CHAR32_TYPE__ unsigned int
@@ -6452,7 +7344,7 @@
 // X32:#define __DBL_MIN_10_EXP__ (-307)
 // X32:#define __DBL_MIN_EXP__ (-1021)
 // X32:#define __DBL_MIN__ 2.2250738585072014e-308
-// X32:#define __DECIMAL_DIG__ 21
+// X32:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // X32:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // X32:#define __FLT_DIG__ 6
 // X32:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -6628,6 +7520,7 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=x86_64-pc-linux-gnu < /dev/null | FileCheck -check-prefix X86_64-LINUX %s
 //
 // X86_64-LINUX:#define _LP64 1
+// X86_64-LINUX:#define __BIGGEST_ALIGNMENT__ 16
 // X86_64-LINUX:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // X86_64-LINUX:#define __CHAR16_TYPE__ unsigned short
 // X86_64-LINUX:#define __CHAR32_TYPE__ unsigned int
@@ -6645,7 +7538,7 @@
 // X86_64-LINUX:#define __DBL_MIN_10_EXP__ (-307)
 // X86_64-LINUX:#define __DBL_MIN_EXP__ (-1021)
 // X86_64-LINUX:#define __DBL_MIN__ 2.2250738585072014e-308
-// X86_64-LINUX:#define __DECIMAL_DIG__ 21
+// X86_64-LINUX:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // X86_64-LINUX:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // X86_64-LINUX:#define __FLT_DIG__ 6
 // X86_64-LINUX:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -6819,13 +7712,17 @@
 //
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=x86_64-unknown-freebsd9.1 < /dev/null | FileCheck -check-prefix X86_64-FREEBSD %s
 //
+// X86_64-FREEBSD:#define __DBL_DECIMAL_DIG__ 17
+// X86_64-FREEBSD:#define __FLT_DECIMAL_DIG__ 9
 // X86_64-FREEBSD:#define __FreeBSD__ 9
 // X86_64-FREEBSD:#define __FreeBSD_cc_version 900001
+// X86_64-FREEBSD:#define __LDBL_DECIMAL_DIG__ 21
 // X86_64-FREEBSD:#define __STDC_MB_MIGHT_NEQ_WC__ 1
 //
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=x86_64-netbsd < /dev/null | FileCheck -check-prefix X86_64-NETBSD %s
 //
 // X86_64-NETBSD:#define _LP64 1
+// X86_64-NETBSD:#define __BIGGEST_ALIGNMENT__ 16
 // X86_64-NETBSD:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
 // X86_64-NETBSD:#define __CHAR16_TYPE__ unsigned short
 // X86_64-NETBSD:#define __CHAR32_TYPE__ unsigned int
@@ -6843,7 +7740,7 @@
 // X86_64-NETBSD:#define __DBL_MIN_10_EXP__ (-307)
 // X86_64-NETBSD:#define __DBL_MIN_EXP__ (-1021)
 // X86_64-NETBSD:#define __DBL_MIN__ 2.2250738585072014e-308
-// X86_64-NETBSD:#define __DECIMAL_DIG__ 21
+// X86_64-NETBSD:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
 // X86_64-NETBSD:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // X86_64-NETBSD:#define __FLT_DIG__ 6
 // X86_64-NETBSD:#define __FLT_EPSILON__ 1.19209290e-7F
@@ -7015,6 +7912,119 @@
 // X86_64-NETBSD:#define __x86_64 1
 // X86_64-NETBSD:#define __x86_64__ 1
 //
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=x86_64-scei-ps4 < /dev/null | FileCheck -check-prefix PS4 %s
+//
+// PS4:#define _LP64 1
+// PS4:#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
+// PS4:#define __CHAR16_TYPE__ unsigned short
+// PS4:#define __CHAR32_TYPE__ unsigned int
+// PS4:#define __CHAR_BIT__ 8
+// PS4:#define __DBL_DENORM_MIN__ 4.9406564584124654e-324
+// PS4:#define __DBL_DIG__ 15
+// PS4:#define __DBL_EPSILON__ 2.2204460492503131e-16
+// PS4:#define __DBL_HAS_DENORM__ 1
+// PS4:#define __DBL_HAS_INFINITY__ 1
+// PS4:#define __DBL_HAS_QUIET_NAN__ 1
+// PS4:#define __DBL_MANT_DIG__ 53
+// PS4:#define __DBL_MAX_10_EXP__ 308
+// PS4:#define __DBL_MAX_EXP__ 1024
+// PS4:#define __DBL_MAX__ 1.7976931348623157e+308
+// PS4:#define __DBL_MIN_10_EXP__ (-307)
+// PS4:#define __DBL_MIN_EXP__ (-1021)
+// PS4:#define __DBL_MIN__ 2.2250738585072014e-308
+// PS4:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
+// PS4:#define __ELF__ 1
+// PS4:#define __FLT_DENORM_MIN__ 1.40129846e-45F
+// PS4:#define __FLT_DIG__ 6
+// PS4:#define __FLT_EPSILON__ 1.19209290e-7F
+// PS4:#define __FLT_EVAL_METHOD__ 0
+// PS4:#define __FLT_HAS_DENORM__ 1
+// PS4:#define __FLT_HAS_INFINITY__ 1
+// PS4:#define __FLT_HAS_QUIET_NAN__ 1
+// PS4:#define __FLT_MANT_DIG__ 24
+// PS4:#define __FLT_MAX_10_EXP__ 38
+// PS4:#define __FLT_MAX_EXP__ 128
+// PS4:#define __FLT_MAX__ 3.40282347e+38F
+// PS4:#define __FLT_MIN_10_EXP__ (-37)
+// PS4:#define __FLT_MIN_EXP__ (-125)
+// PS4:#define __FLT_MIN__ 1.17549435e-38F
+// PS4:#define __FLT_RADIX__ 2
+// PS4:#define __FreeBSD__ 9
+// PS4:#define __FreeBSD_cc_version 900001
+// PS4:#define __INT16_TYPE__ short
+// PS4:#define __INT32_TYPE__ int
+// PS4:#define __INT64_C_SUFFIX__ L
+// PS4:#define __INT64_TYPE__ long int
+// PS4:#define __INT8_TYPE__ signed char
+// PS4:#define __INTMAX_MAX__ 9223372036854775807L
+// PS4:#define __INTMAX_TYPE__ long int
+// PS4:#define __INTMAX_WIDTH__ 64
+// PS4:#define __INTPTR_TYPE__ long int
+// PS4:#define __INTPTR_WIDTH__ 64
+// PS4:#define __INT_MAX__ 2147483647
+// PS4:#define __KPRINTF_ATTRIBUTE__ 1
+// PS4:#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
+// PS4:#define __LDBL_DIG__ 18
+// PS4:#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
+// PS4:#define __LDBL_HAS_DENORM__ 1
+// PS4:#define __LDBL_HAS_INFINITY__ 1
+// PS4:#define __LDBL_HAS_QUIET_NAN__ 1
+// PS4:#define __LDBL_MANT_DIG__ 64
+// PS4:#define __LDBL_MAX_10_EXP__ 4932
+// PS4:#define __LDBL_MAX_EXP__ 16384
+// PS4:#define __LDBL_MAX__ 1.18973149535723176502e+4932L
+// PS4:#define __LDBL_MIN_10_EXP__ (-4931)
+// PS4:#define __LDBL_MIN_EXP__ (-16381)
+// PS4:#define __LDBL_MIN__ 3.36210314311209350626e-4932L
+// PS4:#define __LITTLE_ENDIAN__ 1
+// PS4:#define __LONG_LONG_MAX__ 9223372036854775807LL
+// PS4:#define __LONG_MAX__ 9223372036854775807L
+// PS4:#define __LP64__ 1
+// PS4:#define __MMX__ 1
+// PS4:#define __NO_MATH_INLINES 1
+// PS4:#define __POINTER_WIDTH__ 64
+// PS4:#define __PS4__ 1
+// PS4:#define __PTRDIFF_MAX__ 9223372036854775807L
+// PS4:#define __PTRDIFF_TYPE__ long int
+// PS4:#define __PTRDIFF_WIDTH__ 64
+// PS4:#define __REGISTER_PREFIX__ 
+// PS4:#define __SCHAR_MAX__ 127
+// PS4:#define __SHRT_MAX__ 32767
+// PS4:#define __SIG_ATOMIC_MAX__ 2147483647
+// PS4:#define __SIG_ATOMIC_WIDTH__ 32
+// PS4:#define __SIZEOF_DOUBLE__ 8
+// PS4:#define __SIZEOF_FLOAT__ 4
+// PS4:#define __SIZEOF_INT__ 4
+// PS4:#define __SIZEOF_LONG_DOUBLE__ 16
+// PS4:#define __SIZEOF_LONG_LONG__ 8
+// PS4:#define __SIZEOF_LONG__ 8
+// PS4:#define __SIZEOF_POINTER__ 8
+// PS4:#define __SIZEOF_PTRDIFF_T__ 8
+// PS4:#define __SIZEOF_SHORT__ 2
+// PS4:#define __SIZEOF_SIZE_T__ 8
+// PS4:#define __SIZEOF_WCHAR_T__ 2
+// PS4:#define __SIZEOF_WINT_T__ 4
+// PS4:#define __SIZE_TYPE__ long unsigned int
+// PS4:#define __SIZE_WIDTH__ 64
+// PS4:#define __SSE2_MATH__ 1
+// PS4:#define __SSE2__ 1
+// PS4:#define __SSE_MATH__ 1
+// PS4:#define __SSE__ 1
+// PS4:#define __UINTMAX_TYPE__ long unsigned int
+// PS4:#define __USER_LABEL_PREFIX__
+// PS4:#define __WCHAR_MAX__ 65535
+// PS4:#define __WCHAR_TYPE__ unsigned short
+// PS4:#define __WCHAR_UNSIGNED__ 1
+// PS4:#define __WCHAR_WIDTH__ 16
+// PS4:#define __WINT_TYPE__ int
+// PS4:#define __WINT_WIDTH__ 32
+// PS4:#define __amd64 1
+// PS4:#define __amd64__ 1
+// PS4:#define __unix 1
+// PS4:#define __unix__ 1
+// PS4:#define __x86_64 1
+// PS4:#define __x86_64__ 1
+//
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=sparc64-none-none < /dev/null | FileCheck -check-prefix SPARCV9 %s
 // SPARCV9:#define __INT64_TYPE__ long int
 // SPARCV9:#define __INTMAX_C_SUFFIX__ L
diff --git a/test/Preprocessor/iwithprefix.c b/test/Preprocessor/iwithprefix.c
index 59935ac..a65a804 100644
--- a/test/Preprocessor/iwithprefix.c
+++ b/test/Preprocessor/iwithprefix.c
@@ -9,7 +9,7 @@
 
 // CHECK: #include <...> search starts here:
 // CHECK: {{.*}}.tmps/first
-// CHECK: {{/|\\}}lib{{/|\\}}clang{{/|\\}}{{[.0-9]+}}{{/|\\}}include
+// CHECK: {{/|\\}}lib{{(32|64)?}}{{/|\\}}clang{{/|\\}}{{[.0-9]+}}{{/|\\}}include
 // CHECK: {{.*}}.tmps/second
 // CHECK-NOT: {{.*}}.tmps
 
diff --git a/test/Preprocessor/macro-reserved-cxx11.cpp b/test/Preprocessor/macro-reserved-cxx11.cpp
new file mode 100644
index 0000000..a740ff6
--- /dev/null
+++ b/test/Preprocessor/macro-reserved-cxx11.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -pedantic -verify %s
+
+#define for 0    // expected-warning {{keyword is hidden by macro definition}}
+#define final 1  // expected-warning {{keyword is hidden by macro definition}}
+#define override // expected-warning {{keyword is hidden by macro definition}}
+
+int x;
diff --git a/test/Preprocessor/macro-reserved-ms.c b/test/Preprocessor/macro-reserved-ms.c
new file mode 100644
index 0000000..c533ee3
--- /dev/null
+++ b/test/Preprocessor/macro-reserved-ms.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -fms-extensions -verify %s
+// expected-no-diagnostics
+
+#define inline _inline
+#undef  inline
+
+int x;
diff --git a/test/Preprocessor/macro-reserved.c b/test/Preprocessor/macro-reserved.c
new file mode 100644
index 0000000..84b9262
--- /dev/null
+++ b/test/Preprocessor/macro-reserved.c
@@ -0,0 +1,64 @@
+// RUN: %clang_cc1 -fsyntax-only -pedantic -verify %s
+
+#define for 0    // expected-warning {{keyword is hidden by macro definition}}
+#define final 1
+#define __HAVE_X 0
+#define __cplusplus
+#define _HAVE_X 0
+#define X__Y
+
+#undef for
+#undef final
+#undef __HAVE_X
+#undef __cplusplus
+#undef _HAVE_X
+#undef X__Y
+
+// whitelisted definitions
+#define while while
+#define const
+#define static
+#define extern
+#define inline
+
+#undef while
+#undef const
+#undef static
+#undef extern
+#undef inline
+
+#define inline __inline
+#undef  inline
+#define inline __inline__
+#undef  inline
+
+#define inline inline__  // expected-warning {{keyword is hidden by macro definition}}
+#undef  inline
+#define extern __inline  // expected-warning {{keyword is hidden by macro definition}}
+#undef  extern
+#define extern __extern	 // expected-warning {{keyword is hidden by macro definition}}
+#undef  extern
+#define extern __extern__ // expected-warning {{keyword is hidden by macro definition}}
+#undef  extern
+
+#define inline _inline   // expected-warning {{keyword is hidden by macro definition}}
+#undef  inline
+#define volatile   // expected-warning {{keyword is hidden by macro definition}}
+#undef  volatile
+
+#pragma clang diagnostic warning "-Wreserved-id-macro"
+
+#define switch if  // expected-warning {{keyword is hidden by macro definition}}
+#define final 1
+#define __clusplus // expected-warning {{macro name is a reserved identifier}}
+#define __HAVE_X 0 // expected-warning {{macro name is a reserved identifier}}
+#define _HAVE_X 0  // expected-warning {{macro name is a reserved identifier}}
+#define X__Y
+
+#undef switch
+#undef final
+#undef __cplusplus // expected-warning {{macro name is a reserved identifier}}
+#undef _HAVE_X     // expected-warning {{macro name is a reserved identifier}}
+#undef X__Y
+
+int x;
diff --git a/test/Preprocessor/macro-reserved.cpp b/test/Preprocessor/macro-reserved.cpp
new file mode 100644
index 0000000..ba1594a
--- /dev/null
+++ b/test/Preprocessor/macro-reserved.cpp
@@ -0,0 +1,63 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -pedantic %s
+
+#define for 0    // expected-warning {{keyword is hidden by macro definition}}
+#define final 1
+#define __HAVE_X 0
+#define _HAVE_X 0
+#define X__Y
+
+#undef for
+#undef final
+#undef __HAVE_X
+#undef _HAVE_X
+#undef X__Y
+
+#undef __cplusplus
+#define __cplusplus
+
+// whitelisted definitions
+#define while while
+#define const
+#define static
+#define extern
+#define inline
+
+#undef while
+#undef const
+#undef static
+#undef extern
+#undef inline
+
+#define inline __inline
+#undef  inline
+#define inline __inline__
+#undef  inline
+
+#define inline inline__  // expected-warning {{keyword is hidden by macro definition}}
+#undef  inline
+#define extern __inline  // expected-warning {{keyword is hidden by macro definition}}
+#undef  extern
+#define extern __extern	 // expected-warning {{keyword is hidden by macro definition}}
+#undef  extern
+#define extern __extern__ // expected-warning {{keyword is hidden by macro definition}}
+#undef  extern
+
+#define inline _inline   // expected-warning {{keyword is hidden by macro definition}}
+#undef  inline
+#define volatile   // expected-warning {{keyword is hidden by macro definition}}
+#undef  volatile
+
+
+#pragma clang diagnostic warning "-Wreserved-id-macro"
+
+#define switch if  // expected-warning {{keyword is hidden by macro definition}}
+#define final 1
+#define __HAVE_X 0 // expected-warning {{macro name is a reserved identifier}}
+#define _HAVE_X 0  // expected-warning {{macro name is a reserved identifier}}
+#define X__Y       // expected-warning {{macro name is a reserved identifier}}
+
+#undef __cplusplus // expected-warning {{macro name is a reserved identifier}}
+#undef _HAVE_X     // expected-warning {{macro name is a reserved identifier}}
+#undef X__Y        // expected-warning {{macro name is a reserved identifier}}
+
+int x;
diff --git a/test/Preprocessor/macro_arg_directive.c b/test/Preprocessor/macro_arg_directive.c
index 5bc2236..21d1b20 100644
--- a/test/Preprocessor/macro_arg_directive.c
+++ b/test/Preprocessor/macro_arg_directive.c
@@ -7,6 +7,11 @@
   a);
 _Static_assert(n == 5, "");
 
+#define M(A)
+M(
+#pragma pack(pop) // expected-error {{embedding a #pragma directive within macro arguments is not supported}}
+)
+
 // header1.h
 void fail(const char *);
 #define MUNCH(...) \
diff --git a/test/Preprocessor/pr19649-signed-wchar_t.c b/test/Preprocessor/pr19649-signed-wchar_t.c
new file mode 100644
index 0000000..f76f431
--- /dev/null
+++ b/test/Preprocessor/pr19649-signed-wchar_t.c
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -triple powerpc64-unknown-linux-gnu -E -x c %s
+// RUN: %clang_cc1 -triple powerpc64-unknown-linux-gnu -E -fno-signed-char -x c %s
+
+#if (L'\0' - 1 > 0)
+# error "Unexpected expression evaluation result"
+#endif
diff --git a/test/Preprocessor/pr19649-unsigned-wchar_t.c b/test/Preprocessor/pr19649-unsigned-wchar_t.c
new file mode 100644
index 0000000..4bbe1b5
--- /dev/null
+++ b/test/Preprocessor/pr19649-unsigned-wchar_t.c
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -triple i386-pc-cygwin -E -x c %s
+// RUN: %clang_cc1 -triple powerpc64-unknown-linux-gnu -E -fshort-wchar -x c %s
+
+#if (L'\0' - 1 < 0)
+# error "Unexpected expression evaluation result"
+#endif
diff --git a/test/Preprocessor/stdint.c b/test/Preprocessor/stdint.c
index c7189f6..9bc1aa7 100644
--- a/test/Preprocessor/stdint.c
+++ b/test/Preprocessor/stdint.c
@@ -322,8 +322,8 @@
 //
 // RUN: %clang_cc1 -E -ffreestanding -triple=mips64-none-none %s | FileCheck -check-prefix MIPS64 %s
 //
-// MIPS64:typedef long long int int64_t;
-// MIPS64:typedef long long unsigned int uint64_t;
+// MIPS64:typedef long int int64_t;
+// MIPS64:typedef long unsigned int uint64_t;
 // MIPS64:typedef int64_t int_least64_t;
 // MIPS64:typedef uint64_t uint_least64_t;
 // MIPS64:typedef int64_t int_fast64_t;
@@ -353,8 +353,8 @@
 // MIPS64:typedef int64_t intptr_t;
 // MIPS64:typedef uint64_t uintptr_t;
 //
-// MIPS64:typedef long long int intmax_t;
-// MIPS64:typedef long long unsigned int uintmax_t;
+// MIPS64:typedef long int intmax_t;
+// MIPS64:typedef long unsigned int uintmax_t;
 //
 // MIPS64:INT8_MAX_ 127
 // MIPS64:INT8_MIN_ (-127 -1)
@@ -386,26 +386,26 @@
 // MIPS64:INT_FAST32_MAX_ 2147483647
 // MIPS64:UINT_FAST32_MAX_ 4294967295U
 //
-// MIPS64:INT64_MAX_ 9223372036854775807LL
-// MIPS64:INT64_MIN_ (-9223372036854775807LL -1)
-// MIPS64:UINT64_MAX_ 18446744073709551615ULL
-// MIPS64:INT_LEAST64_MIN_ (-9223372036854775807LL -1)
-// MIPS64:INT_LEAST64_MAX_ 9223372036854775807LL
-// MIPS64:UINT_LEAST64_MAX_ 18446744073709551615ULL
-// MIPS64:INT_FAST64_MIN_ (-9223372036854775807LL -1)
-// MIPS64:INT_FAST64_MAX_ 9223372036854775807LL
-// MIPS64:UINT_FAST64_MAX_ 18446744073709551615ULL
+// MIPS64:INT64_MAX_ 9223372036854775807L
+// MIPS64:INT64_MIN_ (-9223372036854775807L -1)
+// MIPS64:UINT64_MAX_ 18446744073709551615UL
+// MIPS64:INT_LEAST64_MIN_ (-9223372036854775807L -1)
+// MIPS64:INT_LEAST64_MAX_ 9223372036854775807L
+// MIPS64:UINT_LEAST64_MAX_ 18446744073709551615UL
+// MIPS64:INT_FAST64_MIN_ (-9223372036854775807L -1)
+// MIPS64:INT_FAST64_MAX_ 9223372036854775807L
+// MIPS64:UINT_FAST64_MAX_ 18446744073709551615UL
 //
-// MIPS64:INTPTR_MIN_ (-9223372036854775807LL -1)
-// MIPS64:INTPTR_MAX_ 9223372036854775807LL
-// MIPS64:UINTPTR_MAX_ 18446744073709551615ULL
-// MIPS64:PTRDIFF_MIN_ (-9223372036854775807LL -1)
-// MIPS64:PTRDIFF_MAX_ 9223372036854775807LL
-// MIPS64:SIZE_MAX_ 18446744073709551615ULL
+// MIPS64:INTPTR_MIN_ (-9223372036854775807L -1)
+// MIPS64:INTPTR_MAX_ 9223372036854775807L
+// MIPS64:UINTPTR_MAX_ 18446744073709551615UL
+// MIPS64:PTRDIFF_MIN_ (-9223372036854775807L -1)
+// MIPS64:PTRDIFF_MAX_ 9223372036854775807L
+// MIPS64:SIZE_MAX_ 18446744073709551615UL
 //
-// MIPS64:INTMAX_MIN_ (-9223372036854775807LL -1)
-// MIPS64:INTMAX_MAX_ 9223372036854775807LL
-// MIPS64:UINTMAX_MAX_ 18446744073709551615ULL
+// MIPS64:INTMAX_MIN_ (-9223372036854775807L -1)
+// MIPS64:INTMAX_MAX_ 9223372036854775807L
+// MIPS64:UINTMAX_MAX_ 18446744073709551615UL
 //
 // MIPS64:SIG_ATOMIC_MIN_ (-2147483647 -1)
 // MIPS64:SIG_ATOMIC_MAX_ 2147483647
@@ -421,11 +421,11 @@
 // MIPS64:UINT16_C_(0) 0U
 // MIPS64:INT32_C_(0) 0
 // MIPS64:UINT32_C_(0) 0U
-// MIPS64:INT64_C_(0) 0LL
-// MIPS64:UINT64_C_(0) 0ULL
+// MIPS64:INT64_C_(0) 0L
+// MIPS64:UINT64_C_(0) 0UL
 //
-// MIPS64:INTMAX_C_(0) 0LL
-// MIPS64:UINTMAX_C_(0) 0ULL
+// MIPS64:INTMAX_C_(0) 0L
+// MIPS64:UINTMAX_C_(0) 0UL
 //
 // RUN: %clang_cc1 -E -ffreestanding -triple=msp430-none-none %s | FileCheck -check-prefix MSP430 %s
 //
diff --git a/test/Profile/c-captured.c b/test/Profile/c-captured.c
index ef7fb31..8a9e069 100644
--- a/test/Profile/c-captured.c
+++ b/test/Profile/c-captured.c
@@ -4,8 +4,8 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-captured.c %s -o - -emit-llvm -fprofile-instr-use=%t.profdata | FileCheck -check-prefix=PGOUSE -check-prefix=PGOALL %s
 
 // PGOGEN: @[[DCC:__llvm_profile_counters_debug_captured]] = hidden global [3 x i64] zeroinitializer
-// PGOGEN: @[[CSC:__llvm_profile_counters___captured_stmt]] = internal global [2 x i64] zeroinitializer
-// PGOGEN: @[[C1C:__llvm_profile_counters___captured_stmt1]] = internal global [3 x i64] zeroinitializer
+// PGOGEN: @[[CSC:"__llvm_profile_counters_c-captured.c:__captured_stmt"]] = internal global [2 x i64] zeroinitializer
+// PGOGEN: @[[C1C:"__llvm_profile_counters_c-captured.c:__captured_stmt1"]] = internal global [3 x i64] zeroinitializer
 
 // PGOALL-LABEL: define void @debug_captured()
 // PGOGEN: store {{.*}} @[[DCC]], i64 0, i64 0
@@ -47,11 +47,11 @@
   if (x) {} // This is DC2. Checked above.
 }
 
-// PGOUSE-DAG: ![[DC1]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[DC2]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[CS1]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[C11]] = metadata !{metadata !"branch_weights", i32 11, i32 2}
-// PGOUSE-DAG: ![[C12]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[DC1]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[DC2]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[CS1]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[C11]] = !{!"branch_weights", i32 11, i32 2}
+// PGOUSE-DAG: ![[C12]] = !{!"branch_weights", i32 2, i32 1}
 
 int main(int argc, const char *argv[]) {
   debug_captured();
diff --git a/test/Profile/c-counter-overflows.c b/test/Profile/c-counter-overflows.c
index f6f8f73..18a3d33 100644
--- a/test/Profile/c-counter-overflows.c
+++ b/test/Profile/c-counter-overflows.c
@@ -44,6 +44,6 @@
   return 0;
 }
 
-// CHECK-DAG: ![[FOR]] = metadata !{metadata !"branch_weights", i32 -252645135, i32 1}
-// CHECK-DAG: ![[IF]]  = metadata !{metadata !"branch_weights", i32 -268435456, i32 268435456}
-// CHECK-DAG: ![[SWITCH]] = metadata !{metadata !"branch_weights", i32 715827883, i32 -715827883, i32 -715827883, i32 -715827883}
+// CHECK-DAG: ![[FOR]] = !{!"branch_weights", i32 -252645135, i32 1}
+// CHECK-DAG: ![[IF]]  = !{!"branch_weights", i32 -268435456, i32 268435456}
+// CHECK-DAG: ![[SWITCH]] = !{!"branch_weights", i32 715827883, i32 -715827883, i32 -715827883, i32 -715827883}
diff --git a/test/Profile/c-general.c b/test/Profile/c-general.c
index 79707ad..981fd98 100644
--- a/test/Profile/c-general.c
+++ b/test/Profile/c-general.c
@@ -18,7 +18,7 @@
 // PGOGEN: @[[BLC:__llvm_profile_counters_boolop_loops]] = hidden global [9 x i64] zeroinitializer
 // PGOGEN: @[[COC:__llvm_profile_counters_conditional_operator]] = hidden global [3 x i64] zeroinitializer
 // PGOGEN: @[[MAC:__llvm_profile_counters_main]] = hidden global [1 x i64] zeroinitializer
-// PGOGEN: @[[STC:__llvm_profile_counters_static_func]] = internal global [2 x i64] zeroinitializer
+// PGOGEN: @[[STC:"__llvm_profile_counters_c-general.c:static_func"]] = internal global [2 x i64] zeroinitializer
 
 // PGOGEN-LABEL: @simple_loops()
 // PGOUSE-LABEL: @simple_loops()
@@ -459,77 +459,77 @@
   }
 }
 
-// PGOUSE-DAG: ![[SL1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
-// PGOUSE-DAG: ![[SL2]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
-// PGOUSE-DAG: ![[SL3]] = metadata !{metadata !"branch_weights", i32 76, i32 2}
+// PGOUSE-DAG: ![[SL1]] = !{!"branch_weights", i32 101, i32 2}
+// PGOUSE-DAG: ![[SL2]] = !{!"branch_weights", i32 101, i32 2}
+// PGOUSE-DAG: ![[SL3]] = !{!"branch_weights", i32 76, i32 2}
 
-// PGOUSE-DAG: ![[EE1]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[EE2]] = metadata !{metadata !"branch_weights", i32 52, i32 1}
-// PGOUSE-DAG: ![[EE3]] = metadata !{metadata !"branch_weights", i32 2, i32 51}
-// PGOUSE-DAG: ![[EE4]] = metadata !{metadata !"branch_weights", i32 26, i32 26}
-// PGOUSE-DAG: ![[EE5]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[EE6]] = metadata !{metadata !"branch_weights", i32 2, i32 26}
-// PGOUSE-DAG: ![[EE7]] = metadata !{metadata !"branch_weights", i32 26, i32 1}
+// PGOUSE-DAG: ![[EE1]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[EE2]] = !{!"branch_weights", i32 52, i32 1}
+// PGOUSE-DAG: ![[EE3]] = !{!"branch_weights", i32 2, i32 51}
+// PGOUSE-DAG: ![[EE4]] = !{!"branch_weights", i32 26, i32 26}
+// PGOUSE-DAG: ![[EE5]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[EE6]] = !{!"branch_weights", i32 2, i32 26}
+// PGOUSE-DAG: ![[EE7]] = !{!"branch_weights", i32 26, i32 1}
 
-// PGOUSE-DAG: ![[IF1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
-// PGOUSE-DAG: ![[IF2]] = metadata !{metadata !"branch_weights", i32 51, i32 51}
-// PGOUSE-DAG: ![[IF3]] = metadata !{metadata !"branch_weights", i32 51, i32 1}
-// PGOUSE-DAG: ![[IF4]] = metadata !{metadata !"branch_weights", i32 34, i32 18}
-// PGOUSE-DAG: ![[IF5]] = metadata !{metadata !"branch_weights", i32 34, i32 1}
-// PGOUSE-DAG: ![[IF6]] = metadata !{metadata !"branch_weights", i32 17, i32 2}
-// PGOUSE-DAG: ![[IF7]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
-// PGOUSE-DAG: ![[IF8]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
+// PGOUSE-DAG: ![[IF1]] = !{!"branch_weights", i32 101, i32 2}
+// PGOUSE-DAG: ![[IF2]] = !{!"branch_weights", i32 51, i32 51}
+// PGOUSE-DAG: ![[IF3]] = !{!"branch_weights", i32 51, i32 1}
+// PGOUSE-DAG: ![[IF4]] = !{!"branch_weights", i32 34, i32 18}
+// PGOUSE-DAG: ![[IF5]] = !{!"branch_weights", i32 34, i32 1}
+// PGOUSE-DAG: ![[IF6]] = !{!"branch_weights", i32 17, i32 2}
+// PGOUSE-DAG: ![[IF7]] = !{!"branch_weights", i32 100, i32 2}
+// PGOUSE-DAG: ![[IF8]] = !{!"branch_weights", i32 100, i32 2}
 
-// PGOUSE-DAG: ![[JM1]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[JM2]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[JM3]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[JM4]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[JM5]] = metadata !{metadata !"branch_weights", i32 3, i32 2}
-// PGOUSE-DAG: ![[JM6]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[JM7]] = metadata !{metadata !"branch_weights", i32 1, i32 2, i32 2, i32 2}
-// PGOUSE-DAG: ![[JM8]] = metadata !{metadata !"branch_weights", i32 11, i32 2}
-// PGOUSE-DAG: ![[JM9]] = metadata !{metadata !"branch_weights", i32 10, i32 2}
+// PGOUSE-DAG: ![[JM1]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[JM2]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[JM3]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[JM4]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[JM5]] = !{!"branch_weights", i32 3, i32 2}
+// PGOUSE-DAG: ![[JM6]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[JM7]] = !{!"branch_weights", i32 1, i32 2, i32 2, i32 2}
+// PGOUSE-DAG: ![[JM8]] = !{!"branch_weights", i32 11, i32 2}
+// PGOUSE-DAG: ![[JM9]] = !{!"branch_weights", i32 10, i32 2}
 
-// PGOUSE-DAG: ![[SW1]] = metadata !{metadata !"branch_weights", i32 16, i32 1}
-// PGOUSE-DAG: ![[SW2]] = metadata !{metadata !"branch_weights", i32 6, i32 2, i32 3, i32 4, i32 5}
-// PGOUSE-DAG: ![[SW3]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[SW4]] = metadata !{metadata !"branch_weights", i32 3, i32 2}
-// PGOUSE-DAG: ![[SW5]] = metadata !{metadata !"branch_weights", i32 4, i32 1}
-// PGOUSE-DAG: ![[SW6]] = metadata !{metadata !"branch_weights", i32 5, i32 1}
-// PGOUSE-DAG: ![[SW7]] = metadata !{metadata !"branch_weights", i32 1, i32 2, i32 2, i32 2, i32 2}
-// PGOUSE-DAG: ![[SW8]] = metadata !{metadata !"branch_weights", i32 5, i32 1}
-// PGOUSE-DAG: ![[SW9]] = metadata !{metadata !"branch_weights", i32 2, i32 5}
+// PGOUSE-DAG: ![[SW1]] = !{!"branch_weights", i32 16, i32 1}
+// PGOUSE-DAG: ![[SW2]] = !{!"branch_weights", i32 6, i32 2, i32 3, i32 4, i32 5}
+// PGOUSE-DAG: ![[SW3]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[SW4]] = !{!"branch_weights", i32 3, i32 2}
+// PGOUSE-DAG: ![[SW5]] = !{!"branch_weights", i32 4, i32 1}
+// PGOUSE-DAG: ![[SW6]] = !{!"branch_weights", i32 5, i32 1}
+// PGOUSE-DAG: ![[SW7]] = !{!"branch_weights", i32 1, i32 2, i32 2, i32 2, i32 2}
+// PGOUSE-DAG: ![[SW8]] = !{!"branch_weights", i32 5, i32 1}
+// PGOUSE-DAG: ![[SW9]] = !{!"branch_weights", i32 2, i32 5}
 
-// PGOUSE-DAG: ![[BS1]] = metadata !{metadata !"branch_weights", i32 33, i32 2}
-// PGOUSE-DAG: ![[BS2]] = metadata !{metadata !"branch_weights", i32 29, i32 2, i32 2, i32 2, i32 2, i32 1}
-// PGOUSE-DAG: ![[BS3]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[BS4]] = metadata !{metadata !"branch_weights", i32 2, i32 2}
-// PGOUSE-DAG: ![[BS5]] = metadata !{metadata !"branch_weights", i32 12, i32 1}
-// PGOUSE-DAG: ![[BS6]] = metadata !{metadata !"branch_weights", i32 12, i32 3}
-// PGOUSE-DAG: ![[BS7]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[BS8]] = metadata !{metadata !"branch_weights", i32 16, i32 1}
-// PGOUSE-DAG: ![[BS9]] = metadata !{metadata !"branch_weights", i32 16, i32 14}
-// PGOUSE-DAG: ![[BS10]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[BS11]] = metadata !{metadata !"branch_weights", i32 3, i32 1}
+// PGOUSE-DAG: ![[BS1]] = !{!"branch_weights", i32 33, i32 2}
+// PGOUSE-DAG: ![[BS2]] = !{!"branch_weights", i32 29, i32 2, i32 2, i32 2, i32 2, i32 1}
+// PGOUSE-DAG: ![[BS3]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[BS4]] = !{!"branch_weights", i32 2, i32 2}
+// PGOUSE-DAG: ![[BS5]] = !{!"branch_weights", i32 12, i32 1}
+// PGOUSE-DAG: ![[BS6]] = !{!"branch_weights", i32 12, i32 3}
+// PGOUSE-DAG: ![[BS7]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[BS8]] = !{!"branch_weights", i32 16, i32 1}
+// PGOUSE-DAG: ![[BS9]] = !{!"branch_weights", i32 16, i32 14}
+// PGOUSE-DAG: ![[BS10]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[BS11]] = !{!"branch_weights", i32 3, i32 1}
 
-// PGOUSE-DAG: ![[BO1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
-// PGOUSE-DAG: ![[BO2]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
-// PGOUSE-DAG: ![[BO3]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
-// PGOUSE-DAG: ![[BO4]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
-// PGOUSE-DAG: ![[BO5]] = metadata !{metadata !"branch_weights", i32 18, i32 18}
-// PGOUSE-DAG: ![[BO6]] = metadata !{metadata !"branch_weights", i32 51, i32 51}
-// PGOUSE-DAG: ![[BO7]] = metadata !{metadata !"branch_weights", i32 34, i32 18}
-// PGOUSE-DAG: ![[BL1]] = metadata !{metadata !"branch_weights", i32 52, i32 1}
-// PGOUSE-DAG: ![[BL2]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
-// PGOUSE-DAG: ![[BL3]] = metadata !{metadata !"branch_weights", i32 26, i32 27}
-// PGOUSE-DAG: ![[BL4]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
-// PGOUSE-DAG: ![[BL5]] = metadata !{metadata !"branch_weights", i32 52, i32 1}
-// PGOUSE-DAG: ![[BL6]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
-// PGOUSE-DAG: ![[BL7]] = metadata !{metadata !"branch_weights", i32 26, i32 27}
-// PGOUSE-DAG: ![[BL8]] = metadata !{metadata !"branch_weights", i32 51, i32 2}
-// PGOUSE-DAG: ![[CO1]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// PGOUSE-DAG: ![[CO2]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[ST1]] = metadata !{metadata !"branch_weights", i32 11, i32 2}
+// PGOUSE-DAG: ![[BO1]] = !{!"branch_weights", i32 101, i32 2}
+// PGOUSE-DAG: ![[BO2]] = !{!"branch_weights", i32 67, i32 35}
+// PGOUSE-DAG: ![[BO3]] = !{!"branch_weights", i32 67, i32 35}
+// PGOUSE-DAG: ![[BO4]] = !{!"branch_weights", i32 67, i32 35}
+// PGOUSE-DAG: ![[BO5]] = !{!"branch_weights", i32 18, i32 18}
+// PGOUSE-DAG: ![[BO6]] = !{!"branch_weights", i32 51, i32 51}
+// PGOUSE-DAG: ![[BO7]] = !{!"branch_weights", i32 34, i32 18}
+// PGOUSE-DAG: ![[BL1]] = !{!"branch_weights", i32 52, i32 1}
+// PGOUSE-DAG: ![[BL2]] = !{!"branch_weights", i32 51, i32 2}
+// PGOUSE-DAG: ![[BL3]] = !{!"branch_weights", i32 26, i32 27}
+// PGOUSE-DAG: ![[BL4]] = !{!"branch_weights", i32 51, i32 2}
+// PGOUSE-DAG: ![[BL5]] = !{!"branch_weights", i32 52, i32 1}
+// PGOUSE-DAG: ![[BL6]] = !{!"branch_weights", i32 51, i32 2}
+// PGOUSE-DAG: ![[BL7]] = !{!"branch_weights", i32 26, i32 27}
+// PGOUSE-DAG: ![[BL8]] = !{!"branch_weights", i32 51, i32 2}
+// PGOUSE-DAG: ![[CO1]] = !{!"branch_weights", i32 1, i32 2}
+// PGOUSE-DAG: ![[CO2]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[ST1]] = !{!"branch_weights", i32 11, i32 2}
 
 int main(int argc, const char *argv[]) {
   simple_loops();
diff --git a/test/Profile/c-linkage-available_externally.c b/test/Profile/c-linkage-available_externally.c
index aa1080b..e89632a 100644
--- a/test/Profile/c-linkage-available_externally.c
+++ b/test/Profile/c-linkage-available_externally.c
@@ -2,8 +2,9 @@
 // get thrown out.
 // RUN: %clang_cc1 -O2 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage-available_externally.c %s -o - -emit-llvm -fprofile-instr-generate | FileCheck %s
 
-// CHECK: @__llvm_profile_counters_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
 // CHECK: @__llvm_profile_name_foo = linkonce_odr hidden constant [3 x i8] c"foo", section "__DATA,__llvm_prf_names", align 1
+
+// CHECK: @__llvm_profile_counters_foo = linkonce_odr hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
 // CHECK: @__llvm_profile_data_foo = linkonce_odr hidden constant { i32, i32, i64, i8*, i64* } { i32 3, i32 1, i64 {{[0-9]+}}, i8* getelementptr inbounds ([3 x i8]* @__llvm_profile_name_foo, i32 0, i32 0), i64* getelementptr inbounds ([1 x i64]* @__llvm_profile_counters_foo, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 inline int foo(void) { return 1; }
 
diff --git a/test/Profile/c-linkage.c b/test/Profile/c-linkage.c
index 3b0fa1a..7c2e925 100644
--- a/test/Profile/c-linkage.c
+++ b/test/Profile/c-linkage.c
@@ -1,21 +1,16 @@
-// Check the data structures emitted by instrumentation.
+// Check that the profiling names we create have the linkage we expect
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name c-linkage.c %s -o - -emit-llvm -fprofile-instr-generate | FileCheck %s
 
-// CHECK: @__llvm_profile_runtime = external global i32
-// CHECK: @__llvm_profile_counters_foo = hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name_foo = hidden constant [3 x i8] c"foo", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data_foo = hidden constant { i32, i32, i64, i8*, i64* } { i32 3, i32 1, i64 {{[0-9]+}}, i8* getelementptr inbounds ([3 x i8]* @__llvm_profile_name_foo, i32 0, i32 0), i64* getelementptr inbounds ([1 x i64]* @__llvm_profile_counters_foo, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
+// CHECK: @__llvm_profile_name_foo = hidden constant [3 x i8] c"foo"
+// CHECK: @__llvm_profile_name_foo_weak = weak hidden constant [8 x i8] c"foo_weak"
+// CHECK: @__llvm_profile_name_main = hidden constant [4 x i8] c"main"
+// CHECK: @"__llvm_profile_name_c-linkage.c:foo_internal" = internal constant [24 x i8] c"c-linkage.c:foo_internal"
+
 void foo(void) { }
 
-// CHECK: @__llvm_profile_counters_foo_weak = weak hidden global [5 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name_foo_weak = weak hidden constant [8 x i8] c"foo_weak", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data_foo_weak = weak hidden constant { i32, i32, i64, i8*, i64* } { i32 8, i32 5, i64 {{[0-9]+}}, i8* getelementptr inbounds ([8 x i8]* @__llvm_profile_name_foo_weak, i32 0, i32 0), i64* getelementptr inbounds ([5 x i64]* @__llvm_profile_counters_foo_weak, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 void foo_weak(void) __attribute__((weak));
 void foo_weak(void) { if (0){} if (0){} if (0){} if (0){} }
 
-// CHECK: @__llvm_profile_counters_main = hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name_main = hidden constant [4 x i8] c"main", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data_main = hidden constant { i32, i32, i64, i8*, i64* } { i32 4, i32 1, i64 {{[0-9]+}}, i8* getelementptr inbounds ([4 x i8]* @__llvm_profile_name_main, i32 0, i32 0), i64* getelementptr inbounds ([1 x i64]* @__llvm_profile_counters_main, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 static void foo_internal(void);
 int main(void) {
   foo();
@@ -24,14 +19,4 @@
   return 0;
 }
 
-// CHECK: @__llvm_profile_counters_foo_internal = internal global [3 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name_foo_internal = internal constant [24 x i8] c"c-linkage.c:foo_internal", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data_foo_internal = internal constant { i32, i32, i64, i8*, i64* } { i32 24, i32 3, i64 {{[0-9]+}}, i8* getelementptr inbounds ([24 x i8]* @__llvm_profile_name_foo_internal, i32 0, i32 0), i64* getelementptr inbounds ([3 x i64]* @__llvm_profile_counters_foo_internal, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 static void foo_internal(void) { if (0){} if (0){} }
-
-// CHECK: @llvm.used = appending global [5 x i8*] [i8* bitcast (i32 ()* @__llvm_profile_runtime_user to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data_foo to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data_foo_weak to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data_main to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data_foo_internal to i8*)], section "llvm.metadata"
-
-// CHECK: define linkonce_odr i32 @__llvm_profile_runtime_user() {{.*}} {
-// CHECK:   %[[REG:.*]] = load i32* @__llvm_profile_runtime
-// CHECK:   ret i32 %[[REG]]
-// CHECK: }
diff --git a/test/Profile/c-unreachable-after-switch.c b/test/Profile/c-unreachable-after-switch.c
new file mode 100644
index 0000000..0770437
--- /dev/null
+++ b/test/Profile/c-unreachable-after-switch.c
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -O3 -triple x86_64-apple-macosx10.10 -main-file-name c-unreachable-after-switch.c %s -o - -emit-llvm -fprofile-instr-generate | FileCheck %s
+
+// CHECK: @[[C:__llvm_profile_counters_foo]] = hidden global [3 x i64] zeroinitializer
+
+// CHECK-LABEL: @foo()
+// CHECK: store {{.*}} @[[C]], i64 0, i64 0
+void foo() {
+  // CHECK: store {{.*}} @[[C]], i64 0, i64 2
+  switch (0) {
+  default:
+    return;
+  }
+  // We shouldn't emit the unreachable counter. This used to crash in GlobalDCE.
+  // CHECK-NOT: store {{.*}} @[[SWC]], i64 0, i64 1}
+}
diff --git a/test/Profile/cxx-class.cpp b/test/Profile/cxx-class.cpp
index 1a0c84b..21cbbd6 100644
--- a/test/Profile/cxx-class.cpp
+++ b/test/Profile/cxx-class.cpp
@@ -27,7 +27,7 @@
     // CTRUSE-NOT: br {{.*}} !prof ![0-9]+
     // CTRUSE: ret
   }
-  // CTRUSE: ![[SC1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
+  // CTRUSE: ![[SC1]] = !{!"branch_weights", i32 100, i32 2}
 
   // DTRGEN-LABEL: define {{.*}} @_ZN6SimpleD2Ev(
   // DTRUSE-LABEL: define {{.*}} @_ZN6SimpleD2Ev(
@@ -40,7 +40,7 @@
     // DTRUSE-NOT: br {{.*}} !prof ![0-9]+
     // DTRUSE: ret
   }
-  // DTRUSE: ![[SD1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
+  // DTRUSE: ![[SD1]] = !{!"branch_weights", i32 100, i32 2}
 
   // MTHGEN-LABEL: define {{.*}} @_ZN6Simple6methodEv(
   // MTHUSE-LABEL: define {{.*}} @_ZN6Simple6methodEv(
@@ -53,7 +53,7 @@
     // MTHUSE-NOT: br {{.*}} !prof ![0-9]+
     // MTHUSE: ret
   }
-  // MTHUSE: ![[SM1]] = metadata !{metadata !"branch_weights", i32 100, i32 2}
+  // MTHUSE: ![[SM1]] = !{!"branch_weights", i32 100, i32 2}
 };
 
 // WRPGEN-LABEL: define {{.*}} @_Z14simple_wrapperv(
@@ -70,7 +70,7 @@
   // WRPUSE-NOT: br {{.*}} !prof ![0-9]+
   // WRPUSE: ret
 }
-// WRPUSE: ![[SW1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
+// WRPUSE: ![[SW1]] = !{!"branch_weights", i32 101, i32 2}
 
 int main(int argc, const char *argv[]) {
   simple_wrapper();
diff --git a/test/Profile/cxx-lambda.cpp b/test/Profile/cxx-lambda.cpp
index 6c37a86..ebf7f4c 100644
--- a/test/Profile/cxx-lambda.cpp
+++ b/test/Profile/cxx-lambda.cpp
@@ -11,7 +11,7 @@
 
 // PGOGEN: @[[LWC:__llvm_profile_counters__Z7lambdasv]] = hidden global [4 x i64] zeroinitializer
 // PGOGEN: @[[MAC:__llvm_profile_counters_main]] = hidden global [1 x i64] zeroinitializer
-// LMBGEN: @[[LFC:"__llvm_profile_counters__ZZ7lambdasvENK3\$_0clEi"]] = internal global [3 x i64] zeroinitializer
+// LMBGEN: @[[LFC:"__llvm_profile_counters_cxx-lambda.cpp:_ZZ7lambdasvENK3\$_0clEi"]] = internal global [3 x i64] zeroinitializer
 
 // PGOGEN-LABEL: define void @_Z7lambdasv()
 // PGOUSE-LABEL: define void @_Z7lambdasv()
@@ -45,12 +45,12 @@
   if (i) {}
 }
 
-// PGOUSE-DAG: ![[LW1]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
-// PGOUSE-DAG: ![[LW2]] = metadata !{metadata !"branch_weights", i32 11, i32 2}
-// PGOUSE-DAG: ![[LW3]] = metadata !{metadata !"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[LW1]] = !{!"branch_weights", i32 2, i32 1}
+// PGOUSE-DAG: ![[LW2]] = !{!"branch_weights", i32 11, i32 2}
+// PGOUSE-DAG: ![[LW3]] = !{!"branch_weights", i32 2, i32 1}
 
-// LMBUSE-DAG: ![[LF1]] = metadata !{metadata !"branch_weights", i32 10, i32 2}
-// LMBUSE-DAG: ![[LF2]] = metadata !{metadata !"branch_weights", i32 10, i32 2}
+// LMBUSE-DAG: ![[LF1]] = !{!"branch_weights", i32 10, i32 2}
+// LMBUSE-DAG: ![[LF2]] = !{!"branch_weights", i32 10, i32 2}
 
 int main(int argc, const char *argv[]) {
   lambdas();
diff --git a/test/Profile/cxx-linkage.cpp b/test/Profile/cxx-linkage.cpp
index df896e7..6d07f35 100644
--- a/test/Profile/cxx-linkage.cpp
+++ b/test/Profile/cxx-linkage.cpp
@@ -1,20 +1,15 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9.0 -emit-llvm -main-file-name cxx-linkage.cpp %s -o - -fprofile-instr-generate | FileCheck %s
 
-// CHECK: @__llvm_profile_runtime = external global i32
-// CHECK: @__llvm_profile_counters__Z3foov = hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name__Z3foov = hidden constant [7 x i8] c"_Z3foov", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data__Z3foov = hidden constant { i32, i32, i64, i8*, i64* } { i32 7, i32 1, i64 {{[0-9]+}}, i8* getelementptr inbounds ([7 x i8]* @__llvm_profile_name__Z3foov, i32 0, i32 0), i64* getelementptr inbounds ([1 x i64]* @__llvm_profile_counters__Z3foov, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
+// CHECK: @__llvm_profile_name__Z3foov = hidden constant [7 x i8] c"_Z3foov"
+// CHECK: @__llvm_profile_name__Z8foo_weakv = weak hidden constant [12 x i8] c"_Z8foo_weakv"
+// CHECK: @__llvm_profile_name_main = hidden constant [4 x i8] c"main"
+// CHECK: @__llvm_profile_name__Z10foo_inlinev = linkonce_odr hidden constant [15 x i8] c"_Z10foo_inlinev"
+
 void foo(void) { }
 
-// CHECK: @__llvm_profile_counters__Z8foo_weakv = weak hidden global [5 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name__Z8foo_weakv = weak hidden constant [12 x i8] c"_Z8foo_weakv", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data__Z8foo_weakv = weak hidden constant { i32, i32, i64, i8*, i64* } { i32 12, i32 5, i64 {{[0-9]+}}, i8* getelementptr inbounds ([12 x i8]* @__llvm_profile_name__Z8foo_weakv, i32 0, i32 0), i64* getelementptr inbounds ([5 x i64]* @__llvm_profile_counters__Z8foo_weakv, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 void foo_weak(void) __attribute__((weak));
 void foo_weak(void) { if (0){} if (0){} if (0){} if (0){} }
 
-// CHECK: @__llvm_profile_counters_main = hidden global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name_main = hidden constant [4 x i8] c"main", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data_main = hidden constant { i32, i32, i64, i8*, i64* } { i32 4, i32 1, i64 {{[0-9]+}}, i8* getelementptr inbounds ([4 x i8]* @__llvm_profile_name_main, i32 0, i32 0), i64* getelementptr inbounds ([1 x i64]* @__llvm_profile_counters_main, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 inline void foo_inline(void);
 int main(void) {
   foo();
@@ -23,14 +18,4 @@
   return 0;
 }
 
-// CHECK: @__llvm_profile_counters__Z10foo_inlinev = linkonce_odr hidden global [7 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
-// CHECK: @__llvm_profile_name__Z10foo_inlinev = linkonce_odr hidden constant [15 x i8] c"_Z10foo_inlinev", section "__DATA,__llvm_prf_names", align 1
-// CHECK: @__llvm_profile_data__Z10foo_inlinev = linkonce_odr hidden constant { i32, i32, i64, i8*, i64* } { i32 15, i32 7, i64 {{[0-9]+}}, i8* getelementptr inbounds ([15 x i8]* @__llvm_profile_name__Z10foo_inlinev, i32 0, i32 0), i64* getelementptr inbounds ([7 x i64]* @__llvm_profile_counters__Z10foo_inlinev, i32 0, i32 0) }, section "__DATA,__llvm_prf_data", align 8
 inline void foo_inline(void) { if (0){} if (0){} if (0){} if (0){} if (0){} if (0){}}
-
-// CHECK: @llvm.used = appending global [5 x i8*] [i8* bitcast (i32 ()* @__llvm_profile_runtime_user to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data__Z3foov to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data__Z8foo_weakv to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data_main to i8*), i8* bitcast ({ i32, i32, i64, i8*, i64* }* @__llvm_profile_data__Z10foo_inlinev to i8*)], section "llvm.metadata"
-
-// CHECK: define linkonce_odr i32 @__llvm_profile_runtime_user() {{.*}} {
-// CHECK:   %[[REG:.*]] = load i32* @__llvm_profile_runtime
-// CHECK:   ret i32 %[[REG]]
-// CHECK: }
diff --git a/test/Profile/cxx-templates.cpp b/test/Profile/cxx-templates.cpp
index 55ab36f..ce5651a 100644
--- a/test/Profile/cxx-templates.cpp
+++ b/test/Profile/cxx-templates.cpp
@@ -32,8 +32,8 @@
   // ALL: ret
 }
 
-// T0USE-DAG: ![[T01]] = metadata !{metadata !"branch_weights", i32 1, i32 2}
-// T100USE-DAG: ![[T1001]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
+// T0USE-DAG: ![[T01]] = !{!"branch_weights", i32 1, i32 2}
+// T100USE-DAG: ![[T1001]] = !{!"branch_weights", i32 101, i32 2}
 
 int main(int argc, const char *argv[]) {
   loop<0>();
diff --git a/test/Profile/cxx-throws.cpp b/test/Profile/cxx-throws.cpp
index 9ea5ace..17f4d8c 100644
--- a/test/Profile/cxx-throws.cpp
+++ b/test/Profile/cxx-throws.cpp
@@ -3,12 +3,12 @@
 // FIXME: Don't seek bb labels, like "if.else"
 // REQUIRES: asserts
 
-// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -target %itanium_abi_triple | FileCheck -check-prefix=PGOGEN %s
-// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -target %itanium_abi_triple | FileCheck -check-prefix=PGOGEN-EXC %s
+// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -fexceptions -target %itanium_abi_triple | FileCheck -check-prefix=PGOGEN %s
+// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -fexceptions -target %itanium_abi_triple | FileCheck -check-prefix=PGOGEN-EXC %s
 
 // RUN: llvm-profdata merge %S/Inputs/cxx-throws.proftext -o %t.profdata
-// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-use=%t.profdata -target %itanium_abi_triple | FileCheck -check-prefix=PGOUSE %s
-// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-use=%t.profdata -target %itanium_abi_triple | FileCheck -check-prefix=PGOUSE-EXC %s
+// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-use=%t.profdata -fcxx-exceptions -target %itanium_abi_triple | FileCheck -check-prefix=PGOUSE %s
+// RUN: %clang %s -o - -emit-llvm -S -fprofile-instr-use=%t.profdata -fcxx-exceptions -target %itanium_abi_triple | FileCheck -check-prefix=PGOUSE-EXC %s
 
 // PGOGEN: @[[THC:__llvm_profile_counters__Z6throwsv]] = hidden global [9 x i64] zeroinitializer
 // PGOGEN-EXC: @[[THC:__llvm_profile_counters__Z6throwsv]] = hidden global [9 x i64] zeroinitializer
@@ -60,12 +60,12 @@
   // PGOUSE: ret void
 }
 
-// PGOUSE-DAG: ![[TH1]] = metadata !{metadata !"branch_weights", i32 101, i32 2}
-// PGOUSE-DAG: ![[TH2]] = metadata !{metadata !"branch_weights", i32 67, i32 35}
-// PGOUSE-DAG: ![[TH3]] = metadata !{metadata !"branch_weights", i32 34, i32 34}
-// PGOUSE-DAG: ![[TH4]] = metadata !{metadata !"branch_weights", i32 18, i32 18}
-// PGOUSE-EXC: ![[TH5]] = metadata !{metadata !"branch_weights", i32 34, i32 18}
-// PGOUSE-DAG: ![[TH6]] = metadata !{metadata !"branch_weights", i32 101, i32 1}
+// PGOUSE-DAG: ![[TH1]] = !{!"branch_weights", i32 101, i32 2}
+// PGOUSE-DAG: ![[TH2]] = !{!"branch_weights", i32 67, i32 35}
+// PGOUSE-DAG: ![[TH3]] = !{!"branch_weights", i32 34, i32 34}
+// PGOUSE-DAG: ![[TH4]] = !{!"branch_weights", i32 18, i32 18}
+// PGOUSE-EXC: ![[TH5]] = !{!"branch_weights", i32 34, i32 18}
+// PGOUSE-DAG: ![[TH6]] = !{!"branch_weights", i32 101, i32 1}
 
 int main(int argc, const char *argv[]) {
   throws();
diff --git a/test/Profile/objc-general.m b/test/Profile/objc-general.m
index ba06f91..9a36667 100644
--- a/test/Profile/objc-general.m
+++ b/test/Profile/objc-general.m
@@ -31,8 +31,8 @@
 @end;
 #endif
 
-// PGOGEN: @[[FRC:"__llvm_profile_counters_\+\[A foreach:\]"]] = internal global [2 x i64] zeroinitializer
-// PGOGEN: @[[BLC:"__llvm_profile_counters___13\+\[A foreach:\]_block_invoke"]] = internal global [2 x i64] zeroinitializer
+// PGOGEN: @[[FRC:"__llvm_profile_counters_objc-general.m:\+\[A foreach:\]"]] = internal global [2 x i64] zeroinitializer
+// PGOGEN: @[[BLC:"__llvm_profile_counters_objc-general.m:__13\+\[A foreach:\]_block_invoke"]] = internal global [2 x i64] zeroinitializer
 // PGOGEN: @[[MAC:__llvm_profile_counters_main]] = hidden global [1 x i64] zeroinitializer
 
 @interface A : NSObject
@@ -63,9 +63,9 @@
 }
 @end
 
-// PGOUSE-DAG: ![[FR1]] = metadata !{metadata !"branch_weights", i32 2, i32 3}
-// PGOUSE-DAG: ![[FR2]] = metadata !{metadata !"branch_weights", i32 3, i32 2}
-// PGOUSE-DAG: ![[BL1]] = metadata !{metadata !"branch_weights", i32 2, i32 2}
+// PGOUSE-DAG: ![[FR1]] = !{!"branch_weights", i32 2, i32 3}
+// PGOUSE-DAG: ![[FR2]] = !{!"branch_weights", i32 3, i32 2}
+// PGOUSE-DAG: ![[BL1]] = !{!"branch_weights", i32 2, i32 2}
 
 int main(int argc, const char *argv[]) {
   A *a = [[A alloc] init];
diff --git a/test/Sema/128bitfloat.cc b/test/Sema/128bitfloat.cpp
similarity index 100%
rename from test/Sema/128bitfloat.cc
rename to test/Sema/128bitfloat.cpp
diff --git a/test/Sema/MicrosoftCompatibility-x64.c b/test/Sema/MicrosoftCompatibility-x64.c
index bf595af..7d1f649 100644
--- a/test/Sema/MicrosoftCompatibility-x64.c
+++ b/test/Sema/MicrosoftCompatibility-x64.c
@@ -1,8 +1,13 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-compatibility -triple x86_64-pc-win32
-int __stdcall f(void); /* expected-warning {{calling convention '__stdcall' ignored for this target}} */
+// RUN: %clang_cc1 %s -Wmicrosoft -verify -fms-compatibility -triple x86_64-pc-win32
 
-/* This should compile without warning because __stdcall is treated
-as __cdecl in MS compatibility mode for x64 compiles*/
+// None of these should warn. stdcall is treated as equivalent to cdecl on
+// x64.
+// expected-no-diagnostics
+
+int __stdcall f(void);
 int __cdecl f(void) {
   return 0;
 }
+int __stdcall func_std(void);
+int __thiscall func_this(void);
+int __fastcall func_fast(void);
diff --git a/test/Sema/MicrosoftCompatibility.c b/test/Sema/MicrosoftCompatibility.c
index a193b26..010033b 100644
--- a/test/Sema/MicrosoftCompatibility.c
+++ b/test/Sema/MicrosoftCompatibility.c
@@ -21,3 +21,5 @@
 struct __declspec(appdomain) S3 {}; /* expected-warning {{__declspec attribute 'appdomain' is not supported}} */
 
 __declspec(__noreturn__) void f7(void); /* expected-warning {{__declspec attribute '__noreturn__' is not supported}} */
+
+size_t x;
diff --git a/test/Sema/__try.c b/test/Sema/__try.c
index a355de9..0e5de20 100644
--- a/test/Sema/__try.c
+++ b/test/Sema/__try.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -fborland-extensions -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fborland-extensions -DBORLAND -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
 
 #define JOIN2(x,y) x ## y
 #define JOIN(x,y) JOIN2(x,y)
@@ -10,9 +11,11 @@
 
 struct EXCEPTION_INFO{};
 
-int __exception_code();
+unsigned long __exception_code();
+#ifdef BORLAND
 struct EXCEPTION_INFO* __exception_info();
-void __abnormal_termination();
+#endif
+int __abnormal_termination();
 
 #define GetExceptionCode __exception_code
 #define GetExceptionInformation __exception_info
@@ -143,7 +146,11 @@
   __except( function_scope ? 1 : -1 ) {}
 }
 
+#ifdef BORLAND
 void TEST() {
+  (void)__abnormal_termination(); // expected-error{{only allowed in __finally block}}
+  (void)AbnormalTermination();  // expected-error{{only allowed in __finally block}}
+
   __try {
     (void)AbnormalTermination;  // expected-error{{only allowed in __finally block}}
     (void)__abnormal_termination; // expected-error{{only allowed in __finally block}}
@@ -160,15 +167,27 @@
     __abnormal_termination();
   }
 }
+#endif
 
 void TEST() {
-  (void)__exception_code;       // expected-error{{only allowed in __except block}}
-  (void)__exception_info;       // expected-error{{only allowed in __except filter expression}}
-  (void)__abnormal_termination; // expected-error{{only allowed in __finally block}}
-
-  (void)GetExceptionCode();     // expected-error{{only allowed in __except block}}
+  (void)__exception_info();       // expected-error{{only allowed in __except filter expression}}
   (void)GetExceptionInformation(); // expected-error{{only allowed in __except filter expression}}
-  (void)AbnormalTermination();  // expected-error{{only allowed in __finally block}}
+}
+
+void TEST() {
+#ifndef BORLAND
+  (void)__exception_code;     // expected-error{{builtin functions must be directly called}}
+#endif
+  (void)__exception_code();     // expected-error{{only allowed in __except block or filter expression}}
+  (void)GetExceptionCode();     // expected-error{{only allowed in __except block or filter expression}}
+}
+
+void TEST() {
+  __try {
+  } __except(1) {
+    GetExceptionCode(); // valid
+    GetExceptionInformation(); // expected-error{{only allowed in __except filter expression}}
+  }
 }
 
 void test_seh_leave_stmt() {
@@ -188,4 +207,3 @@
   }
   __leave; // expected-error{{'__leave' statement not in __try block}}
 }
-
diff --git a/test/Sema/alias-redefinition.c b/test/Sema/alias-redefinition.c
index 6c6ebf8..91f4b27 100644
--- a/test/Sema/alias-redefinition.c
+++ b/test/Sema/alias-redefinition.c
@@ -23,22 +23,11 @@
 void f5() {}
 void __attribute((alias("f5"))) fun5(void) {} // expected-error {{redefinition of 'fun5'}} // expected-note {{previous definition}}
 
-int v1;
-int var1 __attribute((alias("v1"))); // expected-note {{previous definition}}
-int var1 __attribute((alias("v1"))); // expected-error {{redefinition of 'var1'}}
+int var1 __attribute((alias("v1"))); // expected-error {{definition 'var1' cannot also be an alias}}
+static int var2 __attribute((alias("v2"))) = 2; // expected-error {{definition 'var2' cannot also be an alias}}
 
-int v2;
-int var2 = 2; // expected-note {{previous definition}}
-int var2 __attribute((alias("v2"))); // expected-error {{redefinition of 'var2'}}
+extern int var3 __attribute__((alias("C"))); // expected-note{{previous definition is here}}
+int var3 = 3; // expected-error{{redefinition of 'var3'}}
 
-int v3;
-int var3 __attribute((alias("v3"))); // expected-note {{previous definition}}
-int var3 = 2; // expected-error {{redefinition of 'var3'}}
-
-int v4;
-int var4; // expected-note {{previous definition}}
-int var4 __attribute((alias("v4"))); // expected-error {{alias definition of 'var4' after tentative definition}}
-
-int v5;
-int var5 __attribute((alias("v5"))); // expected-note {{previous definition}}
-int var5; // expected-error {{tentative definition of 'var5' after alias definition}}
+int var4; // expected-note{{previous definition is here}}
+extern int var4 __attribute__((alias("v4"))); // expected-error{{alias definition of 'var4' after tentative definition}}
diff --git a/test/Sema/align-x86.c b/test/Sema/align-x86.c
index f112c63..e3b8c70 100644
--- a/test/Sema/align-x86.c
+++ b/test/Sema/align-x86.c
@@ -27,6 +27,8 @@
 short chk1[__alignof__(g6) == 8 ? 1 : -1];
 short chk2[__alignof__(double[3]) == 8 ? 1 : -1];
 
+enum { x = 18446744073709551615ULL } g7;
+short chk1[__alignof__(g7) == 8 ? 1 : -1];
 
 // PR5637
 
diff --git a/test/Sema/asm.c b/test/Sema/asm.c
index 13ae25f..6c6f3f3 100644
--- a/test/Sema/asm.c
+++ b/test/Sema/asm.c
@@ -164,3 +164,43 @@
   __asm("foo1": "=f" (result)); // expected-error {{invalid output constraint '=f' in asm}}
   return result;
 }
+
+void fn1() {
+  int l;
+  __asm__(""
+          : [l] "=r"(l)
+          : "[l],m"(l)); // expected-error {{asm constraint has an unexpected number of alternatives: 1 vs 2}}
+}
+
+void fn2() {
+  int l;
+ __asm__(""
+          : "+&m"(l)); // expected-error {{invalid output constraint '+&m' in asm}}
+}
+
+void fn3() {
+  int l;
+ __asm__(""
+          : "+#r"(l)); // expected-error {{invalid output constraint '+#r' in asm}}
+}
+
+void fn4() {
+  int l;
+ __asm__(""
+          : "=r"(l)
+          : "m#"(l));
+}
+
+void fn5() {
+  int l;
+    __asm__(""
+          : [g] "+r"(l)
+          : "[g]"(l)); // expected-error {{invalid input constraint '[g]' in asm}}
+}
+
+void fn6() {
+    int a;
+  __asm__(""
+            : "=rm"(a), "=rm"(a)
+            : "11m"(a)) // expected-error {{invalid input constraint '11m' in asm}}
+}
diff --git a/test/Sema/atomic-ops.c b/test/Sema/atomic-ops.c
index e21c3fd..71eaaa8 100644
--- a/test/Sema/atomic-ops.c
+++ b/test/Sema/atomic-ops.c
@@ -49,7 +49,7 @@
 short i16;
 int i32;
 int __attribute__((vector_size(8))) i64;
-struct Incomplete *incomplete;
+struct Incomplete *incomplete; // expected-note {{forward declaration of 'struct Incomplete'}}
 
 _Static_assert(__atomic_is_lock_free(1, &i8), "");
 _Static_assert(__atomic_is_lock_free(1, &i64), "");
@@ -268,6 +268,10 @@
   (void)__c11_atomic_fetch_add(Ap, 1, memory_order_acq_rel);
   (void)__c11_atomic_fetch_add(Ap, 1, memory_order_seq_cst);
 
+  (void)__c11_atomic_fetch_add(
+      (struct Incomplete * _Atomic *)0, // expected-error {{incomplete type 'struct Incomplete'}}
+      1, memory_order_seq_cst);
+
   (void)__c11_atomic_init(Ap, val);
   (void)__c11_atomic_init(Ap, val);
   (void)__c11_atomic_init(Ap, val);
diff --git a/test/Sema/attr-capabilities.c b/test/Sema/attr-capabilities.c
index cdbd2f3..5bfbdac 100644
--- a/test/Sema/attr-capabilities.c
+++ b/test/Sema/attr-capabilities.c
@@ -7,8 +7,8 @@
 // Test an invalid capability name
 struct __attribute__((capability("wrong"))) IncorrectName {}; // expected-warning {{invalid capability name 'wrong'; capability name must be 'mutex' or 'role'}}
 
-int Test1 __attribute__((capability("test1")));  // expected-error {{'capability' attribute only applies to structs or typedefs}}
-int Test2 __attribute__((shared_capability("test2"))); // expected-error {{'shared_capability' attribute only applies to structs or typedefs}}
+int Test1 __attribute__((capability("test1")));  // expected-error {{'capability' attribute only applies to structs and typedefs}}
+int Test2 __attribute__((shared_capability("test2"))); // expected-error {{'shared_capability' attribute only applies to structs and typedefs}}
 int Test3 __attribute__((acquire_capability("test3")));  // expected-warning {{'acquire_capability' attribute only applies to functions}}
 int Test4 __attribute__((try_acquire_capability("test4"))); // expected-error {{'try_acquire_capability' attribute only applies to functions}}
 int Test5 __attribute__((release_capability("test5"))); // expected-warning {{'release_capability' attribute only applies to functions}}
diff --git a/test/Sema/attr-flag-enum.c b/test/Sema/attr-flag-enum.c
new file mode 100644
index 0000000..a53c1dc
--- /dev/null
+++ b/test/Sema/attr-flag-enum.c
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -std=c11 -Wassign-enum %s
+
+enum __attribute__((flag_enum)) flag {
+  ea = 0x1,
+  eb = 0x2,
+  ec = 0x8,
+};
+
+enum __attribute__((flag_enum)) flag2 {
+  ga = 0x1,
+  gb = 0x4,
+
+  gc = 0x5, // no-warning
+  gd = 0x7, // expected-warning {{enumeration value 'gd' is out of range}}
+  ge = ~0x2, // expected-warning {{enumeration value 'ge' is out of range}}
+  gf = ~0x4, // no-warning
+  gg = ~0x1, // no-warning
+  gh = ~0x5, // no-warning
+  gi = ~0x11, // expected-warning {{enumeration value 'gi' is out of range}}
+};
+
+enum __attribute__((flag_enum)) flag3 {
+  fa = 0x1,
+  fb = ~0x1u, // no-warning
+};
+
+// What happens here is that ~0x2 is negative, and so the enum must be signed.
+// But ~0x1u is unsigned and has the high bit set, so the enum must be 64-bit.
+// The result is that ~0x1u does not have high bits set, and so it is considered
+// to be an invalid value. See Sema::IsValueInFlagEnum in SemaDecl.cpp for more
+// discussion.
+enum __attribute__((flag_enum)) flag4 {
+  ha = 0x1,
+  hb = 0x2,
+
+  hc = ~0x1u, // expected-warning {{enumeration value 'hc' is out of range}}
+  hd = ~0x2, // no-warning
+};
+
+void f(void) {
+  enum flag e = 0; // no-warning
+  e = 0x1; // no-warning
+  e = 0x3; // no-warning
+  e = 0xa; // no-warning
+  e = 0x4; // expected-warning {{integer constant not in range of enumerated type}}
+  e = 0xf; // expected-warning {{integer constant not in range of enumerated type}}
+  e = ~0; // no-warning
+  e = ~0x1; // no-warning
+  e = ~0x2; // no-warning
+  e = ~0x3; // no-warning
+  e = ~0x4; // expected-warning {{integer constant not in range of enumerated type}}
+
+  switch (e) {
+    case 0: break; // no-warning
+    case 0x1: break; // no-warning
+    case 0x3: break; // no-warning
+    case 0xa: break; // no-warning
+    case 0x4: break; // expected-warning {{case value not in enumerated type}}
+    case 0xf: break; // expected-warning {{case value not in enumerated type}}
+    case ~0: break; // expected-warning {{case value not in enumerated type}}
+    case ~0x1: break; // expected-warning {{case value not in enumerated type}}
+    case ~0x2: break; // expected-warning {{case value not in enumerated type}}
+    case ~0x3: break; // expected-warning {{case value not in enumerated type}}
+    case ~0x4: break; // expected-warning {{case value not in enumerated type}}
+    default: break;
+  }
+
+  enum flag2 f = ~0x1; // no-warning
+  f = ~0x1u; // no-warning
+
+  enum flag4 h = ~0x1; // no-warning
+  h = ~0x1u; // expected-warning {{integer constant not in range of enumerated type}}
+}
diff --git a/test/Sema/attr-format.c b/test/Sema/attr-format.c
index 21d9585..3ea9d79 100644
--- a/test/Sema/attr-format.c
+++ b/test/Sema/attr-format.c
@@ -57,6 +57,13 @@
   null(0,  (int*)0); // expected-warning {{incompatible pointer types}}
 }
 
+// FreeBSD kernel extensions
+void a3(const char *a, ...)    __attribute__((format(freebsd_kprintf, 1,2))); // no-error
+void b3(const char *a, ...)    __attribute__((format(freebsd_kprintf, 1,1))); // expected-error {{'format' attribute parameter 3 is out of bounds}}
+void c3(const char *a, ...)    __attribute__((format(freebsd_kprintf, 0,2))); // expected-error {{'format' attribute parameter 2 is out of bounds}}
+void d3(const char *a, int c)  __attribute__((format(freebsd_kprintf, 1,2))); // expected-error {{format attribute requires variadic function}}
+void e3(char *str, int c, ...) __attribute__((format(freebsd_kprintf, 2,3))); // expected-error {{format argument not a string type}}
+
 
 
 // PR4470
diff --git a/test/Sema/attr-malloc.c b/test/Sema/attr-malloc.c
index c78d15c..5351d75 100644
--- a/test/Sema/attr-malloc.c
+++ b/test/Sema/attr-malloc.c
@@ -6,16 +6,16 @@
 // Declare malloc here explicitly so we don't depend on system headers.
 void * malloc(size_t) __attribute((malloc));
 
-int no_vars __attribute((malloc)); // expected-warning {{functions returning a pointer type}}
+int no_vars __attribute((malloc)); // expected-warning {{attribute only applies to functions}}
 
-void  returns_void  (void) __attribute((malloc)); // expected-warning {{functions returning a pointer type}}
-int   returns_int   (void) __attribute((malloc)); // expected-warning {{functions returning a pointer type}}
+void  returns_void  (void) __attribute((malloc)); // expected-warning {{attribute only applies to return values that are pointers}}
+int   returns_int   (void) __attribute((malloc)); // expected-warning {{attribute only applies to return values that are pointers}}
 int * returns_intptr(void) __attribute((malloc)); // no-warning
 typedef int * iptr;
 iptr  returns_iptr  (void) __attribute((malloc)); // no-warning
 
-__attribute((malloc)) void *(*f)(); //  expected-warning{{'malloc' attribute only applies to functions returning a pointer type}}
-__attribute((malloc)) int (*g)(); // expected-warning{{'malloc' attribute only applies to functions returning a pointer type}}
+__attribute((malloc)) void *(*f)(); //  expected-warning{{attribute only applies to functions}}
+__attribute((malloc)) int (*g)(); // expected-warning{{attribute only applies to functions}}
 
 __attribute((malloc))
 void * xalloc(unsigned n) { return malloc(n); } // no-warning
diff --git a/test/Sema/attr-naked.cpp b/test/Sema/attr-naked.cpp
new file mode 100644
index 0000000..eaa8e22
--- /dev/null
+++ b/test/Sema/attr-naked.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only -triple arm-none-linux
+class Foo {
+  void bar();
+  static void bar2();
+  unsigned v;
+  static unsigned s;
+};
+
+void __attribute__((naked)) Foo::bar() { // expected-note{{attribute is here}}
+  asm("mov r2, %0" : : "r"(v)); // expected-error{{'this' pointer references not allowed in naked functions}}
+}
+
+void __attribute__((naked)) Foo::bar2() {
+  asm("mov r2, %0" : : "r"(s)); // static member reference is OK
+}
diff --git a/test/Sema/bitfield.c b/test/Sema/bitfield.c
index a4629c6..fb72213 100644
--- a/test/Sema/bitfield.c
+++ b/test/Sema/bitfield.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify -std=c11
+// RUN: %clang_cc1 %s -fsyntax-only -verify -std=c11 -Wno-unused-value
+
 enum e0; // expected-note{{forward declaration of 'enum e0'}}
 
 struct a {
diff --git a/test/Sema/builtins-x86.c b/test/Sema/builtins-x86.c
new file mode 100644
index 0000000..326d2a3
--- /dev/null
+++ b/test/Sema/builtins-x86.c
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -triple=x86_64-apple-darwin -fsyntax-only -verify %s
+
+typedef long long __m128i __attribute__((__vector_size__(16)));
+typedef float __m128 __attribute__((__vector_size__(16)));
+typedef double __m128d __attribute__((__vector_size__(16)));
+
+typedef float __m512 __attribute__((__vector_size__(64)));
+typedef double __m512d __attribute__((__vector_size__(64)));
+
+typedef unsigned char __mmask8;
+typedef unsigned short __mmask16;
+
+__m128 test__builtin_ia32_cmpps(__m128 __a, __m128 __b) {
+  __builtin_ia32_cmpps(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
+}
+
+__m128d test__builtin_ia32_cmppd(__m128d __a, __m128d __b) {
+  __builtin_ia32_cmppd(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
+}
+
+__m128 test__builtin_ia32_cmpss(__m128 __a, __m128 __b) {
+  __builtin_ia32_cmpss(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
+}
+
+__m128d test__builtin_ia32_cmpsd(__m128d __a, __m128d __b) {
+  __builtin_ia32_cmpsd(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
+}
+
+__mmask16 test__builtin_ia32_cmpps512_mask(__m512d __a, __m512d __b) {
+  __builtin_ia32_cmpps512_mask(__a, __b, 32, -1, 0); // expected-error {{argument should be a value from 0 to 31}}
+}
+
+__mmask8 test__builtin_ia32_cmppd512_mask(__m512d __a, __m512d __b) {
+  __builtin_ia32_cmppd512_mask(__a, __b, 32, -1, 0); // expected-error {{argument should be a value from 0 to 31}}
+}
+
+__m128i test__builtin_ia32_vpcomub(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomub(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomuw(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomuw(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomud(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomud(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomuq(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomuq(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomb(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomub(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomw(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomuw(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomd(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomud(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
+
+__m128i test__builtin_ia32_vpcomq(__m128i __a, __m128i __b) {
+  __builtin_ia32_vpcomuq(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
+}
diff --git a/test/Sema/call-with-static-chain.c b/test/Sema/call-with-static-chain.c
new file mode 100644
index 0000000..4a076d2
--- /dev/null
+++ b/test/Sema/call-with-static-chain.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -fblocks -verify %s
+
+void f();
+
+void g() {
+  __builtin_call_with_static_chain(f(), f);
+  __builtin_call_with_static_chain(f, f); // expected-error {{first argument to __builtin_call_with_static_chain must be a non-member call expression}}
+  __builtin_call_with_static_chain(^{}(), f); // expected-error {{first argument to __builtin_call_with_static_chain must not be a block call}}
+  __builtin_call_with_static_chain(__builtin_unreachable(), f); // expected-error {{first argument to __builtin_call_with_static_chain must not be a builtin call}}
+  __builtin_call_with_static_chain(f(), 42); // expected-error {{second argument to __builtin_call_with_static_chain must be of pointer type}}
+}
diff --git a/test/Sema/callingconv.c b/test/Sema/callingconv.c
index 6a8be5a..c7a4821 100644
--- a/test/Sema/callingconv.c
+++ b/test/Sema/callingconv.c
@@ -59,8 +59,6 @@
 typedef __attribute__((stdcall)) void (*PROC)();
 PROC __attribute__((cdecl)) ctest4(const char *x) {}
 
-void __attribute__((pnaclcall)) pnaclfunc(float *a) {} // expected-warning {{calling convention 'pnaclcall' ignored for this target}}
-
 void __attribute__((intel_ocl_bicc)) inteloclbifunc(float *a) {}
 
 typedef void typedef_fun_t(int);
diff --git a/test/Sema/complex-int.c b/test/Sema/complex-int.c
index 32249b3..2b797e5 100644
--- a/test/Sema/complex-int.c
+++ b/test/Sema/complex-int.c
@@ -8,6 +8,8 @@
 __complex__ int result;
 int ii;
 int aa = 1 + 1.0iF;
+int bb = 0;
+bb += 1i;
 
 result = arr*ii;
 result = ii*brr;
diff --git a/test/Sema/expr-comma-c99.c b/test/Sema/expr-comma-c99.c
index 02886bf..934c81c 100644
--- a/test/Sema/expr-comma-c99.c
+++ b/test/Sema/expr-comma-c99.c
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 %s -fsyntax-only -verify -std=c99 -Wno-sizeof-array-decay
-// expected-no-diagnostics
 // rdar://6095180
 
 struct s { char c[17]; };
@@ -14,5 +13,5 @@
 // comma does array/function promotion in c99.
 int X[sizeof(0, (foo().c)) == sizeof(char*) ? 1 : -1];
 int Y[sizeof(0, (a,b).c) == sizeof(char*) ? 1 : -1];
-int Z[sizeof(0, (a=b).c) == sizeof(char*) ? 1 : -1];
+int Z[sizeof(0, (a=b).c) == sizeof(char*) ? 1 : -1]; // expected-warning {{expression with side effects has no effect in an unevaluated context}}
 
diff --git a/test/Sema/expr-comma.c b/test/Sema/expr-comma.c
index e2beafe..04e57de 100644
--- a/test/Sema/expr-comma.c
+++ b/test/Sema/expr-comma.c
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 %s -fsyntax-only -verify -std=c89 -Wno-sizeof-array-decay
-// expected-no-diagnostics
 // rdar://6095180
 
 struct s { char c[17]; };
@@ -15,4 +14,4 @@
 int W[sizeof(0, a.c) == sizeof(char*) ? 1 : -1];
 int X[sizeof(0, (foo().c)) == 17 ? 1 : -1];
 int Y[sizeof(0, (a,b).c) == 17 ? 1 : -1];
-int Z[sizeof(0, (a=b).c) == 17 ? 1 : -1];
+int Z[sizeof(0, (a=b).c) == 17 ? 1 : -1]; // expected-warning {{expression with side effects has no effect in an unevaluated context}}
diff --git a/test/Sema/format-strings-freebsd.c b/test/Sema/format-strings-freebsd.c
new file mode 100644
index 0000000..cdf273a
--- /dev/null
+++ b/test/Sema/format-strings-freebsd.c
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -triple i386-unknown-freebsd %s
+// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-unknown-freebsd %s
+
+// Test FreeBSD kernel printf extensions.
+int freebsd_kernel_printf(const char *, ...) __attribute__((__format__(__freebsd_kprintf__, 1, 2)));
+
+void check_freebsd_kernel_extensions(int i, long l, char *s)
+{
+  // %b expects an int and a char *
+  freebsd_kernel_printf("reg=%b\n", i, "\10\2BITTWO\1BITONE\n"); // no-warning
+  freebsd_kernel_printf("reg=%b\n", l, "\10\2BITTWO\1BITONE\n"); // expected-warning{{format specifies type 'int' but the argument has type 'long'}}
+  freebsd_kernel_printf("reg=%b\n", i, l); // expected-warning{{format specifies type 'char *' but the argument has type 'long'}}
+  freebsd_kernel_printf("reg=%b\n", i); // expected-warning{{more '%' conversions than data arguments}}
+  freebsd_kernel_printf("reg=%b\n", i, "\10\2BITTWO\1BITONE\n", l); // expected-warning{{data argument not used by format string}}
+
+  // %D expects an unsigned char * and a char *
+  freebsd_kernel_printf("%6D", s, ":"); // no-warning
+  freebsd_kernel_printf("%6D", i, ":"); // expected-warning{{format specifies type 'void *' but the argument has type 'int'}}
+  freebsd_kernel_printf("%6D", s, i); // expected-warning{{format specifies type 'char *' but the argument has type 'int'}}
+  freebsd_kernel_printf("%6D", s); // expected-warning{{more '%' conversions than data arguments}}
+  freebsd_kernel_printf("%6D", s, ":", i); // expected-warning{{data argument not used by format string}}
+
+  freebsd_kernel_printf("%*D", 42, s, ":"); // no-warning
+  freebsd_kernel_printf("%*D", 42, i, ":"); // expected-warning{{format specifies type 'void *' but the argument has type 'int'}}
+  freebsd_kernel_printf("%*D", 42, s, i); // expected-warning{{format specifies type 'char *' but the argument has type 'int'}}
+  freebsd_kernel_printf("%*D", 42, s); // expected-warning{{more '%' conversions than data arguments}}
+  freebsd_kernel_printf("%*D", 42, s, ":", i); // expected-warning{{data argument not used by format string}}
+
+  // %r expects an int
+  freebsd_kernel_printf("%r", i); // no-warning
+  freebsd_kernel_printf("%r", l); // expected-warning{{format specifies type 'int' but the argument has type 'long'}}
+  freebsd_kernel_printf("%lr", i); // expected-warning{{format specifies type 'long' but the argument has type 'int'}}
+  freebsd_kernel_printf("%lr", l); // no-warning
+
+  // %y expects an int
+  freebsd_kernel_printf("%y", i); // no-warning
+  freebsd_kernel_printf("%y", l); // expected-warning{{format specifies type 'int' but the argument has type 'long'}}
+  freebsd_kernel_printf("%ly", i); // expected-warning{{format specifies type 'long' but the argument has type 'int'}}
+  freebsd_kernel_printf("%ly", l); // no-warning
+}
diff --git a/test/Sema/function.c b/test/Sema/function.c
index 81d303c..26be614 100644
--- a/test/Sema/function.c
+++ b/test/Sema/function.c
@@ -113,3 +113,9 @@
   decays(array);
   no_decay(array);
 }
+
+void const Bar (void); // ok on decl
+// PR 20146
+void const Bar (void) // expected-warning {{function cannot return qualified void type 'const void'}}
+{
+}
diff --git a/test/Sema/inline-asm-validate-aarch64.c b/test/Sema/inline-asm-validate-aarch64.c
index 1364b64..014767d 100644
--- a/test/Sema/inline-asm-validate-aarch64.c
+++ b/test/Sema/inline-asm-validate-aarch64.c
@@ -36,3 +36,19 @@
 
   return byte;
 }
+
+// CHECK: warning: value size does not match register size specified by the constraint and modifier
+// CHECK: asm ("%w0 %w1 %2" : "+r" (one) : "r" (wide_two));
+// CHECK: note: use constraint modifier "w"
+// CHECK: fix-it:{{.*}}:{47:17-47:19}:"%w2"
+
+void read_write_modifier0(int one, int two) {
+  long wide_two = two;
+  asm ("%w0 %w1 %2" : "+r" (one) : "r" (wide_two));
+}
+
+// CHECK-NOT: warning: 
+void read_write_modifier1(int one, int two) {
+  long wide_two = two;
+  asm ("%w0 %1" : "+r" (one), "+r" (wide_two));
+}
diff --git a/test/Sema/inline-asm-validate-x86.c b/test/Sema/inline-asm-validate-x86.c
new file mode 100644
index 0000000..658b714
--- /dev/null
+++ b/test/Sema/inline-asm-validate-x86.c
@@ -0,0 +1,105 @@
+// RUN: %clang_cc1 -triple i686 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64 -fsyntax-only -verify %s
+
+void I(int i, int j) {
+  static const int BelowMin = -1;
+  static const int AboveMax = 32;
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "I"(j)); // expected-error{{constraint 'I' expects an integer constant expression}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "I"(BelowMin)); // expected-error{{value '-1' out of range for constraint 'I'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "I"(AboveMax)); // expected-error{{value '32' out of range for constraint 'I'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "I"(16)); // expected-no-error
+}
+
+void J(int i, int j) {
+  static const int BelowMin = -1;
+  static const int AboveMax = 64;
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "J"(j)); // expected-error{{constraint 'J' expects an integer constant expression}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "J"(BelowMin)); // expected-error{{value '-1' out of range for constraint 'J'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "J"(AboveMax)); // expected-error{{value '64' out of range for constraint 'J'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "J"(32)); // expected-no-error
+}
+
+void K(int i, int j) {
+  static const int BelowMin = -129;
+  static const int AboveMax = 128;
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "K"(j)); // expected-error{{constraint 'K' expects an integer constant expression}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "K"(BelowMin)); // expected-error{{value '-129' out of range for constraint 'K'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "K"(AboveMax)); // expected-error{{value '128' out of range for constraint 'K'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "K"(96)); // expected-no-error
+}
+
+void M(int i, int j) {
+  static const int BelowMin = -1;
+  static const int AboveMax = 4;
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "M"(j)); // expected-error{{constraint 'M' expects an integer constant expression}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "M"(BelowMin)); // expected-error{{value '-1' out of range for constraint 'M'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "M"(AboveMax)); // expected-error{{value '4' out of range for constraint 'M'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "M"(2)); // expected-no-error
+}
+
+void N(int i, int j) {
+  static const int BelowMin = -1;
+  static const int AboveMax = 256;
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "N"(j)); // expected-error{{constraint 'N' expects an integer constant expression}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "N"(BelowMin)); // expected-error{{value '-1' out of range for constraint 'N'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "N"(AboveMax)); // expected-error{{value '256' out of range for constraint 'N'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "N"(128)); // expected-no-error
+}
+
+void O(int i, int j) {
+  static const int BelowMin = -1;
+  static const int AboveMax = 128;
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "O"(j)); // expected-error{{constraint 'O' expects an integer constant expression}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "O"(BelowMin)); // expected-error{{value '-1' out of range for constraint 'O'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "O"(AboveMax)); // expected-error{{value '128' out of range for constraint 'O'}}
+  __asm__("xorl %0,%2"
+          : "=r"(i)
+          : "0"(i), "O"(64)); // expected-no-error
+}
+
diff --git a/test/Sema/integer-overflow.c b/test/Sema/integer-overflow.c
new file mode 100644
index 0000000..44fbcd4
--- /dev/null
+++ b/test/Sema/integer-overflow.c
@@ -0,0 +1,147 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+typedef unsigned long long uint64_t;
+typedef unsigned long long uint32_t;
+
+uint64_t f0(uint64_t);
+uint64_t f1(uint64_t, uint32_t);
+uint64_t f2(uint64_t, ...);
+
+static const uint64_t overflow = 1 * 4608 * 1024 * 1024; // expected-warning {{overflow in expression; result is 536870912 with type 'int'}}
+
+uint64_t check_integer_overflows(int i) {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t overflow = 4608 * 1024 * 1024,
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow2 = (uint64_t)(4608 * 1024 * 1024),
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow3 = (uint64_t)(4608 * 1024 * 1024 * i),
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow4 =  (1ULL * ((4608) * ((1024) * (1024))) + 2ULL),
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+           multi_overflow = (uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow += overflow2 = overflow3 = (uint64_t)(4608 * 1024 * 1024);
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow += overflow2 = overflow3 = 4608 * 1024 * 1024;
+
+  uint64_t not_overflow = 4608 * 1024 * 1024ULL;
+  uint64_t not_overflow2 = (1ULL * ((uint64_t)(4608) * (1024 * 1024)) + 2ULL);
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  overflow = 4608 * 1024 * 1024 ?  4608 * 1024 * 1024 : 0;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow =  0 ? 0 : 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if (4608 * 1024 * 1024)
+    return 0;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)(4608 * 1024 * 1024))
+    return 1;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)(4608 * 1024 * 1024))
+    return 2;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)(4608 * 1024 * 1024 * i))
+    return 3;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL))
+    return 4;
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)))
+    return 5;
+
+  switch (i) {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  case 4608 * 1024 * 1024:
+    return 6;
+// expected-warning@+1 {{overflow in expression; result is 537919488 with type 'int'}}
+  case (uint64_t)(4609 * 1024 * 1024):
+    return 7;
+// expected-error@+1 {{expression is not an integer constant expression}}
+  case ((uint64_t)(4608 * 1024 * 1024 * i)):
+    return 8;
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  case ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL)):
+    return 9;
+// expected-warning@+2 2{{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+1 {{overflow converting case value to switch condition type (288230376151711744 to 0)}}
+  case ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024))):
+    return 10;
+  }
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while (4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)(4608 * 1024 * 1024 * i));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL));
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while (4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)(4608 * 1024 * 1024 * i));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL));
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)));
+
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+  for (uint64_t i = 4608 * 1024 * 1024;
+       (uint64_t)(4608 * 1024 * 1024);
+       i += (uint64_t)(4608 * 1024 * 1024 * i));
+
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 2{{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 2{{overflow in expression; result is 536870912 with type 'int'}}
+  for (uint64_t i = (1ULL * ((4608) * ((1024) * (1024))) + 2ULL);
+       ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)));
+       i = ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024))));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  _Complex long long x = 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (__real__ x) = 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (__imag__ x) = 4608 * 1024 * 1024;
+
+// expected-warning@+4 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 {{array index 536870912 is past the end of the array (which contains 10 elements)}}
+// expected-note@+1 {{array 'a' declared here}}
+  uint64_t a[10];
+  a[4608 * 1024 * 1024] = 1i;
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
+}
diff --git a/test/Sema/nonnull.c b/test/Sema/nonnull.c
index de47e96..4b3df85 100644
--- a/test/Sema/nonnull.c
+++ b/test/Sema/nonnull.c
@@ -141,3 +141,15 @@
  }
 }
 
+void pr21668_1(__attribute__((nonnull)) const char *p, const char *s) {
+  if (p) // expected-warning {{nonnull parameter 'p' will evaluate to 'true' on first encounter}}
+    ;
+  if (s) // No warning
+    ;
+}
+
+void pr21668_2(__attribute__((nonnull)) const char *p) {
+  p = 0;
+  if (p) // No warning
+    ;
+}
diff --git a/test/Sema/parentheses.c b/test/Sema/parentheses.c
index b7f1b6e..739561d 100644
--- a/test/Sema/parentheses.c
+++ b/test/Sema/parentheses.c
@@ -80,7 +80,7 @@
 
 _Bool someConditionFunc();
 
-void conditional_op(int x, int y, _Bool b) {
+void conditional_op(int x, int y, _Bool b, void* p) {
   (void)(x + someConditionFunc() ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '+'}} \
                                            // expected-note {{place parentheses around the '+' expression to silence this warning}} \
                                            // expected-note {{place parentheses around the '?:' expression to evaluate it first}}
@@ -116,6 +116,14 @@
   // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:24-[[@LINE-6]]:24}:")"
 
   (void)(x % 2 ? 1 : 2); // no warning
+
+  (void)(x + p ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '+'}} expected-note 2{{place parentheses}}
+  (void)(p + x ? 1 : 2); // no warning
+
+  (void)(p + b ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '+'}} expected-note 2{{place parentheses}}
+
+  (void)(x + y > 0 ? 1 : 2); // no warning
+  (void)(x + (y > 0) ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '+'}} expected-note 2{{place parentheses}}
 }
 
 // RUN: not %clang_cc1 -fsyntax-only -Wparentheses -Werror -fdiagnostics-show-option %s 2>&1 | FileCheck %s -check-prefix=CHECK-FLAG
diff --git a/test/Sema/pointer-addition.c b/test/Sema/pointer-addition.c
index 21ce63b..667fe9a 100644
--- a/test/Sema/pointer-addition.c
+++ b/test/Sema/pointer-addition.c
@@ -1,6 +1,7 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -std=c11
 
-typedef struct S S; // expected-note 3 {{forward declaration of 'struct S'}}
+typedef struct S S; // expected-note 4 {{forward declaration of 'struct S'}}
+extern _Atomic(S*) e;
 void a(S* b, void* c) {
   void (*fp)(int) = 0;
   b++;       // expected-error {{arithmetic on a pointer to an incomplete type}}
@@ -18,4 +19,5 @@
   d--;       // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' is a GNU extension}}
   d -= 1;    // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' is a GNU extension}}
   (void)(1 + d); // expected-warning {{arithmetic on a pointer to the function type 'void (S *, void *)' is a GNU extension}}
+  e++;       // expected-error {{arithmetic on a pointer to an incomplete type}}
 }
diff --git a/test/Sema/sizeof-struct-non-zero-as-member.cl b/test/Sema/sizeof-struct-non-zero-as-member.cl
index b64c036..0e13c61 100644
--- a/test/Sema/sizeof-struct-non-zero-as-member.cl
+++ b/test/Sema/sizeof-struct-non-zero-as-member.cl
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -verify -fsyntax-only -triple r600 -target-cpu verde -S -emit-llvm -o - %s
+// RUN: %clang_cc1 -verify -fsyntax-only -triple amdgcn -target-cpu verde -S -emit-llvm -o - %s
 // expected-no-diagnostics
 
 // Record lowering was crashing on SI and newer targets, because it
diff --git a/test/Sema/string-plus-char.c b/test/Sema/string-plus-char.c
index 322e8f5..66c1182 100644
--- a/test/Sema/string-plus-char.c
+++ b/test/Sema/string-plus-char.c
@@ -1,5 +1,11 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
 
+struct AB{const char *a; const char*b;};
+
+const char *foo(const struct AB *ab) {
+  return ab->a + 'b'; // expected-warning {{adding 'char' to a string pointer does not append to the string}} expected-note {{use array indexing to silence this warning}}
+}
+
 void f(const char *s) {
   char *str = 0;
   char *str2 = str + 'c'; // expected-warning {{adding 'char' to a string pointer does not append to the string}} expected-note {{use array indexing to silence this warning}}
@@ -8,6 +14,15 @@
 
   str = 'c' + str;// expected-warning {{adding 'char' to a string pointer does not append to the string}} expected-note {{use array indexing to silence this warning}}
 
+  char strArr[] = "foo";
+  str = strArr + 'c'; // expected-warning {{adding 'char' to a string pointer does not append to the string}} expected-note {{use array indexing to silence this warning}}
+  char *strArr2[] = {"ac","dc"};
+  str = strArr2[0] + 'c'; // expected-warning {{adding 'char' to a string pointer does not append to the string}} expected-note {{use array indexing to silence this warning}}
+
+
+  struct AB ab;
+  constStr = foo(&ab) + 'c'; // expected-warning {{adding 'char' to a string pointer does not append to the string}} expected-note {{use array indexing to silence this warning}}
+
   // no-warning
   char c = 'c';
   str = str + c;
diff --git a/test/Sema/types.c b/test/Sema/types.c
index 1ed8dae..5614d16 100644
--- a/test/Sema/types.c
+++ b/test/Sema/types.c
@@ -1,7 +1,7 @@
-// RUN: %clang_cc1 %s -pedantic -verify -triple=x86_64-apple-darwin9
-// RUN: %clang_cc1 %s -pedantic -verify -triple=mips64-linux-gnu
-// RUN: %clang_cc1 %s -pedantic -verify -triple=x86_64-unknown-linux
-// RUN: %clang_cc1 %s -pedantic -verify -triple=x86_64-unknown-linux-gnux32
+// RUN: %clang_cc1 %s -fblocks -pedantic -verify -triple=x86_64-apple-darwin9
+// RUN: %clang_cc1 %s -fblocks -pedantic -verify -triple=mips64-linux-gnu
+// RUN: %clang_cc1 %s -fblocks -pedantic -verify -triple=x86_64-unknown-linux
+// RUN: %clang_cc1 %s -fblocks -pedantic -verify -triple=x86_64-unknown-linux-gnux32
 
 // rdar://6097662
 typedef int (*T)[2];
@@ -84,3 +84,7 @@
     uchar32 r = 0;
     r.s[ 1234 ] = 1; // expected-error {{illegal vector component name 's'}}
 }
+
+int &*_Atomic null_type_0; // expected-error {{expected identifier or '('}}
+int &*__restrict__ null_type_1; // expected-error {{expected identifier or '('}}
+int ^_Atomic null_type_2; // expected-error {{block pointer to non-function type is invalid}}
diff --git a/test/Sema/typo-correction.c b/test/Sema/typo-correction.c
new file mode 100644
index 0000000..8276737
--- /dev/null
+++ b/test/Sema/typo-correction.c
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+//
+// This file contains typo correction tests which hit different code paths in C
+// than in C++ and may exhibit different behavior as a result.
+
+__typeof__(struct F*) var[invalid];  // expected-error-re {{use of undeclared identifier 'invalid'{{$}}}}
+
+void PR21656() {
+  float x;
+  x = (float)arst;  // expected-error-re {{use of undeclared identifier 'arst'{{$}}}}
+}
+
+a = b ? : 0;  // expected-warning {{type specifier missing, defaults to 'int'}} \
+              // expected-error {{use of undeclared identifier 'b'}}
+
+int foobar;  // expected-note {{'foobar' declared here}}
+a = goobar ?: 4;  // expected-warning {{type specifier missing, defaults to 'int'}} \
+                  // expected-error {{use of undeclared identifier 'goobar'; did you mean 'foobar'?}} \
+                  // expected-error {{initializer element is not a compile-time constant}}
+
+struct ContainerStuct {
+  enum { SOME_ENUM }; // expected-note {{'SOME_ENUM' declared here}}
+};
+
+void func(int arg) {
+  switch (arg) {
+  case SOME_ENUM_: // expected-error {{use of undeclared identifier 'SOME_ENUM_'; did you mean 'SOME_ENUM'}}
+    ;
+  }
+}
diff --git a/test/Sema/var-redecl.c b/test/Sema/var-redecl.c
index 0e30aa2..811e9f1 100644
--- a/test/Sema/var-redecl.c
+++ b/test/Sema/var-redecl.c
@@ -4,7 +4,7 @@
 extern int outer2; // expected-note{{previous definition is here}}
 int outer4;
 int outer4; // expected-note{{previous definition is here}}
-int outer5; // expected-note{{previous definition is here}}
+int outer5;
 int outer6(float); // expected-note{{previous definition is here}}
 int outer7(float);
 
@@ -13,7 +13,7 @@
   extern float outer2; // expected-error{{redefinition of 'outer2' with a different type}}
   extern float outer3; // expected-note{{previous definition is here}}
   double outer4;
-  extern int outer5;
+  extern int outer5; // expected-note{{previous definition is here}}
   extern int outer6; // expected-error{{redefinition of 'outer6' as different kind of symbol}}
   int outer7;
   extern int outer8; // expected-note{{previous definition is here}}
@@ -60,3 +60,11 @@
 static int a;
 extern int a; // expected-note {{previous declaration is here}}
 int a;	// expected-error {{non-static declaration of 'a' follows static declaration}}
+
+void f(int x) { // expected-note {{previous definition is here}}
+  extern int x; // expected-error {{extern declaration of 'x' follows non-extern declaration}}
+}
+
+extern int b[];
+void g20() { extern int b[3]; } // expected-note{{previous definition is here}}
+void g21() { extern int b[4]; } // expected-error{{redefinition of 'b' with a different type: 'int [4]' vs 'int [3]'}}
diff --git a/test/Sema/warn-cast-qual.c b/test/Sema/warn-cast-qual.c
new file mode 100644
index 0000000..dc11f57
--- /dev/null
+++ b/test/Sema/warn-cast-qual.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -Wcast-qual -verify %s
+
+#include <stdint.h>
+
+void foo() {
+  const char * const ptr = 0;
+  const char * const *ptrptr = 0;
+  char *y = (char *)ptr;	// expected-warning {{cast from 'const char *' to 'char *' drops const qualifier}}
+  char **y1 = (char **)ptrptr;	// expected-warning {{cast from 'const char *const' to 'char *' drops const qualifier}}
+  const char **y2 = (const char **)ptrptr;	// expected-warning {{cast from 'const char *const *' to 'const char **' drops const qualifier}}
+
+  char *z = (char *)(uintptr_t)(const void *)ptr;	// no warning
+  char *z1 = (char *)(const void *)ptr;	// expected-warning {{cast from 'const void *' to 'char *' drops const qualifier}}
+
+  volatile char *vol = 0;
+  char *vol2 = (char *)vol; // expected-warning {{cast from 'volatile char *' to 'char *' drops volatile qualifier}}
+  const volatile char *volc = 0;
+  char *volc2 = (char *)volc; // expected-warning {{cast from 'const volatile char *' to 'char *' drops const and volatile qualifiers}}
+
+  int **intptrptr;
+  const int **intptrptrc = (const int **)intptrptr; // expected-warning {{cast from 'int **' to 'const int **' must have all intermediate pointers const qualified}}
+  volatile int **intptrptrv = (volatile int **)intptrptr; // expected-warning {{cast from 'int **' to 'volatile int **' must have all intermediate pointers const qualified}}
+
+  int *intptr;
+  const int *intptrc = (const int *)intptr;    // no warning
+
+  const char **charptrptrc;
+  char **charptrptr = (char **)charptrptrc; // expected-warning {{cast from 'const char *' to 'char *' drops const qualifier}}
+}
diff --git a/test/Sema/warn-tautological-compare.c b/test/Sema/warn-tautological-compare.c
index 2856edd..55de617 100644
--- a/test/Sema/warn-tautological-compare.c
+++ b/test/Sema/warn-tautological-compare.c
@@ -77,4 +77,10 @@
        (!array && array[0])) {} // expected-warning {{address of array 'array' will always evaluate to 'true'}}
  }
 
-
+// rdar://19256338
+#define SAVE_READ(PTR) if( (PTR) && (&result) ) *result=*PTR;
+void _HTTPClientErrorHandler(int me)
+{
+  int *result;
+  SAVE_READ(&me);
+}
diff --git a/test/Sema/warn-unsequenced.c b/test/Sema/warn-unsequenced.c
index a14d328..70163dc 100644
--- a/test/Sema/warn-unsequenced.c
+++ b/test/Sema/warn-unsequenced.c
@@ -29,6 +29,11 @@
   a = f(a++, 0); // ok
   a = f(++a, a++); // expected-warning {{multiple unsequenced modifications}}
 
+  ++a + f(++a, 0); // expected-warning {{multiple unsequenced modifications}}
+  f(++a, 0) + ++a; // expected-warning {{multiple unsequenced modifications}}
+  a++ + f(a++, 0); // expected-warning {{multiple unsequenced modifications}}
+  f(a++, 0) + a++; // expected-warning {{multiple unsequenced modifications}}
+
   a = ++a; // expected-warning {{multiple unsequenced modifications}}
   a += ++a; // expected-warning {{unsequenced modification and access}}
 
@@ -48,7 +53,7 @@
   (1 ? a : ++a) + a; // ok
   (xs[5] ? ++a : ++a) + a; // FIXME: warn here
 
-  (++a, xs[6] ? ++a : 0) + a; // FIXME: warn here
+  (++a, xs[6] ? ++a : 0) + a; // expected-warning {{unsequenced modification and access}}
 
   // Here, the read of the fourth 'a' might happen before or after the write to
   // the second 'a'.
@@ -84,5 +89,8 @@
 
   (__builtin_classify_type(++a) ? 1 : 0) + ++a; // ok
   (__builtin_constant_p(++a) ? 1 : 0) + ++a; // ok
-  (__builtin_expect(++a, 0) ? 1 : 0) + ++a; // FIXME: warn here
+  (__builtin_expect(++a, 0) ? 1 : 0) + ++a; // expected-warning {{multiple unsequenced modifications}}
+  _Generic(++a, default: 0) + ++a; // ok
+  sizeof(++a) + ++a; // ok
+  _Alignof(++a) + ++a; // expected-warning {{extension}}
 }
diff --git a/test/Sema/warn-unused-value.c b/test/Sema/warn-unused-value.c
index 95cd8fb..edf7915 100644
--- a/test/Sema/warn-unused-value.c
+++ b/test/Sema/warn-unused-value.c
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wunused-value -Wunused-label %s
-// RUN: %clang_cc1 -fsyntax-only -verify -Wunused %s
-// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wunused-value -Wunused-label %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wunused %s
+// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wall %s
 
 int i = 0;
 int j = 0;
@@ -88,3 +88,22 @@
   // rdar://8139785
   f0((int)(a->f0 + 1, 10)); // expected-warning {{expression result unused}}
 }
+
+void blah(int a);
+#define GenTest(x) _Generic(x, default : blah)(x)
+
+void unevaluated_operands(void) {
+  int val = 0;
+
+  (void)sizeof(++val); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+  (void)_Generic(val++, default : 0); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+  (void)_Alignof(val++);  // expected-warning {{expression with side effects has no effect in an unevaluated context}} expected-warning {{'_Alignof' applied to an expression is a GNU extension}}
+
+  // VLAs can have side effects so long as it's part of the type and not
+  // an expression.
+  (void)sizeof(int[++val]); // Ok
+  (void)_Alignof(int[++val]); // Ok
+
+  // Side effects as part of macro expansion are ok.
+  GenTest(val++);
+}
diff --git a/test/Sema/wchar.c b/test/Sema/wchar.c
index a45a14d..9e41f53 100644
--- a/test/Sema/wchar.c
+++ b/test/Sema/wchar.c
@@ -4,7 +4,7 @@
 typedef __WCHAR_TYPE__ wchar_t;
 
 #if defined(_WIN32) || defined(_M_IX86) || defined(__CYGWIN__) \
- || defined(_M_X64) || defined(SHORT_WCHAR)
+ || defined(_M_X64) || defined(__PS4__) || defined(SHORT_WCHAR)
   #define WCHAR_T_TYPE unsigned short
 #elif defined(__arm) || defined(__aarch64__)
   #define WCHAR_T_TYPE unsigned int
diff --git a/test/Sema/x86-builtin-palignr.c b/test/Sema/x86-builtin-palignr.c
index 6f4b90d..f7e70b9 100644
--- a/test/Sema/x86-builtin-palignr.c
+++ b/test/Sema/x86-builtin-palignr.c
@@ -8,10 +8,3 @@
    // be removed when that is fixed.
    return _mm_alignr_pi8(a, b, c); // expected-error {{argument to '__builtin_ia32_palignr' must be a constant integer}} expected-error {{incompatible result type}}
 }
-
-int test2(int N) {
- __m128i white2;
- white2 = __builtin_ia32_pslldqi128(white2, N); // expected-error {{argument to '__builtin_ia32_pslldqi128' must be a constant integer}}
- return 0;
-} 
-
diff --git a/test/SemaCUDA/amdgpu-num-gpr-attr.cu b/test/SemaCUDA/amdgpu-num-gpr-attr.cu
new file mode 100644
index 0000000..83acbc5
--- /dev/null
+++ b/test/SemaCUDA/amdgpu-num-gpr-attr.cu
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+#include "Inputs/cuda.h"
+
+__attribute__((amdgpu_num_vgpr(64)))
+__global__ void test_num_vgpr() { } // expected-error {{'amdgpu_num_vgpr' attribute only applies to kernel functions}}
+
+__attribute__((amdgpu_num_sgpr(32)))
+__global__ void test_num_sgpr() { } // expected-error {{'amdgpu_num_sgpr' attribute only applies to kernel functions}}
+
+// fixme-expected-error@+3 {{'amdgpu_num_sgpr' attribute only applies to kernel functions}}
+// expected-error@+2 {{'amdgpu_num_vgpr' attribute only applies to kernel functions}}
+__attribute__((amdgpu_num_sgpr(32), amdgpu_num_vgpr(64)))
+__global__ void test_num_vgpr_num_sgpr() { }
diff --git a/test/SemaCUDA/function-target-hd.cu b/test/SemaCUDA/function-target-hd.cu
new file mode 100644
index 0000000..25fcc6e
--- /dev/null
+++ b/test/SemaCUDA/function-target-hd.cu
@@ -0,0 +1,71 @@
+// Test the Sema analysis of caller-callee relationships of host device
+// functions when compiling CUDA code. There are 4 permutations of this test as
+// host and device compilation are separate compilation passes, and clang has
+// an option to allow host calls from host device functions. __CUDA_ARCH__ is
+// defined when compiling for the device and TEST_WARN_HD when host calls are
+// allowed from host device functions. So for example, if __CUDA_ARCH__ is
+// defined and TEST_WARN_HD is not then device compilation is happening but
+// host device functions are not allowed to call device functions.
+
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-allow-host-calls-from-host-device -verify %s -DTEST_WARN_HD
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -fcuda-allow-host-calls-from-host-device -verify %s -DTEST_WARN_HD
+
+#include "Inputs/cuda.h"
+
+__host__ void hd1h(void);
+#if defined(__CUDA_ARCH__) && !defined(TEST_WARN_HD)
+// expected-note@-2 {{candidate function not viable: call to __host__ function from __host__ __device__ function}}
+#endif
+__device__ void hd1d(void);
+#ifndef __CUDA_ARCH__
+// expected-note@-2 {{candidate function not viable: call to __device__ function from __host__ __device__ function}}
+#endif
+__host__ void hd1hg(void);
+__device__ void hd1dg(void);
+#ifdef __CUDA_ARCH__
+__host__ void hd1hig(void);
+#if !defined(TEST_WARN_HD)
+// expected-note@-2 {{candidate function not viable: call to __host__ function from __host__ __device__ function}}
+#endif
+#else
+__device__ void hd1dig(void); // expected-note {{candidate function not viable: call to __device__ function from __host__ __device__ function}}
+#endif
+__host__ __device__ void hd1hd(void);
+__global__ void hd1g(void); // expected-note {{'hd1g' declared here}}
+
+__host__ __device__ void hd1(void) {
+#if defined(TEST_WARN_HD) && defined(__CUDA_ARCH__)
+// expected-warning@-2 {{calling __host__ function hd1h from __host__ __device__ function hd1}}
+// expected-warning@-3 {{calling __host__ function hd1hig from __host__ __device__ function hd1}}
+#endif
+  hd1d();
+#ifndef __CUDA_ARCH__
+// expected-error@-2 {{no matching function}}
+#endif
+  hd1h();
+#if defined(__CUDA_ARCH__) && !defined(TEST_WARN_HD)
+// expected-error@-2 {{no matching function}}
+#endif
+
+  // No errors as guarded
+#ifdef __CUDA_ARCH__
+  hd1d();
+#else
+  hd1h();
+#endif
+
+  // Errors as incorrectly guarded
+#ifndef __CUDA_ARCH__
+  hd1dig(); // expected-error {{no matching function}}
+#else
+  hd1hig();
+#ifndef TEST_WARN_HD
+// expected-error@-2 {{no matching function}}
+#endif
+#endif
+
+  hd1hd();
+  hd1g<<<1, 1>>>(); // expected-error {{reference to __global__ function 'hd1g' in __host__ __device__ function}}
+}
diff --git a/test/SemaCUDA/function-target.cu b/test/SemaCUDA/function-target.cu
index 51bc8c9..83dce50 100644
--- a/test/SemaCUDA/function-target.cu
+++ b/test/SemaCUDA/function-target.cu
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify %s
 
 #include "Inputs/cuda.h"
 
@@ -30,15 +31,3 @@
   d1hd();
   d1g<<<1, 1>>>(); // expected-error {{reference to __global__ function 'd1g' in __device__ function}}
 }
-
-__host__ void hd1h(void); // expected-note {{candidate function not viable: call to __host__ function from __host__ __device__ function}}
-__device__ void hd1d(void); // expected-note {{candidate function not viable: call to __device__ function from __host__ __device__ function}}
-__host__ __device__ void hd1hd(void);
-__global__ void hd1g(void); // expected-note {{'hd1g' declared here}}
-
-__host__ __device__ void hd1(void) {
-  hd1h(); // expected-error {{no matching function}}
-  hd1d(); // expected-error {{no matching function}}
-  hd1hd();
-  hd1g<<<1, 1>>>(); // expected-error {{reference to __global__ function 'hd1g' in __host__ __device__ function}}
-}
diff --git a/test/SemaCUDA/implicit-copy.cu b/test/SemaCUDA/implicit-copy.cu
new file mode 100644
index 0000000..b1b4887
--- /dev/null
+++ b/test/SemaCUDA/implicit-copy.cu
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -std=gnu++11 -triple nvptx64-unknown-unknown -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=gnu++11 -triple nvptx64-unknown-unknown -fcuda-is-device -fsyntax-only -verify %s
+
+struct CopyableH {
+  const CopyableH& operator=(const CopyableH& x) { return *this; }
+};
+struct CopyableD {
+  __attribute__((device)) const CopyableD& operator=(const CopyableD x) { return *this; }
+};
+
+struct SimpleH {
+  CopyableH b;
+};
+// expected-note@-3 2 {{candidate function (the implicit copy assignment operator) not viable: call to __host__ function from __device__ function}}
+// expected-note@-4 2 {{candidate function (the implicit move assignment operator) not viable: call to __host__ function from __device__ function}}
+
+struct SimpleD {
+  CopyableD b;
+};
+// expected-note@-3 2 {{candidate function (the implicit copy assignment operator) not viable: call to __device__ function from __host__ function}}
+// expected-note@-4 2 {{candidate function (the implicit move assignment operator) not viable: call to __device__ function from __host__ function}}
+
+void foo1hh() {
+  SimpleH a, b;
+  a = b;
+}
+__attribute__((device)) void foo1hd() {
+  SimpleH a, b;
+  a = b; // expected-error {{no viable overloaded}}
+}
+void foo1dh() {
+  SimpleD a, b;
+  a = b; // expected-error {{no viable overloaded}}
+}
+__attribute__((device)) void foo1dd() {
+  SimpleD a, b;
+  a = b;
+}
+
+void foo2hh(SimpleH &a, SimpleH &b) {
+  a = b;
+}
+__attribute__((device)) void foo2hd(SimpleH &a, SimpleH &b) {
+  a = b; // expected-error {{no viable overloaded}}
+}
+void foo2dh(SimpleD &a, SimpleD &b) {
+  a = b; // expected-error {{no viable overloaded}}
+}
+__attribute__((device)) void foo2dd(SimpleD &a, SimpleD &b) {
+  a = b;
+}
diff --git a/test/SemaCUDA/implicit-member-target.cu b/test/SemaCUDA/implicit-member-target.cu
index 87b05e6..6064560 100644
--- a/test/SemaCUDA/implicit-member-target.cu
+++ b/test/SemaCUDA/implicit-member-target.cu
@@ -146,11 +146,12 @@
 struct B7_with_copy_assign : A7_with_copy_assign {
 };
 
-// expected-note@-3 {{copy assignment operator of 'B7_with_copy_assign' is implicitly deleted}}
+// expected-note@-3 {{candidate function (the implicit copy assignment operator) not viable: call to __device__ function from __host__ function}}
+// expected-note@-4 {{candidate function (the implicit move assignment operator) not viable: call to __device__ function from __host__ function}}
 
 void hostfoo7() {
   B7_with_copy_assign b1, b2;
-  b1 = b2; // expected-error {{object of type 'B7_with_copy_assign' cannot be assigned because its copy assignment operator is implicitly deleted}}
+  b1 = b2; // expected-error {{no viable overloaded '='}}
 }
 
 //------------------------------------------------------------------------------
@@ -176,9 +177,10 @@
 struct B8_with_move_assign : A8_with_move_assign {
 };
 
-// expected-note@-3 {{copy assignment operator of 'B8_with_move_assign' is implicitly deleted because base class 'A8_with_move_assign' has no copy assignment operator}}
+// expected-note@-3 {{candidate function (the implicit copy assignment operator) not viable: call to __device__ function from __host__ function}}
+// expected-note@-4 {{candidate function (the implicit move assignment operator) not viable: call to __device__ function from __host__ function}}
 
 void hostfoo8() {
   B8_with_move_assign b1, b2;
-  b1 = std::move(b2); // expected-error {{object of type 'B8_with_move_assign' cannot be assigned because its copy assignment operator is implicitly deleted}}
+  b1 = std::move(b2); // expected-error {{no viable overloaded '='}}
 }
diff --git a/test/SemaCXX/MicrosoftExtensions.cpp b/test/SemaCXX/MicrosoftExtensions.cpp
index ec3dfce..db5e458 100644
--- a/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/test/SemaCXX/MicrosoftExtensions.cpp
@@ -79,6 +79,7 @@
 
 // __unaligned handling
 typedef char __unaligned *aligned_type;
+typedef struct UnalignedTag { int f; } __unaligned *aligned_type2;
 
 
 template<typename T> void h1(T (__stdcall M::* const )()) { }
@@ -343,6 +344,18 @@
   __declspec(property(get=GetV)) int : 10; // expected-error {{anonymous property is not supported}}
 };
 
+struct MSPropertyClass {
+  int get() { return 42; }
+  int __declspec(property(get = get)) n;
+};
+
+int *f(MSPropertyClass &x) {
+  return &x.n; // expected-error {{address of property expression requested}}
+}
+int MSPropertyClass::*g() {
+  return &MSPropertyClass::n; // expected-error {{address of property expression requested}}
+}
+
 namespace rdar14250378 {
   class Bar {};
 
diff --git a/test/SemaCXX/MicrosoftSuper.cpp b/test/SemaCXX/MicrosoftSuper.cpp
index 13138ca..df63691 100644
--- a/test/SemaCXX/MicrosoftSuper.cpp
+++ b/test/SemaCXX/MicrosoftSuper.cpp
@@ -88,14 +88,14 @@
 struct BaseTemplate {
   typedef int XXX;
 
-  void foo() {}
+  int foo() { return 0; }
 };
 
 struct DerivedFromKnownSpecialization : BaseTemplate<int> {
   __super::XXX a;
   typedef __super::XXX b;
 
-  void test() {
+  void foo() {
     __super::XXX c;
     typedef __super::XXX d;
 
@@ -111,14 +111,14 @@
   __super::XXX c;         // expected-error {{missing 'typename'}}
   typedef __super::XXX d; // expected-error {{missing 'typename'}}
 
-  void test() {
+  void foo() {
     typename __super::XXX e;
     typedef typename __super::XXX f;
 
     __super::XXX g;         // expected-error {{missing 'typename'}}
     typedef __super::XXX h; // expected-error {{missing 'typename'}}
 
-    __super::foo();
+    int x = __super::foo();
   }
 };
 
@@ -130,7 +130,7 @@
   __super::XXX c;         // expected-error {{missing 'typename'}}
   typedef __super::XXX d; // expected-error {{missing 'typename'}}
 
-  void test() {
+  void foo() {
     typename __super::XXX e;
     typedef typename __super::XXX f;
 
@@ -143,7 +143,16 @@
 
 void instantiate() {
   DerivedFromDependentBase<int> d;
-  d.test();
+  d.foo();
   DerivedFromTemplateParameter<Base1> t;
-  t.test();
+  t.foo();
+}
+
+namespace {
+struct B { int a; };
+template <class C>
+struct A : B {
+  // Don't crash on dependent_type_var '->' '__super'
+  void f() { int a = this->__super::a; }
+};
 }
diff --git a/test/SemaCXX/PR21679.cpp b/test/SemaCXX/PR21679.cpp
new file mode 100644
index 0000000..06db2bf
--- /dev/null
+++ b/test/SemaCXX/PR21679.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int w = z.;  // expected-error {{use of undeclared identifier 'z'}} \
+             // expected-error {{expected unqualified-id}}
+
+int x = { y[  // expected-error {{use of undeclared identifier 'y'}} \
+              // expected-note {{to match this '['}} \
+              // expected-note {{to match this '{'}} \
+              // expected-error {{expected ';' after top level declarator}}
+
+// The errors below all occur on the last line of the file, so splitting them
+// among multiple lines doesn't work.
+// expected-error {{expected expression}} expected-error {{expected ']'}} expected-error {{expected '}'}}
diff --git a/test/SemaCXX/PR9461.cpp b/test/SemaCXX/PR9461.cpp
index beed348..f97a208 100644
--- a/test/SemaCXX/PR9461.cpp
+++ b/test/SemaCXX/PR9461.cpp
@@ -22,9 +22,9 @@
 };
 
 template<typename _CharT,typename _Traits,typename _Alloc>
-basic_string<_CharT,_Traits,_Alloc>::basic_string(const _CharT*,const _Alloc&)
+basic_string<_CharT,_Traits,_Alloc>::basic_string(const _CharT* c,const _Alloc&)
 :us(_S_construct)
-{string a;}
+{string a(c);}
 
 struct runtime_error{runtime_error(string);};
 
diff --git a/test/SemaCXX/accessible-base.cpp b/test/SemaCXX/accessible-base.cpp
new file mode 100644
index 0000000..6bf06ce
--- /dev/null
+++ b/test/SemaCXX/accessible-base.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct A {
+  int a;
+};
+
+struct X1 : virtual A 
+{};
+
+struct Y1 : X1, virtual A
+{};
+
+struct Y2 : X1, A // expected-warning{{direct base 'A' is inaccessible due to ambiguity:\n    struct Y2 -> struct X1 -> struct A\n    struct Y2 -> struct A}}
+{};
+
+struct X2 : A 
+{};
+
+struct Z1 : X2, virtual A // expected-warning{{direct base 'A' is inaccessible due to ambiguity:\n    struct Z1 -> struct X2 -> struct A\n    struct Z1 -> struct A}}
+{};
+
+struct Z2 : X2, A // expected-warning{{direct base 'A' is inaccessible due to ambiguity:\n    struct Z2 -> struct X2 -> struct A\n    struct Z2 -> struct A}}
+{};
diff --git a/test/SemaCXX/alignof.cpp b/test/SemaCXX/alignof.cpp
index 011f459..f51146c 100644
--- a/test/SemaCXX/alignof.cpp
+++ b/test/SemaCXX/alignof.cpp
@@ -77,3 +77,10 @@
   // ok, does not complete type of S<-1>::a
   static_assert(alignof(S<-1>::a) == alignof(int), ""); // expected-warning {{GNU extension}}
 }
+
+template <typename T> void n(T) {
+  alignas(T) int T1;
+  char k[__alignof__(T1)];
+  static_assert(sizeof(k) == alignof(long long), "");
+}
+template void n(long long);
diff --git a/test/SemaCXX/anonymous-union.cpp b/test/SemaCXX/anonymous-union.cpp
index fde27b0..46d426c 100644
--- a/test/SemaCXX/anonymous-union.cpp
+++ b/test/SemaCXX/anonymous-union.cpp
@@ -80,10 +80,14 @@
 };
 
 static union {
-  int int_val2;
+  int int_val2; // expected-note{{previous definition is here}}
   float float_val2;
 };
 
+void PR21858() {
+  void int_val2(); // expected-error{{redefinition of 'int_val2' as different kind of symbol}}
+}
+
 void f() {
   int_val2 = 0;
   float_val2 = 0.0;
diff --git a/test/SemaCXX/ast-print.cpp b/test/SemaCXX/ast-print.cpp
index baece3c..1b57406 100644
--- a/test/SemaCXX/ast-print.cpp
+++ b/test/SemaCXX/ast-print.cpp
@@ -53,7 +53,7 @@
     test6fn((int&)y);
 }
 
-// CHECK: S s( 1, 2 );
+// CHECK: S s(1, 2);
 
 template <class S> void test7()
 {
@@ -213,3 +213,9 @@
 // CHECK: struct {{\[\[gnu::visibility\(\"hidden\"\)\]\]}} S;
 struct [[gnu::visibility("hidden")]] S;
 }
+
+// CHECK: struct CXXFunctionalCastExprPrint fce = CXXFunctionalCastExprPrint{};
+struct CXXFunctionalCastExprPrint {} fce = CXXFunctionalCastExprPrint{};
+
+// CHECK: struct CXXTemporaryObjectExprPrint toe = CXXTemporaryObjectExprPrint{};
+struct CXXTemporaryObjectExprPrint { CXXTemporaryObjectExprPrint(); } toe = CXXTemporaryObjectExprPrint{};
diff --git a/test/SemaCXX/atomic-type.cpp b/test/SemaCXX/atomic-type.cpp
index ae18eab..a2b314a 100644
--- a/test/SemaCXX/atomic-type.cpp
+++ b/test/SemaCXX/atomic-type.cpp
@@ -71,6 +71,8 @@
 #if __cplusplus >= 201103L
   _Atomic(X) e2{0}; // expected-error {{illegal initializer}}
   _Atomic(X) a{X(0)};
+  // FIXME: This does not seem like the right answer.
+  _Atomic(int) e3{0}; // expected-error {{illegal initializer}}
 #endif
 
   struct Y {
@@ -79,7 +81,16 @@
   };
   Y y1 = { X(0), 4 };
   Y y2 = { 0, 4 }; // expected-error {{cannot initialize}}
+
   // FIXME: It's not really clear if we should allow these. Generally, C++11
-  // allows extraneous braces around initializers.
-  Y y3 = { { X(0) }, { 4 } }; // expected-error 2{{illegal initializer type}}
+  // allows extraneous braces around initializers. We should at least give the
+  // same answer in all these cases:
+  Y y3 = { X(0), { 4 } }; // expected-error {{illegal initializer type}}
+  Y y4 = { { X(0) }, 4 };
+  _Atomic(int) ai = { 4 }; // expected-error {{illegal initializer type}}
+  _Atomic(X) ax = { X(0) };
+}
+
+bool PR21836(_Atomic(int) *x) {
+    return *x;
 }
diff --git a/test/SemaCXX/attr-cxx0x-fixit.cpp b/test/SemaCXX/attr-cxx0x-fixit.cpp
new file mode 100644
index 0000000..6a6cdc1
--- /dev/null
+++ b/test/SemaCXX/attr-cxx0x-fixit.cpp
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s

+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -std=c++11 %s 2>&1 | FileCheck %s

+

+[[noreturn()]] void f(); // expected-error {{attribute 'noreturn' cannot have an argument list}} \

+// CHECK: fix-it:"{{.*}}":{4:11-4:13}:""

diff --git a/test/SemaCXX/attr-flag-enum-reject.cpp b/test/SemaCXX/attr-flag-enum-reject.cpp
new file mode 100644
index 0000000..f28d60c
--- /dev/null
+++ b/test/SemaCXX/attr-flag-enum-reject.cpp
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -x c++ -Wassign-enum %s
+
+enum __attribute__((flag_enum)) flag { // expected-warning {{ignored}}
+};
diff --git a/test/SemaCXX/attr-optnone.cpp b/test/SemaCXX/attr-optnone.cpp
index eaa5000..58776ca 100644
--- a/test/SemaCXX/attr-optnone.cpp
+++ b/test/SemaCXX/attr-optnone.cpp
@@ -3,11 +3,37 @@
 int foo() __attribute__((optnone));
 int bar() __attribute__((optnone)) __attribute__((noinline));
 
-int baz() __attribute__((always_inline)) __attribute__((optnone)); // expected-error{{'always_inline' and 'optnone' attributes are not compatible}}
-int quz() __attribute__((optnone)) __attribute__((always_inline)); // expected-error{{'optnone' and 'always_inline' attributes are not compatible}}
+int baz() __attribute__((always_inline)) __attribute__((optnone)); // expected-warning{{'always_inline' attribute ignored}} expected-note{{conflicting attribute is here}}
+int quz() __attribute__((optnone)) __attribute__((always_inline)); // expected-warning{{'always_inline' attribute ignored}} expected-note{{conflicting attribute is here}}
 
-__forceinline __attribute__((optnone)) int bax(); // expected-error{{'__forceinline' and 'optnone' attributes are not compatible}}
-__attribute__((optnone)) __forceinline int qux(); // expected-error{{'optnone' and '__forceinline' attributes are not compatible}}
+__attribute__((always_inline)) int baz1(); // expected-warning{{'always_inline' attribute ignored}}
+__attribute__((optnone)) int baz1() { return 1; } // expected-note{{conflicting attribute is here}}
+
+__attribute__((optnone)) int quz1(); // expected-note{{conflicting attribute is here}}
+__attribute__((always_inline)) int quz1() { return 1; } // expected-warning{{'always_inline' attribute ignored}}
+
+int bay() __attribute__((minsize)) __attribute__((optnone)); // expected-warning{{'minsize' attribute ignored}} expected-note{{conflicting}}
+int quy() __attribute__((optnone)) __attribute__((minsize)); // expected-warning{{'minsize' attribute ignored}} expected-note{{conflicting}}
+
+__attribute__((minsize)) int bay1(); // expected-warning{{'minsize' attribute ignored}}
+__attribute__((optnone)) int bay1() { return 1; } // expected-note{{conflicting attribute is here}}
+
+__attribute__((optnone)) int quy1(); // expected-note{{conflicting attribute is here}}
+__attribute__((minsize)) int quy1() { return 1; } // expected-warning{{'minsize' attribute ignored}}
+
+__attribute__((always_inline)) // expected-warning{{'always_inline' attribute ignored}}
+  __attribute__((minsize)) // expected-warning{{'minsize' attribute ignored}}
+void bay2();
+__attribute__((optnone)) // expected-note 2 {{conflicting}}
+void bay2() {}
+
+__forceinline __attribute__((optnone)) int bax(); // expected-warning{{'__forceinline' attribute ignored}} expected-note{{conflicting}}
+__attribute__((optnone)) __forceinline int qux(); // expected-warning{{'__forceinline' attribute ignored}} expected-note{{conflicting}}
+
+__forceinline int bax2(); // expected-warning{{'__forceinline' attribute ignored}}
+__attribute__((optnone)) int bax2() { return 1; } // expected-note{{conflicting}}
+__attribute__((optnone)) int qux2(); // expected-note{{conflicting}}
+__forceinline int qux2() { return 1; } // expected-warning{{'__forceinline' attribute ignored}}
 
 int globalVar __attribute__((optnone)); // expected-warning{{'optnone' attribute only applies to functions}}
 
@@ -29,8 +55,8 @@
 [[clang::optnone]]
 int bar2() __attribute__((noinline));
 
-[[clang::optnone]]
-int baz2() __attribute__((always_inline)); // expected-error{{'always_inline' and 'optnone' attributes are not compatible}}
+[[clang::optnone]] // expected-note {{conflicting}}
+int baz2() __attribute__((always_inline)); // expected-warning{{'always_inline' attribute ignored}}
 
 [[clang::optnone]] int globalVar2; //expected-warning{{'optnone' attribute only applies to functions}}
 
diff --git a/test/SemaCXX/call-with-static-chain.cpp b/test/SemaCXX/call-with-static-chain.cpp
new file mode 100644
index 0000000..45fe2ac
--- /dev/null
+++ b/test/SemaCXX/call-with-static-chain.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int &f();
+
+struct A {
+  void f();
+};
+
+typedef int I;
+
+void g() {
+  __builtin_call_with_static_chain(f(), f) = 42;
+  __builtin_call_with_static_chain(A().f(), f); // expected-error {{first argument to __builtin_call_with_static_chain must be a non-member call expression}}
+  __builtin_call_with_static_chain((42).~I(), f); // expected-error {{first argument to __builtin_call_with_static_chain must not be a pseudo-destructor call}}
+}
diff --git a/test/SemaCXX/class-layout.cpp b/test/SemaCXX/class-layout.cpp
index 64c8ceb..96552de 100644
--- a/test/SemaCXX/class-layout.cpp
+++ b/test/SemaCXX/class-layout.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++98
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++98 -Wno-inaccessible-base
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base
 // expected-no-diagnostics
 
 #define SA(n, p) int a##n[(p) ? 1 : -1]
diff --git a/test/SemaCXX/class.cpp b/test/SemaCXX/class.cpp
index 636f584..a669440 100644
--- a/test/SemaCXX/class.cpp
+++ b/test/SemaCXX/class.cpp
@@ -119,9 +119,9 @@
 // PR5415 - don't hang!
 struct S
 {
-  void f(); // expected-note 1 {{previous declaration}}
-  void S::f() {} // expected-error {{extra qualification on member}} expected-error {{class member cannot be redeclared}} expected-note {{previous declaration}} expected-note {{previous definition}}
-  void f() {} // expected-error {{class member cannot be redeclared}} expected-error {{redefinition}}
+  void f(); // expected-note 1 {{previous declaration}} expected-note {{previous declaration}}
+  void S::f() {} // expected-error {{extra qualification on member}} expected-error {{class member cannot be redeclared}}
+  void f() {} // expected-error {{class member cannot be redeclared}}
 };
 
 // Don't crash on this bogus code.
diff --git a/test/SemaCXX/const-cast.cpp b/test/SemaCXX/const-cast.cpp
index cb9937c..330e186 100644
--- a/test/SemaCXX/const-cast.cpp
+++ b/test/SemaCXX/const-cast.cpp
@@ -64,3 +64,6 @@
   (void)const_cast<int&&>(0); // expected-error {{const_cast from rvalue to reference type 'int &&'}} expected-warning {{C++11}}
   return **var3;
 }
+
+template <typename T>
+char *PR21845() { return const_cast<char *>((void)T::x); } // expected-error {{const_cast from 'void' to 'char *' is not allowed}}
diff --git a/test/SemaCXX/constant-expression-cxx11.cpp b/test/SemaCXX/constant-expression-cxx11.cpp
index d50dd0b..9c62e9e 100644
--- a/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1613,7 +1613,8 @@
   A &g();
   constexpr auto &x = typeid(f());
   constexpr auto &y = typeid(g()); // expected-error{{constant expression}} \
-  // expected-note{{typeid applied to expression of polymorphic type 'TypeId::A' is not allowed in a constant expression}}
+  // expected-note{{typeid applied to expression of polymorphic type 'TypeId::A' is not allowed in a constant expression}} \
+  // expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
 }
 
 namespace PR14203 {
@@ -1712,6 +1713,9 @@
     return sum(ints.begin(), ints.end());
   }
   static_assert(sum({1, 2, 3, 4, 5}) == 15, "");
+
+  static_assert(*std::initializer_list<int>{1, 2, 3}.begin() == 1, "");
+  static_assert(std::initializer_list<int>{1, 2, 3}.begin()[2] == 3, "");
 }
 
 namespace StmtExpr {
@@ -1955,3 +1959,38 @@
   constexpr E2 e2b(e2); // expected-error {{constant expression}} expected-note{{read of non-const}} expected-note {{in call}}
   constexpr E3 e3b(e3);
 }
+
+namespace PR21786 {
+  extern void (*start[])();
+  extern void (*end[])();
+  static_assert(&start != &end, ""); // expected-error {{constant expression}}
+  static_assert(&start != nullptr, "");
+
+  struct Foo;
+  struct Bar {
+    static const Foo x;
+    static const Foo y;
+  };
+  static_assert(&Bar::x != nullptr, "");
+  static_assert(&Bar::x != &Bar::y, "");
+}
+
+namespace PR21859 {
+  constexpr int Fun() { return; } // expected-error {{non-void constexpr function 'Fun' should return a value}}
+  constexpr int Var = Fun(); // expected-error {{constexpr variable 'Var' must be initialized by a constant expression}}
+}
+
+struct InvalidRedef {
+  int f; // expected-note{{previous definition is here}}
+  constexpr int f(void); // expected-error{{redefinition of 'f'}} expected-warning{{will not be implicitly 'const'}}
+};
+
+namespace PR17938 {
+  template <typename T> constexpr T const &f(T const &x) { return x; }
+
+  struct X {};
+  struct Y : X {};
+  struct Z : Y { constexpr Z() {} };
+
+  static constexpr auto z = f(Z());
+}
diff --git a/test/SemaCXX/constructor-initializer.cpp b/test/SemaCXX/constructor-initializer.cpp
index 81dc19e..e3ab610 100644
--- a/test/SemaCXX/constructor-initializer.cpp
+++ b/test/SemaCXX/constructor-initializer.cpp
@@ -26,7 +26,7 @@
   D() : B(), C() { }
 };
 
-class E : public D, public B { 
+class E : public D, public B {  // expected-warning{{direct base 'B' is inaccessible due to ambiguity:\n    class E -> class D -> class C -> class B\n    class E -> class B}}
 public:
   E() : B(), D() { } // expected-error{{base class initializer 'B' names both a direct base class and an inherited virtual base class}}
 };
@@ -94,7 +94,7 @@
                            Derived::Base1(), // expected-error {{type 'Derived::Base1' is not a direct or virtual base of 'Current'}}
                            Derived::V(),
                            ::NonExisting(), // expected-error {{member initializer 'NonExisting' does not name a non-static data member or}}
-                           INT::NonExisting()  {} // expected-error {{'INT' (aka 'int') is not a class, namespace, or scoped enumeration}} \
+                           INT::NonExisting()  {} // expected-error {{'INT' (aka 'int') is not a class, namespace, or enumeration}} \
                                                   // expected-error {{member initializer 'NonExisting' does not name a non-static data member or}}
 };
 
@@ -204,7 +204,8 @@
 };
 
 struct B : virtual A { };
-struct C : A, B { };
+
+  struct C : A, B { }; // expected-warning{{direct base 'Test2::A' is inaccessible due to ambiguity:\n    struct Test2::C -> struct Test2::A\n    struct Test2::C -> struct Test2::B -> struct Test2::A}}
 
 C f(C c) {
   return c;
diff --git a/test/SemaCXX/conversion-function.cpp b/test/SemaCXX/conversion-function.cpp
index ede23a2..077e4d9 100644
--- a/test/SemaCXX/conversion-function.cpp
+++ b/test/SemaCXX/conversion-function.cpp
@@ -172,12 +172,10 @@
 
 namespace crazy_declarators {
   struct A {
-    (&operator bool())(); // expected-error {{must use a typedef to declare a conversion to 'bool (&)()'}}
-
-    // FIXME: This diagnostic is misleading (the correct spelling
-    // would be 'operator int*'), but it's a corner case of a
-    // rarely-used syntax extension.
-    *operator int();  // expected-error {{must use a typedef to declare a conversion to 'int *'}}
+    (&operator bool())(); // expected-error {{use a typedef to declare a conversion to 'bool (&)()'}}
+    *operator int();  // expected-error {{put the complete type after 'operator'}}
+    // No suggestion of using a typedef here; that's not possible.
+    template<typename T> (&operator T())(); // expected-error-re {{cannot specify any part of a return type in the declaration of a conversion function{{$}}}}
   };
 }
 
diff --git a/test/SemaCXX/crashes.cpp b/test/SemaCXX/crashes.cpp
index 6ae476f..12251bb 100644
--- a/test/SemaCXX/crashes.cpp
+++ b/test/SemaCXX/crashes.cpp
@@ -175,16 +175,16 @@
 namespace pr16964 {
   template<typename> struct bs {
     bs();
-    static int* member();
+    static int* member(); // expected-note{{possible target}}
     member();  // expected-error{{C++ requires a type specifier for all declarations}}
     static member();  // expected-error{{C++ requires a type specifier for all declarations}}
-    static int* member(int);
+    static int* member(int); // expected-note{{possible target}}
   };
 
-  template<typename T> bs<T>::bs() { member; }
+  template<typename T> bs<T>::bs() { member; }  // expected-error{{did you mean to call it}}
 
   bs<int> test() {
-    return bs<int>();
+    return bs<int>(); // expected-note{{in instantiation}}
   }
 }
 
@@ -195,7 +195,7 @@
   struct forward_iterator_tag : public input_iterator_tag {};
 
   template<typename _CharT, typename _Traits, typename _Alloc> struct basic_string {
-    struct _Alloc_hider : _Alloc {};
+    struct _Alloc_hider : _Alloc { _Alloc_hider(_CharT*, const _Alloc&); };
     mutable _Alloc_hider _M_dataplus;
     template<class _InputIterator> basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a = _Alloc());
     template<class _InIterator> static _CharT* _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, input_iterator_tag);
@@ -206,12 +206,11 @@
   template<typename _CharT, typename _Traits, typename _Alloc>
   template<typename _InputIterator>
   basic_string<_CharT, _Traits, _Alloc>:: basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a)
-  : _M_dataplus(_S_construct(__beg, __end, __a), __a) {}
+  : _M_dataplus(_S_construct(__beg, __end, __a, input_iterator_tag()), __a) {}
 
   template<typename _CharT, typename _Traits = char_traits<_CharT>, typename _Alloc = allocator<_CharT> > struct basic_stringbuf {
     typedef _CharT char_type;
     typedef basic_string<char_type, _Traits, _Alloc> __string_type;
-    typedef typename __string_type::size_type __size_type;
     __string_type str() const {__string_type((char_type*)0,(char_type*)0);}
   };
 
diff --git a/test/SemaCXX/cxx0x-cursory-default-delete.cpp b/test/SemaCXX/cxx0x-cursory-default-delete.cpp
index 375cf4a..e333403 100644
--- a/test/SemaCXX/cxx0x-cursory-default-delete.cpp
+++ b/test/SemaCXX/cxx0x-cursory-default-delete.cpp
@@ -42,6 +42,28 @@
   bad_decls& operator = (const bad_decls&) const = default; // expected-error {{may not have 'const', 'constexpr' or 'volatile' qualifiers}}
 };
 
+struct DefaultDelete {
+  DefaultDelete() = default; // expected-note {{previous declaration is here}}
+  DefaultDelete() = delete; // expected-error {{constructor cannot be redeclared}}
+
+  ~DefaultDelete() = default; // expected-note {{previous declaration is here}}
+  ~DefaultDelete() = delete; // expected-error {{destructor cannot be redeclared}}
+
+  DefaultDelete &operator=(const DefaultDelete &) = default; // expected-note {{previous declaration is here}}
+  DefaultDelete &operator=(const DefaultDelete &) = delete; // expected-error {{class member cannot be redeclared}}
+};
+
+struct DeleteDefault {
+  DeleteDefault() = delete; // expected-note {{previous definition is here}}
+  DeleteDefault() = default; // expected-error {{constructor cannot be redeclared}}
+
+  ~DeleteDefault() = delete; // expected-note {{previous definition is here}}
+  ~DeleteDefault() = default; // expected-error {{destructor cannot be redeclared}}
+
+  DeleteDefault &operator=(const DeleteDefault &) = delete; // expected-note {{previous definition is here}}
+  DeleteDefault &operator=(const DeleteDefault &) = default; // expected-error {{class member cannot be redeclared}}
+};
+
 struct A {}; struct B {};
 
 struct except_spec_a {
diff --git a/test/SemaCXX/cxx0x-defaulted-functions.cpp b/test/SemaCXX/cxx0x-defaulted-functions.cpp
index bc03bcd..617a257 100644
--- a/test/SemaCXX/cxx0x-defaulted-functions.cpp
+++ b/test/SemaCXX/cxx0x-defaulted-functions.cpp
@@ -173,7 +173,7 @@
 
 extern "C" {
  template<typename _Tp> // expected-error {{templates must have C++ linkage}}
- void PR13573(const _Tp&) = delete; // expected-error {{only functions can have deleted definitions}}
+ void PR13573(const _Tp&) = delete;
 }
 
 namespace PR15597 {
diff --git a/test/SemaCXX/cxx0x-initializer-constructor.cpp b/test/SemaCXX/cxx0x-initializer-constructor.cpp
index 3ea5309..6202bf6 100644
--- a/test/SemaCXX/cxx0x-initializer-constructor.cpp
+++ b/test/SemaCXX/cxx0x-initializer-constructor.cpp
@@ -142,6 +142,7 @@
 
     one ov2(int);
     two ov2(F<3>);
+    // expected-warning@+1 {{braces around scalar initializer}}
     static_assert(sizeof(ov2({1})) == sizeof(one), "bad overload"); // list -> int ranks as identity
     static_assert(sizeof(ov2({1, 2, 3})) == sizeof(two), "bad overload"); // list -> F only viable
   }
@@ -214,7 +215,10 @@
 
 namespace PR12117 {
   struct A { A(int); }; 
-  struct B { B(A); } b{{0}};
+  struct B { B(A); } b{{0}};   //FIXME: non-conformant. Temporary fix until standard resolution.
+                                // expected- error {{call to constructor of 'struct B' is ambiguous}} \
+                                // expected- note 2{{candidate is the implicit}} \
+                                // expected- note {{candidate constructor}}
   struct C { C(int); } c{0};
 }
 
diff --git a/test/SemaCXX/cxx0x-initializer-references.cpp b/test/SemaCXX/cxx0x-initializer-references.cpp
index d1a9ed3..f9164fb 100644
--- a/test/SemaCXX/cxx0x-initializer-references.cpp
+++ b/test/SemaCXX/cxx0x-initializer-references.cpp
@@ -105,12 +105,13 @@
   B b2 { { 0 } };
   B b3 { { { 0 } } }; // expected-warning {{braces around scalar init}}
 
-  struct C { C(int); };
+  struct C { C(int); };   // expected-note 2{{candidate constructor (the implicit}} \
+                          // expected-note {{candidate constructor not viable: cannot convert initializer list argument to 'int'}}
   struct D { C &&r; };
   D d1 { 0 }; // ok, 0 implicitly converts to C
   D d2 { { 0 } }; // ok, { 0 } calls C(0)
-  D d3 { { { 0 } } }; // ok, { { 0 } } calls C({ 0 })
-  D d4 { { { { 0 } } } }; // expected-warning {{braces around scalar init}}
+  D d3 { { { 0 } } }; // ok, { { 0 } } calls C({ 0 }), expected-warning {{braces around scalar init}}
+  D d4 { { { { 0 } } } }; // expected-error {{no matching constructor for initialization of 'inner_init::C &&'}}
 
   struct E { explicit E(int); }; // expected-note 2{{here}}
   struct F { E &&r; };
diff --git a/test/SemaCXX/cxx0x-initializer-scalars.cpp b/test/SemaCXX/cxx0x-initializer-scalars.cpp
index 1475dcf..c9d5ffd 100644
--- a/test/SemaCXX/cxx0x-initializer-scalars.cpp
+++ b/test/SemaCXX/cxx0x-initializer-scalars.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s -pedantic-errors
 
 struct one { char c[1]; };
 struct two { char c[2]; };
@@ -55,7 +55,7 @@
     int ar[10];
     (void) ar[{1}]; // expected-error {{array subscript is not an integer}}
 
-    return {1};
+    return {1}; // expected-warning {{braces around scalar init}}
   }
 
   void inline_init() {
@@ -70,15 +70,15 @@
 
   void function_call() {
     void takes_int(int);
-    takes_int({1});
+    takes_int({1}); // expected-warning {{braces around scalar init}}
   }
 
   void overloaded_call() {
     one overloaded(int);
     two overloaded(double);
 
-    static_assert(sizeof(overloaded({0})) == sizeof(one), "bad overload");
-    static_assert(sizeof(overloaded({0.0})) == sizeof(two), "bad overload");
+    static_assert(sizeof(overloaded({0})) == sizeof(one), "bad overload"); // expected-warning {{braces around scalar init}}
+    static_assert(sizeof(overloaded({0.0})) == sizeof(two), "bad overload"); // expected-warning {{braces around scalar init}}
 
     void ambiguous(int, double); // expected-note {{candidate}}
     void ambiguous(double, int); // expected-note {{candidate}}
diff --git a/test/SemaCXX/cxx0x-initializer-stdinitializerlist.cpp b/test/SemaCXX/cxx0x-initializer-stdinitializerlist.cpp
index 70f7c64..a78f022 100644
--- a/test/SemaCXX/cxx0x-initializer-stdinitializerlist.cpp
+++ b/test/SemaCXX/cxx0x-initializer-stdinitializerlist.cpp
@@ -117,6 +117,7 @@
 
 void auto_deduction() {
   auto l = {1, 2, 3, 4};
+  auto l2 {1, 2, 3, 4}; // expected-warning {{will change meaning in a future version of Clang}}
   static_assert(same_type<decltype(l), std::initializer_list<int>>::value, "");
   auto bl = {1, 2.0}; // expected-error {{cannot deduce}}
 
@@ -259,3 +260,18 @@
   template<typename T> void g() { int k = f({0}); }
   template void g<int>();
 }
+
+namespace TemporaryInitListSourceRange_PR22367 {
+  struct A {
+    constexpr A() {}
+    A(std::initializer_list<int>); // expected-note {{here}}
+  };
+  constexpr int f(A) { return 0; }
+  constexpr int k = f( // expected-error {{must be initialized by a constant expression}}
+      // The point of this test is to check that the caret points to
+      // 'std::initializer_list', not to '{0}'.
+      std::initializer_list // expected-note {{constructor}}
+      <int>
+      {0}
+      );
+}
diff --git a/test/SemaCXX/cxx0x-return-init-list.cpp b/test/SemaCXX/cxx0x-return-init-list.cpp
index da83271..84bd89b 100644
--- a/test/SemaCXX/cxx0x-return-init-list.cpp
+++ b/test/SemaCXX/cxx0x-return-init-list.cpp
@@ -4,7 +4,7 @@
 // required for libstdc++ 4.5) is supported in C++98.
 
 int test0(int i) {
-  return { i }; // expected-warning{{generalized initializer lists are a C++11 extension}}
+  return { i }; // expected-warning{{generalized initializer lists are a C++11 extension}} expected-warning {{scalar}}
 }
 
 template<typename T, typename U>
diff --git a/test/SemaCXX/cxx11-gnu-attrs.cpp b/test/SemaCXX/cxx11-gnu-attrs.cpp
index 9f18224..ac9cc55 100644
--- a/test/SemaCXX/cxx11-gnu-attrs.cpp
+++ b/test/SemaCXX/cxx11-gnu-attrs.cpp
@@ -15,6 +15,9 @@
 void alias1() {}
 void aliasa [[gnu::alias("_Z6alias1v")]] ();
 
+extern struct PR22493Ty {
+} PR22493 [[gnu::alias("_ZN7pcrecpp2RE6no_argE")]];
+
 [[gnu::aligned(8)]] int aligned;
 void aligned_fn [[gnu::aligned(32)]] ();
 struct [[gnu::aligned(8)]] aligned_struct {};
diff --git a/test/SemaCXX/cxx11-thread-unsupported.cpp b/test/SemaCXX/cxx11-thread-unsupported.cpp
new file mode 100644
index 0000000..d3fcf82
--- /dev/null
+++ b/test/SemaCXX/cxx11-thread-unsupported.cpp
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -std=c++11 -triple=x86_64-apple-macosx10.6 -verify %s
+
+void f() {
+  thread_local int x; // expected-error {{thread-local storage is not supported for the current target}}
+}
diff --git a/test/SemaCXX/cxx1y-constexpr-not-const.cpp b/test/SemaCXX/cxx1y-constexpr-not-const.cpp
index 071b39c..2352bb7 100644
--- a/test/SemaCXX/cxx1y-constexpr-not-const.cpp
+++ b/test/SemaCXX/cxx1y-constexpr-not-const.cpp
@@ -11,8 +11,6 @@
 
 // expected-error@6 {{class member cannot be redeclared}}
 // expected-note@5 {{previous}}
-// expected-error@6 {{non-constexpr declaration of 'f' follows constexpr declaration}}
-// expected-note@5 {{previous}}
 #else
 // expected-warning@5 {{'constexpr' non-static member function will not be implicitly 'const' in C++14; add 'const' to avoid a change in behavior}}
 #endif
diff --git a/test/SemaCXX/cxx1y-deduced-return-type.cpp b/test/SemaCXX/cxx1y-deduced-return-type.cpp
index 6086416..225d234 100644
--- a/test/SemaCXX/cxx1y-deduced-return-type.cpp
+++ b/test/SemaCXX/cxx1y-deduced-return-type.cpp
@@ -21,8 +21,8 @@
 int conv1d = conv1.operator int(); // expected-error {{no member named 'operator int'}}
 
 struct Conv2 {
-  operator auto() { return 0; }  // expected-note 2{{previous}}
-  operator auto() { return 0.; } // expected-error {{cannot be redeclared}} expected-error {{redefinition of 'operator auto'}}
+  operator auto() { return 0; }  // expected-note {{previous}}
+  operator auto() { return 0.; } // expected-error {{cannot be redeclared}} expected-error {{cannot initialize return object of type 'auto' with an rvalue of type 'double'}}
 };
 
 struct Conv3 {
@@ -483,3 +483,16 @@
     int g = a - a;
   }
 }
+
+namespace TrailingReturnTypeForConversionOperator {
+  struct X {
+    operator auto() -> int { return 0; } // expected-error {{cannot specify any part of a return type in the declaration of a conversion function; put the complete type after 'operator'}}
+  } x;
+  int k = x.operator auto();
+
+  struct Y {
+    operator auto() -> int & { // expected-error {{cannot specify}}
+      return 0; // expected-error {{cannot bind to}}
+    }
+  };
+};
diff --git a/test/SemaCXX/cxx1y-generic-lambdas.cpp b/test/SemaCXX/cxx1y-generic-lambdas.cpp
index 8e07b80..90ecf69 100644
--- a/test/SemaCXX/cxx1y-generic-lambdas.cpp
+++ b/test/SemaCXX/cxx1y-generic-lambdas.cpp
@@ -918,3 +918,16 @@
 
 
 } //end ns inclass_lambdas_within_nested_classes
+
+namespace pr21684_disambiguate_auto_followed_by_ellipsis_no_id {
+int a = [](auto ...) { return 0; }();
+}
+
+namespace PR22117 {
+  int x = [](auto) {
+    return [](auto... run_args) {
+      using T = int(decltype(run_args)...);
+      return 0;
+    };
+  }(0)(0);
+}
diff --git a/test/SemaCXX/cxx1y-sized-deallocation.cpp b/test/SemaCXX/cxx1y-sized-deallocation.cpp
index 81a8eeb..3ec65a6 100644
--- a/test/SemaCXX/cxx1y-sized-deallocation.cpp
+++ b/test/SemaCXX/cxx1y-sized-deallocation.cpp
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 -std=c++1y -verify %s -fsized-deallocation -fexceptions -fcxx-exceptions
 
 using size_t = decltype(sizeof(0));
+void operator delete(void *, size_t) noexcept;   // expected-note {{'operator delete' declared here}}
+void operator delete[](void *, size_t) noexcept;
 
 void f(void *p, void *q) {
   // OK, implicitly declared.
diff --git a/test/SemaCXX/cxx1y-variable-templates_in_class.cpp b/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
index f6f77f0..93a2095 100644
--- a/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
+++ b/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
@@ -321,3 +321,9 @@
   // TODO:
 }
 
+namespace bitfield {
+struct S {
+  template <int I>
+  static int f : I; // expected-error {{static member 'f' cannot be a bit-field}}
+};
+}
diff --git a/test/SemaCXX/cxx98-compat.cpp b/test/SemaCXX/cxx98-compat.cpp
index 029e909..4227272 100644
--- a/test/SemaCXX/cxx98-compat.cpp
+++ b/test/SemaCXX/cxx98-compat.cpp
@@ -74,10 +74,10 @@
   InitListCtor ilc = { true, false }; // expected-warning {{initialization of initializer_list object is incompatible with C++98}}
   const int &r = { 0 }; // expected-warning {{reference initialized from initializer list is incompatible with C++98}}
   struct { int a; const int &r; } rr = { 0, {0} }; // expected-warning {{reference initialized from initializer list is incompatible with C++98}}
-  return { 0 }; // expected-warning {{generalized initializer lists are incompatible with C++98}}
+  return { 0 }; // expected-warning {{generalized initializer lists are incompatible with C++98}} expected-warning {{scalar}}
 }
 struct DelayedDefaultArgumentParseInitList {
-  void f(int i = {1}) { // expected-warning {{generalized initializer lists are incompatible with C++98}}
+  void f(int i = {1}) { // expected-warning {{generalized initializer lists are incompatible with C++98}} expected-warning {{scalar}}
   }
 };
 
diff --git a/test/SemaCXX/default-assignment-operator.cpp b/test/SemaCXX/default-assignment-operator.cpp
index 7ef6f77..f202b61 100644
--- a/test/SemaCXX/default-assignment-operator.cpp
+++ b/test/SemaCXX/default-assignment-operator.cpp
@@ -112,7 +112,7 @@
 
   struct X1 : public virtual X0 { };
 
-  struct X2 : X0, X1 { };
+  struct X2 : X0, X1 { }; // expected-warning{{direct base 'MultiplePaths::X0' is inaccessible due to ambiguity:\n    struct MultiplePaths::X2 -> struct MultiplePaths::X0\n    struct MultiplePaths::X2 -> struct MultiplePaths::X1 -> struct MultiplePaths::X0}}
 
   void f(X2 x2) { x2 = x2; }
 }
diff --git a/test/SemaCXX/default2.cpp b/test/SemaCXX/default2.cpp
index 1626044..c4d40b4 100644
--- a/test/SemaCXX/default2.cpp
+++ b/test/SemaCXX/default2.cpp
@@ -122,3 +122,9 @@
   void A(int length = -1 ) {  } 
   void B() { A(); }
 };
+
+template <int I = (1 * I)> struct S {};  // expected-error-re {{use of undeclared identifier 'I'{{$}}}}
+S<1> s;
+
+template <int I1 = I2, int I2 = 1> struct T {};  // expected-error-re {{use of undeclared identifier 'I2'{{$}}}}
+T<0, 1> t;
diff --git a/test/SemaCXX/deleted-function.cpp b/test/SemaCXX/deleted-function.cpp
index d7ef9b2..bd6fc09 100644
--- a/test/SemaCXX/deleted-function.cpp
+++ b/test/SemaCXX/deleted-function.cpp
@@ -65,3 +65,31 @@
 
 void test4() {} // expected-note {{previous definition is here}}
 void test4() = delete; // expected-error {{redefinition of 'test4'}}
+
+struct DelCtor { // expected-note 4{{implicit}}
+  DelCtor(int) = delete; // expected-note 14{{deleted}}
+  // ensure the class is not an aggregate
+  DelCtor(int, int, int, int);
+};
+DelCtor dc1 = 0; // expected-error {{deleted}}
+DelCtor dc2(0); // expected-error {{deleted}}
+DelCtor dc3 = {0}; // expected-error {{deleted}}
+DelCtor dc4{0}; // expected-error {{deleted}}
+DelCtor dc5 = (DelCtor)0; // expected-error {{deleted}}
+DelCtor dc6 = DelCtor(0); // expected-error {{deleted}}
+DelCtor dc7 = DelCtor{0}; // expected-error {{deleted}}
+DelCtor *dc8 = new DelCtor(0); // expected-error {{deleted}}
+DelCtor *dc9 = new DelCtor{0}; // expected-error {{deleted}}
+DelCtor dc10[] = {0}; // expected-error {{deleted}}
+int use_dc(DelCtor); // expected-note 2{{here}}
+int dc11 = use_dc(0); // expected-error {{deleted}}
+int dc12 = use_dc({0}); // expected-error {{deleted}}
+int use_dcr(const DelCtor &); // expected-note {{here}}
+int dc13 = use_dcr(0); // expected-error {{deleted}}
+int dc14 = use_dcr({0}); // expected-error {{deleted}}
+
+struct DelCtorTemplate {
+  template<typename T> DelCtorTemplate(T) = delete; // expected-note {{deleted}}
+};
+int use_dct(const DelCtorTemplate &);
+int dc15 = use_dct(0); // expected-error {{deleted}}
diff --git a/test/SemaCXX/derived-to-base-ambig.cpp b/test/SemaCXX/derived-to-base-ambig.cpp
index 129ec79..93bd361 100644
--- a/test/SemaCXX/derived-to-base-ambig.cpp
+++ b/test/SemaCXX/derived-to-base-ambig.cpp
@@ -14,8 +14,8 @@
 class B2 : public virtual A2 { };
 class C2 : virtual public A2 { };
 class D2 : public B2, public C2 { };
-class E2 : public D2, public C2, public virtual A2 { };
-class F2 : public E2, public A2 { };
+class E2 : public D2, public C2, public virtual A2 { }; // expected-warning{{direct base 'C2' is inaccessible due to ambiguity:\n    class E2 -> class D2 -> class C2\n    class E2 -> class C2}}
+class F2 : public E2, public A2 { }; // expected-warning{{direct base 'A2' is inaccessible due to ambiguity:\n    class F2 -> class E2 -> class D2 -> class B2 -> class A2\n    class F2 -> class A2}}
 
 void g(E2* e2, F2* f2) {
   Object2* o2;
diff --git a/test/SemaCXX/destructor.cpp b/test/SemaCXX/destructor.cpp
index 5305ff5..60cb0ef 100644
--- a/test/SemaCXX/destructor.cpp
+++ b/test/SemaCXX/destructor.cpp
@@ -173,6 +173,12 @@
   ~S7();
 };
 
+struct S8 {} s8;
+
+UnknownType S8::~S8() { // expected-error {{unknown type name 'UnknownType'}}
+  s8.~S8();
+}
+
 template<class T> class TS : public B {
   virtual void m();
 };
@@ -386,3 +392,14 @@
   volatile ~S() { } // expected-error{{destructor cannot have a return type}}
 };
 }
+
+namespace PR22668 {
+struct S {
+};
+void f(S s) {
+  (s.~S)();
+}
+void g(S s) {
+  (s.~S); // expected-error{{reference to destructor must be called}}
+}
+}
diff --git a/test/SemaCXX/devirtualize-vtable-marking.cpp b/test/SemaCXX/devirtualize-vtable-marking.cpp
index fc3e8ce..1b32182 100644
--- a/test/SemaCXX/devirtualize-vtable-marking.cpp
+++ b/test/SemaCXX/devirtualize-vtable-marking.cpp
@@ -1,29 +1,32 @@
 // RUN: %clang_cc1 -verify -std=c++11 %s
-
+// expected-no-diagnostics
 template <typename T> struct OwnPtr {
   T *p;
   ~OwnPtr() {
-    // expected-error@+1 {{invalid application of 'sizeof'}}
     static_assert(sizeof(T) > 0, "incomplete T");
     delete p;
   }
 };
 
 namespace use_vtable_for_vcall {
-struct Incomplete; // expected-note {{forward declaration}}
+struct Incomplete;
 struct A {
   virtual ~A() {}
   virtual void m() {}
 };
-struct B : A { // expected-note {{in instantiation}}
+struct B : A {
   B();
   virtual void m() { }
   virtual void m2() { static_cast<A *>(this)->m(); }
   OwnPtr<Incomplete> m_sqlError;
 };
 
-B *f() {
-  return new B();
+void f() {
+  // Since B's constructor is declared out of line, nothing in this file
+  // references a vtable, so the destructor doesn't get built.
+  A *b = new B();
+  b->m();
+  delete b;
 }
 }
 
diff --git a/test/SemaCXX/dllexport-pr22591.cpp b/test/SemaCXX/dllexport-pr22591.cpp
new file mode 100644
index 0000000..9d9fc84
--- /dev/null
+++ b/test/SemaCXX/dllexport-pr22591.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple i686-windows-gnu  -verify -std=c++03 %s
+// RUN: %clang_cc1 -triple i686-windows-gnu  -verify -std=c++11 %s
+// RUN: %clang_cc1 -triple i686-windows-msvc -verify -std=c++03 -DERROR %s
+// RUN: %clang_cc1 -triple i686-windows-msvc -verify -std=c++11 %s
+
+#ifndef ERROR
+// expected-no-diagnostics
+#endif
+
+struct NonCopyable {
+private:
+#ifdef ERROR
+  // expected-note@+2{{declared private here}}
+#endif
+  NonCopyable();
+};
+
+#ifdef ERROR
+// expected-error@+4{{field of type 'NonCopyable' has private default constructor}}
+// expected-note@+3{{implicit default constructor for 'S' first required here}}
+// expected-note@+2{{due to 'S' being dllexported; try compiling in C++11 mode}}
+#endif
+struct __declspec(dllexport) S {
+  NonCopyable member;
+};
diff --git a/test/SemaCXX/dllexport.cpp b/test/SemaCXX/dllexport.cpp
index 5d002ac..3bb9d22 100644
--- a/test/SemaCXX/dllexport.cpp
+++ b/test/SemaCXX/dllexport.cpp
@@ -353,10 +353,10 @@
 
 // Don't instantiate class members of templates with explicit instantiation declarations, even if they are exported.
 struct IncompleteType2;
-template <typename T> struct __declspec(dllexport) ExportedTemplateWithExplicitInstantiationDecl {
+template <typename T> struct __declspec(dllexport) ExportedTemplateWithExplicitInstantiationDecl { // expected-note{{attribute is here}}
   int f() { return sizeof(T); } // no-error
 };
-extern template struct ExportedTemplateWithExplicitInstantiationDecl<IncompleteType2>;
+extern template struct ExportedTemplateWithExplicitInstantiationDecl<IncompleteType2>; // expected-warning{{explicit instantiation declaration should not be 'dllexport'}}
 
 // Instantiate class members for explicitly instantiated exported templates.
 struct IncompleteType3; // expected-note{{forward declaration of 'IncompleteType3'}}
@@ -386,7 +386,12 @@
 };
 struct __declspec(dllexport) ExportedBaseClass2 : public ExportedBaseClassTemplateOfExportedClass<IncompleteType5> {};
 
+// Warn about explicit instantiation declarations of dllexport classes.
+template <typename T> struct ExplicitInstantiationDeclTemplate {};
+extern template struct __declspec(dllexport) ExplicitInstantiationDeclTemplate<int>; // expected-warning{{explicit instantiation declaration should not be 'dllexport'}} expected-note{{attribute is here}}
 
+template <typename T> struct __declspec(dllexport) ExplicitInstantiationDeclExportedTemplate {}; // expected-note{{attribute is here}}
+extern template struct ExplicitInstantiationDeclExportedTemplate<int>; // expected-warning{{explicit instantiation declaration should not be 'dllexport'}}
 
 //===----------------------------------------------------------------------===//
 // Classes with template base classes
diff --git a/test/SemaCXX/empty-class-layout.cpp b/test/SemaCXX/empty-class-layout.cpp
index 3cfc491..e802a0c 100644
--- a/test/SemaCXX/empty-class-layout.cpp
+++ b/test/SemaCXX/empty-class-layout.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -Wno-inaccessible-base
 // expected-no-diagnostics
 
 #define SA(n, p) int a##n[(p) ? 1 : -1]
diff --git a/test/SemaCXX/enable_if.cpp b/test/SemaCXX/enable_if.cpp
index e9dc242..99545e0 100644
--- a/test/SemaCXX/enable_if.cpp
+++ b/test/SemaCXX/enable_if.cpp
@@ -77,3 +77,44 @@
   typedep(1);
   typedep(n);  // expected-note{{in instantiation of function template specialization 'typedep<Nothing>' requested here}}
 }
+
+template <typename T> class C {
+  void f() __attribute__((enable_if(T::expr == 0, ""))) {}
+  void g() { f(); }
+};
+
+int fn3(bool b) __attribute__((enable_if(b, "")));
+template <class T> void test3() {
+  fn3(sizeof(T) == 1);
+}
+
+// FIXME: issue an error (without instantiation) because ::h(T()) is not
+// convertible to bool, because return types aren't overloadable.
+void h(int);
+template <typename T> void outer() {
+  void local_function() __attribute__((enable_if(::h(T()), "")));
+  local_function();
+};
+
+namespace PR20988 {
+  struct Integer {
+    Integer(int);
+  };
+
+  int fn1(const Integer &) __attribute__((enable_if(true, "")));
+  template <class T> void test1() {
+    int &expr = T::expr();
+    fn1(expr);
+  }
+
+  int fn2(const Integer &) __attribute__((enable_if(false, "")));  // expected-note{{candidate disabled}}
+  template <class T> void test2() {
+    int &expr = T::expr();
+    fn2(expr);  // expected-error{{no matching function for call to 'fn2'}}
+  }
+
+  int fn3(bool b) __attribute__((enable_if(b, "")));
+  template <class T> void test3() {
+    fn3(sizeof(T) == 1);
+  }
+}
diff --git a/test/SemaCXX/enum-scoped.cpp b/test/SemaCXX/enum-scoped.cpp
index 1eed228..9098023 100644
--- a/test/SemaCXX/enum-scoped.cpp
+++ b/test/SemaCXX/enum-scoped.cpp
@@ -301,3 +301,11 @@
   using E::a; // ok!
   E b = a;
 }
+
+namespace test11 {
+  enum class E { a };
+  typedef E E2;
+  E2 f1() { return E::a; }
+
+  bool f() { return !f1(); } // expected-error {{invalid argument type 'E2' (aka 'test11::E') to unary expression}}
+}
diff --git a/test/SemaCXX/exceptions-seh.cpp b/test/SemaCXX/exceptions-seh.cpp
new file mode 100644
index 0000000..7375ec9
--- /dev/null
+++ b/test/SemaCXX/exceptions-seh.cpp
@@ -0,0 +1,115 @@
+// RUN: %clang_cc1 -std=c++03 -fblocks -triple x86_64-windows-msvc -fms-extensions -fsyntax-only -fexceptions -fcxx-exceptions -verify %s
+// RUN: %clang_cc1 -std=c++11 -fblocks -triple x86_64-windows-msvc -fms-extensions -fsyntax-only -fexceptions -fcxx-exceptions -verify %s
+
+// Basic usage should work.
+int safe_div(int n, int d) {
+  int r;
+  __try {
+    r = n / d;
+  } __except(_exception_code() == 0xC0000094) {
+    r = 0;
+  }
+  return r;
+}
+
+void might_crash();
+
+// Diagnose obvious builtin mis-usage.
+void bad_builtin_scope() {
+  __try {
+    might_crash();
+  } __except(1) {
+  }
+  _exception_code(); // expected-error {{'_exception_code' only allowed in __except block or filter expression}}
+  _exception_info(); // expected-error {{'_exception_info' only allowed in __except filter expression}}
+}
+
+// Diagnose obvious builtin misusage in a template.
+template <void FN()>
+void bad_builtin_scope_template() {
+  __try {
+    FN();
+  } __except(1) {
+  }
+  _exception_code(); // expected-error {{'_exception_code' only allowed in __except block or filter expression}}
+  _exception_info(); // expected-error {{'_exception_info' only allowed in __except filter expression}}
+}
+void instantiate_bad_scope_tmpl() {
+  bad_builtin_scope_template<might_crash>();
+}
+
+#if __cplusplus < 201103L
+// FIXME: Diagnose this case. For now we produce undef in codegen.
+template <typename T, T FN()>
+T func_template() {
+  return FN();
+}
+void inject_builtins() {
+  func_template<void *, __exception_info>();
+  func_template<unsigned long, __exception_code>();
+}
+#endif
+
+void use_seh_after_cxx() {
+  try { // expected-note {{conflicting 'try' here}}
+    might_crash();
+  } catch (int) {
+  }
+  __try { // expected-error {{cannot use C++ 'try' in the same function as SEH '__try'}}
+    might_crash();
+  } __except(1) {
+  }
+}
+
+void use_cxx_after_seh() {
+  __try { // expected-note {{conflicting '__try' here}}
+    might_crash();
+  } __except(1) {
+  }
+  try { // expected-error {{cannot use C++ 'try' in the same function as SEH '__try'}}
+    might_crash();
+  } catch (int) {
+  }
+}
+
+#if __cplusplus >= 201103L
+void use_seh_in_lambda() {
+  ([]() {
+    __try {
+      might_crash();
+    } __except(1) {
+    }
+  })();
+  try {
+    might_crash();
+  } catch (int) {
+  }
+}
+#endif
+
+void use_seh_in_block() {
+  void (^b)() = ^{
+    __try { // expected-error {{cannot use SEH '__try' in blocks, captured regions, or Obj-C method decls}}
+      might_crash();
+    } __except(1) {
+    }
+  };
+  try {
+    b();
+  } catch (int) {
+  }
+}
+
+void (^use_seh_in_global_block)() = ^{
+  __try { // expected-error {{cannot use SEH '__try' in blocks, captured regions, or Obj-C method decls}}
+    might_crash();
+  } __except(1) {
+  }
+};
+
+void (^use_cxx_in_global_block)() = ^{
+  try {
+    might_crash();
+  } catch(int) {
+  }
+};
diff --git a/test/SemaCXX/explicit.cpp b/test/SemaCXX/explicit.cpp
index 155141c..a3902e5 100644
--- a/test/SemaCXX/explicit.cpp
+++ b/test/SemaCXX/explicit.cpp
@@ -56,7 +56,7 @@
   void testExplicit()
   {
     // Taken from 12.3.2p2
-    class X { X(); }; // expected-note+ {{candidate constructor}}
+    class X { X(); };
     class Y { }; // expected-note+ {{candidate constructor (the implicit}}
 
     struct Z {
@@ -89,14 +89,10 @@
     const Y& y11{z}; // expected-error {{excess elements}} expected-note {{in initialization of temporary of type 'const Y'}}
     const int& y12{z};
 
-    // X is not an aggregate, so constructors are considered.
-    // However, by 13.3.3.1/4, only standard conversion sequences and
-    // ellipsis conversion sequences are considered here, so this is not
-    // allowed.
-    // FIXME: It's not really clear that this is a sensible restriction for this
-    // case. g++ allows this, EDG does not.
-    const X x1{z}; // expected-error {{no matching constructor}}
-    const X& x2{z}; // expected-error {{no matching constructor}}
+    // X is not an aggregate, so constructors are considered,
+    // per 13.3.3.1/4 & DR1467.
+    const X x1{z};
+    const X& x2{z};
   }
   
   void testBool() {
diff --git a/test/SemaCXX/for-range-examples.cpp b/test/SemaCXX/for-range-examples.cpp
index 2f777fb..9359ae6 100644
--- a/test/SemaCXX/for-range-examples.cpp
+++ b/test/SemaCXX/for-range-examples.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11 
+// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11
 
 namespace value_range_detail {
   template<typename T>
@@ -214,17 +214,19 @@
 namespace test7 {
   void f() {
     int arr[5], b;
-    for (a : arr) {} // expected-warning {{extension}}
-    // FIXME: Give a -Wshadow for this by default?
-    for (b : arr) {} // expected-warning {{extension}}
-    for (arr : arr) {} // expected-warning {{extension}}
-    for (c alignas(8) : arr) { // expected-warning {{extension}}
+    for (a : arr) {} // expected-error {{requires type for loop variable}}
+    // FIXME: Give a different error in this case?
+    for (b : arr) {} // expected-error {{requires type for loop variable}}
+    for (arr : arr) {} // expected-error {{requires type for loop variable}}
+    for (c alignas(8) : arr) { // expected-error {{requires type for loop variable}}
       static_assert(alignof(c) == 8, ""); // expected-warning {{extension}}
     }
-    // FIXME: We should reject this, but don't, because we only check the
-    // attribute before we deduce the 'auto' type.
-    for (d alignas(1) : arr) {} // expected-warning {{extension}}
-    for (e [[deprecated]] : arr) { e = 0; } // expected-warning {{deprecated}} expected-note {{here}} expected-warning {{extension}}
+    // FIXME: The fix-it hint here is not sufficient to fix the error.
+    // We fail to diagnose that d is underaligned for its type, because
+    // we check the alignment attribute before we perform the auto
+    // deduction.
+    for (d alignas(1) : arr) {} // expected-error {{requires type for loop variable}}
+    for (e [[deprecated]] : arr) { e = 0; } // expected-warning{{use of the 'deprecated' attribute is a C++14 extension}} expected-warning {{deprecated}} expected-note {{here}} expected-error {{requires type for loop variable}}
   }
 }
 
diff --git a/test/SemaCXX/friend.cpp b/test/SemaCXX/friend.cpp
index 0358910..a8e2043 100644
--- a/test/SemaCXX/friend.cpp
+++ b/test/SemaCXX/friend.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++14
 
 friend class A; // expected-error {{'friend' used outside of class}}
 void f() { friend class A; } // expected-error {{'friend' used outside of class}}
@@ -296,3 +296,70 @@
     friend class __attribute__((visibility("hidden"), noreturn)) B; // expected-warning {{'noreturn' attribute only applies to functions and methods}}
   };
 }
+
+namespace pr21851 {
+// PR21851 was a problem where we assumed that when the friend function redecl
+// lookup found a C++ method, it would necessarily have a qualifier. Below we
+// have some test cases where unqualified lookup finds C++ methods without using
+// qualifiers. Unfortunately, we can't exercise the case of an access check
+// failure because nested classes always have access to the members of outer
+// classes.
+
+void friend_own_method() {
+  class A {
+    void m() {}
+    friend void m();
+  };
+}
+
+void friend_enclosing_method() {
+  class A;
+  class C {
+    int p;
+    friend class A;
+  };
+  class A {
+    void enclosing_friend() {
+      (void)b->p;
+      (void)c->p;
+    }
+    class B {
+      void b(A *a) {
+        (void)a->c->p;
+      }
+      int p;
+      friend void enclosing_friend();
+    };
+    B *b;
+    C *c;
+  };
+}
+
+static auto friend_file_func() {
+  extern void file_scope_friend();
+  class A {
+    int p;
+    friend void file_scope_friend();
+  };
+  return A();
+}
+
+void file_scope_friend() {
+  auto a = friend_file_func();
+  (void)a.p;
+}
+}
+
+template<typename T>
+struct X_pr6954 {
+  operator int();
+  friend void f_pr6954(int x);
+};
+
+int array0_pr6954[sizeof(X_pr6954<int>)];
+int array1_pr6954[sizeof(X_pr6954<float>)];
+
+void g_pr6954() {
+  f_pr6954(5); // expected-error{{undeclared identifier 'f_pr6954'}}
+}
+
diff --git a/test/SemaCXX/generalized-deprecated.cpp b/test/SemaCXX/generalized-deprecated.cpp
new file mode 100644
index 0000000..811610f
--- /dev/null
+++ b/test/SemaCXX/generalized-deprecated.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -std=c++11 -verify -fsyntax-only -Wno-deprecated %s
+
+// NOTE: use -Wno-deprecated to avoid cluttering the output with deprecated
+// warnings
+
+[[deprecated("1")]] int function_1();
+// expected-warning@-1 {{use of the 'deprecated' attribute is a C++14 extension}}
+
+[[gnu::deprecated("3")]] int function_3();
+
+int __attribute__ (( deprecated("2") )) function_2();
+
+__declspec(deprecated("4")) int function_4();
+
diff --git a/test/SemaCXX/integer-overflow.cpp b/test/SemaCXX/integer-overflow.cpp
new file mode 100644
index 0000000..566bb05
--- /dev/null
+++ b/test/SemaCXX/integer-overflow.cpp
@@ -0,0 +1,166 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only -std=gnu++98
+typedef unsigned long long uint64_t;
+typedef unsigned long long uint32_t;
+
+uint64_t f0(uint64_t);
+uint64_t f1(uint64_t, uint32_t);
+uint64_t f2(uint64_t, ...);
+
+static const uint64_t overflow = 1 * 4608 * 1024 * 1024; // expected-warning {{overflow in expression; result is 536870912 with type 'int'}}
+
+uint64_t check_integer_overflows(int i) { //expected-note {{declared here}}
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t overflow = 4608 * 1024 * 1024,
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow2 = (uint64_t)(4608 * 1024 * 1024),
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow3 = (uint64_t)(4608 * 1024 * 1024 * i),
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow4 =  (1ULL * ((4608) * ((1024) * (1024))) + 2ULL),
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+           overflow5 = static_cast<uint64_t>(4608 * 1024 * 1024),
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+           multi_overflow = (uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow += overflow2 = overflow3 = (uint64_t)(4608 * 1024 * 1024);
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow += overflow2 = overflow3 = 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow += overflow2 = overflow3 = static_cast<uint64_t>(4608 * 1024 * 1024);
+
+  uint64_t not_overflow = 4608 * 1024 * 1024ULL;
+  uint64_t not_overflow2 = (1ULL * ((uint64_t)(4608) * (1024 * 1024)) + 2ULL);
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  overflow = 4608 * 1024 * 1024 ?  4608 * 1024 * 1024 : 0;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  overflow =  0 ? 0 : 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if (4608 * 1024 * 1024)
+    return 0;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)(4608 * 1024 * 1024))
+    return 1;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if (static_cast<uint64_t>(4608 * 1024 * 1024))
+    return 1;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)(4608 * 1024 * 1024))
+    return 2;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)(4608 * 1024 * 1024 * i))
+    return 3;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  if ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL))
+    return 4;
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  if ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)))
+    return 5;
+
+  switch (i) {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  case 4608 * 1024 * 1024:
+    return 6;
+// expected-warning@+1 {{overflow in expression; result is 537919488 with type 'int'}}
+  case (uint64_t)(4609 * 1024 * 1024):
+    return 7;
+// expected-warning@+1 {{overflow in expression; result is 537919488 with type 'int'}}
+  case 1 + static_cast<uint64_t>(4609 * 1024 * 1024):
+    return 7;
+// expected-error@+2 {{expression is not an integral constant expression}}
+// expected-note@+1 {{read of non-const variable 'i' is not allowed in a constant expression}}
+  case ((uint64_t)(4608 * 1024 * 1024 * i)):
+    return 8;
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  case ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL)):
+    return 9;
+// expected-warning@+2 2{{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+1 {{overflow converting case value to switch condition type (288230376151711744 to 0)}}
+  case ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024))):
+    return 10;
+  }
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while (4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while (static_cast<uint64_t>(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)(4608 * 1024 * 1024 * i));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  while ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL));
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  while ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while (4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while (static_cast<uint64_t>(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)(4608 * 1024 * 1024));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)(4608 * 1024 * 1024 * i));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((1ULL * ((4608) * ((1024) * (1024))) + 2ULL));
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  do { } while ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)));
+
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+  for (uint64_t i = 4608 * 1024 * 1024;
+       (uint64_t)(4608 * 1024 * 1024);
+       i += (uint64_t)(4608 * 1024 * 1024 * i));
+
+// expected-warning@+3 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 2{{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 2{{overflow in expression; result is 536870912 with type 'int'}}
+  for (uint64_t i = (1ULL * ((4608) * ((1024) * (1024))) + 2ULL);
+       ((uint64_t)((uint64_t)(4608 * 1024 * 1024) * (uint64_t)(4608 * 1024 * 1024)));
+       i = ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024))));
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  _Complex long long x = 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (__real__ x) = 4608 * 1024 * 1024;
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (__imag__ x) = 4608 * 1024 * 1024;
+
+// expected-warning@+4 {{overflow in expression; result is 536870912 with type 'int'}}
+// expected-warning@+3 {{array index 536870912 is past the end of the array (which contains 10 elements)}}
+// expected-note@+1 {{array 'a' declared here}}
+  uint64_t a[10];
+  a[4608 * 1024 * 1024] = 1i;
+
+// expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
+  return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
+}
diff --git a/test/SemaCXX/lambda-expressions.cpp b/test/SemaCXX/lambda-expressions.cpp
index 1346c3d..7911c1b 100644
--- a/test/SemaCXX/lambda-expressions.cpp
+++ b/test/SemaCXX/lambda-expressions.cpp
@@ -258,9 +258,7 @@
   void f() {
     const S s {};
     S &&t = [&] { return s; } ();
-#if __cplusplus <= 201103L
-    // expected-error@-2 {{drops qualifiers}}
-#else
+#if __cplusplus > 201103L
     S &&u = [&] () -> auto { return s; } ();
 #endif
   }
@@ -425,3 +423,26 @@
   }
   template void g<int>();
 }
+
+namespace error_in_transform_prototype {
+  template<class T>
+  void f(T t) {
+    // expected-error@+2 {{type 'int' cannot be used prior to '::' because it has no members}}
+    // expected-error@+1 {{no member named 'ns' in 'error_in_transform_prototype::S'}}
+    auto x = [](typename T::ns::type &k) {};
+  }
+  class S {};
+  void foo() {
+    f(5); // expected-note {{requested here}}
+    f(S()); // expected-note {{requested here}}
+  }
+}
+
+namespace PR21857 {
+  template<typename Fn> struct fun : Fn {
+    fun() = default;
+    using Fn::operator();
+  };
+  template<typename Fn> fun<Fn> wrap(Fn fn);
+  auto x = wrap([](){});
+}
diff --git a/test/SemaCXX/libstdcxx_is_pod_hack.cpp b/test/SemaCXX/libstdcxx_is_pod_hack.cpp
index 1ba3721..8d18712 100644
--- a/test/SemaCXX/libstdcxx_is_pod_hack.cpp
+++ b/test/SemaCXX/libstdcxx_is_pod_hack.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only %s
+// RUN: %clang_cc1 -fsyntax-only -verify %s
 
 // This is a test for an egregious hack in Clang that works around
 // issues with GCC's evolution. libstdc++ 4.2.x uses __is_pod as an
@@ -7,7 +7,7 @@
 // a keyword *unless* it is introduced following the struct keyword.
 
 template<typename T>
-struct __is_pod {
+struct __is_pod { // expected-warning {{keyword '__is_pod' will be made available as an identifier}}
   __is_pod() {}
 };
 
@@ -15,7 +15,7 @@
 
 // Ditto for __is_same.
 template<typename T>
-struct __is_same {
+struct __is_same { // expected-warning {{keyword '__is_same' will be made available as an identifier}}
 };
 
 __is_same<int> isi;
@@ -24,7 +24,7 @@
 // trait in Embarcadero's compiler but is used as an identifier in
 // libstdc++.
 struct test_is_signed {
-  static const bool __is_signed = true;
+  static const bool __is_signed = true; // expected-warning {{keyword '__is_signed' will be made available as an identifier}}
 };
 
 bool check_signed = test_is_signed::__is_signed;
@@ -36,6 +36,13 @@
   bool b = __is_pod(int);
   must_be_true<__is_pod(int)> mbt;
 }
+
+// expected-warning@+1 {{declaration does not declare anything}}
+struct // expected-error {{declaration of anonymous struct must be a definition}}
+#pragma pack(pop)
+    S {
+};
+
 #if !__has_feature(is_pod)
 #  error __is_pod should still be available.
 #endif
diff --git a/test/SemaCXX/linkage.cpp b/test/SemaCXX/linkage.cpp
index 8a2013f..79c7835 100644
--- a/test/SemaCXX/linkage.cpp
+++ b/test/SemaCXX/linkage.cpp
@@ -94,8 +94,8 @@
   }
 }
 
-// CHECK: define linkonce_odr i8* @_ZN5test21A1BILj0EE3fooEv(
 // CHECK: define linkonce_odr i8* @_ZN5test11A3fooILj0EEEPvv(
+// CHECK: define linkonce_odr i8* @_ZN5test21A1BILj0EE3fooEv(
 
 namespace test5 {
   struct foo {
diff --git a/test/SemaCXX/member-init.cpp b/test/SemaCXX/member-init.cpp
index 5acb480..b3ee30b 100644
--- a/test/SemaCXX/member-init.cpp
+++ b/test/SemaCXX/member-init.cpp
@@ -185,3 +185,10 @@
 }
 void g() { f<int>(); } // expected-note {{in instantiation of function template specialization 'local_class::f<int>' requested here}}
 }
+
+namespace PR22056 {
+template <int N>
+struct S {
+  int x[3] = {[N] = 3};
+};
+}
diff --git a/test/SemaCXX/member-pointer.cpp b/test/SemaCXX/member-pointer.cpp
index b8631bc..afb7455 100644
--- a/test/SemaCXX/member-pointer.cpp
+++ b/test/SemaCXX/member-pointer.cpp
@@ -12,8 +12,10 @@
 int A::*pdi1;
 int (::A::*pdi2);
 int (A::*pfi)(int);
+void (*A::*ppfie)() throw(); // expected-error {{exception specifications are not allowed beyond a single level of indirection}}
 
-int B::*pbi; // expected-error {{'B' is not a class, namespace, or scoped enumeration}}
+int B::*pbi; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}} \
+             // expected-error {{'pbi' does not point into a class}}
 int C::*pci; // expected-error {{'pci' does not point into a class}}
 void A::*pdv; // expected-error {{'pdv' declared as a member pointer to void}}
 int& A::*pdr; // expected-error {{'pdr' declared as a member pointer to a reference}}
diff --git a/test/SemaCXX/microsoft-dtor-lookup.cpp b/test/SemaCXX/microsoft-dtor-lookup.cpp
index 412749f..312598e 100644
--- a/test/SemaCXX/microsoft-dtor-lookup.cpp
+++ b/test/SemaCXX/microsoft-dtor-lookup.cpp
@@ -23,8 +23,9 @@
   virtual ~VC(); // expected-error {{member 'operator delete' found in multiple base classes of different types}}
 };
 
-void f(VC vc) {
+void f() {
   // This marks VC's vtable used.
+  VC vc;
 }
 
 }
diff --git a/test/SemaCXX/microsoft-new-delete.cpp b/test/SemaCXX/microsoft-new-delete.cpp
index 6c9be22..b929e61 100644
--- a/test/SemaCXX/microsoft-new-delete.cpp
+++ b/test/SemaCXX/microsoft-new-delete.cpp
@@ -31,4 +31,4 @@
 void *operator new[](size_t, explicit_ctor_tag, explicit_ctor);
 void *operator new(size_t, explicit_ctor_tag, int);
 void *t = new (ect, 0) int[4];
-void *u = new (ect, {0}) int[4];
+void *u = new (ect, {0}) int[4]; // expected-warning {{braces around scalar init}}
diff --git a/test/SemaCXX/ms-novtable.cpp b/test/SemaCXX/ms-novtable.cpp
new file mode 100644
index 0000000..2d55c48
--- /dev/null
+++ b/test/SemaCXX/ms-novtable.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify -fms-extensions -Wno-microsoft -std=c++11
+
+struct __declspec(novtable) S {};
+enum __declspec(novtable) E {}; // expected-warning{{'novtable' attribute only applies to classes}}
+int __declspec(novtable) I; // expected-warning{{'novtable' attribute only applies to classes}}
+typedef struct T __declspec(novtable) U; // expected-warning{{'novtable' attribute only applies to classes}}
+auto z = []() __declspec(novtable) { return nullptr; }; // expected-warning{{'novtable' attribute only applies to classes}}
diff --git a/test/SemaCXX/ms_mutable_reference_member.cpp b/test/SemaCXX/ms_mutable_reference_member.cpp
new file mode 100644
index 0000000..ae1389d
--- /dev/null
+++ b/test/SemaCXX/ms_mutable_reference_member.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify -fms-compatibility
+
+struct S {
+  mutable int &a; // expected-warning {{'mutable' on a reference type is a Microsoft extension}}
+  S(int &b) : a(b) {}
+};
+
+int main() {
+  int a = 0;
+  const S s(a);
+  s.a = 10;
+  return s.a + a;
+}
diff --git a/test/SemaCXX/nested-name-spec.cpp b/test/SemaCXX/nested-name-spec.cpp
index bdeb00d..0fbdedc 100644
--- a/test/SemaCXX/nested-name-spec.cpp
+++ b/test/SemaCXX/nested-name-spec.cpp
@@ -13,7 +13,7 @@
 }
 
 A:: ; // expected-error {{expected unqualified-id}}
-::A::ax::undef ex3; // expected-error {{'ax' is not a class, namespace, or scoped enumeration}}
+::A::ax::undef ex3; // expected-error {{'ax' is not a class, namespace, or enumeration}}
 A::undef1::undef2 ex4; // expected-error {{no member named 'undef1'}}
 
 int A::C::Ag1() { return 0; }
@@ -88,9 +88,9 @@
   // declared here", "template 'X' declared here", etc) to help explain what it
   // is if it's 'not a class, namespace, or scoped enumeration'.
   int N; // expected-note {{'N' declared here}}
-  N::x = 0; // expected-error {{'N' is not a class, namespace, or scoped enumeration}}
+  N::x = 0; // expected-error {{'N' is not a class, namespace, or enumeration}}
   { int A;           A::ax = 0; }
-  { typedef int A;   A::ax = 0; } // expected-error{{'A' (aka 'int') is not a class, namespace, or scoped enumeration}}
+  { typedef int A;   A::ax = 0; } // expected-error{{'A' (aka 'int') is not a class, namespace, or enumeration}}
   { typedef A::C A;  A::ax = 0; } // expected-error {{no member named 'ax'}}
   { typedef A::C A;  A::cx = 0; }
 }
@@ -115,8 +115,8 @@
       X = 0
     };
 
-    void f() {
-      return E::X; // expected-error{{'E::Nested::E' is not a class, namespace, or scoped enumeration}}
+    int f() {
+      return E::X; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}}
     }
   }
 }
@@ -310,7 +310,7 @@
 }
 
 namespace TypedefNamespace { typedef int F; };
-TypedefNamespace::F::NonexistentName BadNNSWithCXXScopeSpec; // expected-error {{'F' (aka 'int') is not a class, namespace, or scoped enumeration}}
+TypedefNamespace::F::NonexistentName BadNNSWithCXXScopeSpec; // expected-error {{'F' (aka 'int') is not a class, namespace, or enumeration}}
 
 namespace PR18587 {
 
@@ -410,3 +410,28 @@
 };
 
 }
+
+namespace PR16951 {
+  namespace ns {
+    enum an_enumeration {
+      ENUMERATOR  // expected-note{{'ENUMERATOR' declared here}}
+    };
+  }
+
+  int x1 = ns::an_enumeration::ENUMERATOR; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}}
+
+  int x2 = ns::an_enumeration::ENUMERATOR::vvv; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}} \
+                                                // expected-error{{'ENUMERATOR' is not a class, namespace, or enumeration}} \
+
+  int x3 = ns::an_enumeration::X; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}} \
+                                  // expected-error{{no member named 'X'}}
+
+  enum enumerator_2 {
+    ENUMERATOR_2
+  };
+
+  int x4 = enumerator_2::ENUMERATOR_2; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}}
+  int x5 = enumerator_2::X2; // expected-warning{{use of enumeration in a nested name specifier is a C++11 extension}} \
+                             // expected-error{{no member named 'X2' in 'PR16951::enumerator_2'}}
+
+}
diff --git a/test/SemaCXX/new-array-size-conv.cpp b/test/SemaCXX/new-array-size-conv.cpp
index e8bb679..c987c28 100644
--- a/test/SemaCXX/new-array-size-conv.cpp
+++ b/test/SemaCXX/new-array-size-conv.cpp
@@ -16,7 +16,8 @@
 struct ValueBoth : ValueInt, ValueEnum { };
 
 struct IndirectValueInt : ValueInt { };
-struct TwoValueInts : ValueInt, IndirectValueInt { };
+struct TwoValueInts : ValueInt, IndirectValueInt { }; // expected-warning{{direct base 'ValueInt' is inaccessible due to ambiguity:\n    struct TwoValueInts -> struct ValueInt\n    struct TwoValueInts -> struct IndirectValueInt -> struct ValueInt}}
+
 
 void test() {
   (void)new int[ValueInt(10)]; // expected-warning{{implicit conversion from array size expression of type 'ValueInt' to integral type 'int' is a C++11 extension}}
diff --git a/test/SemaCXX/new-delete.cpp b/test/SemaCXX/new-delete.cpp
index cb43458..7bc724b 100644
--- a/test/SemaCXX/new-delete.cpp
+++ b/test/SemaCXX/new-delete.cpp
@@ -524,3 +524,11 @@
 
 // PR19968
 inline void* operator new(); // expected-error {{'operator new' must have at least one parameter}}
+
+namespace {
+template <class C>
+struct A {
+  void f() { this->::new; } // expected-error {{expected unqualified-id}}
+  void g() { this->::delete; } // expected-error {{expected unqualified-id}}
+};
+}
diff --git a/test/SemaCXX/overload-decl.cpp b/test/SemaCXX/overload-decl.cpp
index fdb14cb..1201396 100644
--- a/test/SemaCXX/overload-decl.cpp
+++ b/test/SemaCXX/overload-decl.cpp
@@ -30,10 +30,8 @@
   static void g(int); // expected-error {{static and non-static member functions with the same parameter types cannot be overloaded}}
   static void g(float); // expected-error {{class member cannot be redeclared}}
 
-  void h(); // expected-note {{previous declaration is here}} \
-               expected-note {{previous declaration is here}}
-  void h() __restrict; // expected-error {{class member cannot be redeclared}} \
-                          expected-error {{conflicting types for 'h'}}
+  void h(); // expected-note {{previous declaration is here}}
+  void h() __restrict; // expected-error {{class member cannot be redeclared}}
 };
 
 int main() {} // expected-note {{previous definition is here}}
diff --git a/test/SemaCXX/pragma-optimize.cpp b/test/SemaCXX/pragma-optimize.cpp
index 0a9f041..48a1546 100644
--- a/test/SemaCXX/pragma-optimize.cpp
+++ b/test/SemaCXX/pragma-optimize.cpp
@@ -1,4 +1,6 @@
 // RUN: %clang_cc1 -I %S/Inputs -x c++ -std=c++11 -triple x86_64-unknown-linux -emit-llvm -O2 < %s | FileCheck %s
+// RUN: %clang_cc1 -I %S/Inputs -x c++ -std=c++11 -triple x86_64-unknown-linux -emit-llvm -Os < %s | FileCheck %s
+// RUN: %clang_cc1 -I %S/Inputs -x c++ -std=c++11 -triple x86_64-unknown-linux -emit-llvm -Oz < %s | FileCheck %s
 
 #pragma clang optimize off
 
@@ -55,6 +57,13 @@
 }
 // CHECK-DAG: @_Z3bazi{{.*}} [[ATTRBAZ:#[0-9]+]]
 
+// This function definition will not be decorated with `optnone` because the
+// attribute would conflict with `minsize`.
+int __attribute__((minsize)) bax(int z) {
+    return foo(z, 2);
+}
+// CHECK-DAG: @_Z3baxi{{.*}} [[ATTRBAX:#[0-9]+]]
+
 #pragma clang optimize on
 
 // The function "int wombat(int param)" created by the macro is not
@@ -144,6 +153,7 @@
 // Check that the other functions do NOT have optnone.
 // CHECK-DAG-NOT: attributes [[ATTRFOO]] = { {{.*}}optnone{{.*}} }
 // CHECK-DAG-NOT: attributes [[ATTRBAZ]] = { {{.*}}optnone{{.*}} }
+// CHECK-DAG-NOT: attributes [[ATTRBAX]] = { {{.*}}optnone{{.*}} }
 // CHECK-DAG-NOT: attributes [[ATTRWOMBAT]] = { {{.*}}optnone{{.*}} }
 // CHECK-DAG-NOT: attributes [[ATTRCONTAINER]] = { {{.*}}optnone{{.*}} }
 // CHECK-DAG-NOT: attributes [[ATTRTWICE]] = { {{.*}}optnone{{.*}} }
diff --git a/test/SemaCXX/pseudo-destructors.cpp b/test/SemaCXX/pseudo-destructors.cpp
index 95363e5..3971881 100644
--- a/test/SemaCXX/pseudo-destructors.cpp
+++ b/test/SemaCXX/pseudo-destructors.cpp
@@ -59,7 +59,11 @@
 typedef int Integer;
 
 void destroy_without_call(int *ip) {
-  ip->~Integer; // expected-error{{called immediately}}
+  ip->~Integer; // expected-error{{reference to pseudo-destructor must be called}}
+}
+
+void paren_destroy_with_call(int *ip) {
+  (ip->~Integer)();
 }
 
 // PR5530
diff --git a/test/SemaCXX/references.cpp b/test/SemaCXX/references.cpp
index cfe7dc1..b1768b1 100644
--- a/test/SemaCXX/references.cpp
+++ b/test/SemaCXX/references.cpp
@@ -70,7 +70,7 @@
   int& okay; // expected-note{{reference member 'okay' will never be initialized}}
 };
 
-struct C : B, A { };
+struct C : B, A { }; // expected-warning {{direct base 'A' is inaccessible due to ambiguity:\n    struct C -> struct B -> struct A\nstruct C -> struct A}}
 
 void test7(C& c) {
   A& a1 = c; // expected-error {{ambiguous conversion from derived class 'C' to base class 'A':}}
diff --git a/test/SemaCXX/return-noreturn.cpp b/test/SemaCXX/return-noreturn.cpp
index 61b45c5..cdd96e6 100644
--- a/test/SemaCXX/return-noreturn.cpp
+++ b/test/SemaCXX/return-noreturn.cpp
@@ -143,7 +143,7 @@
 } // expected-warning {{control reaches end of non-void function}}
 
 void PR9412_f() {
-    PR9412_t<PR9412_Exact>(); // expected-note {{in instantiation of function template specialization 'PR9412_t<0>' requested here}}
+    PR9412_t<PR9412_Exact>(); // expected-note {{in instantiation of function template specialization 'PR9412_t<PR9412_MatchType::PR9412_Exact>' requested here}}
 }
 
 struct NoReturn {
diff --git a/test/SemaCXX/return.cpp b/test/SemaCXX/return.cpp
index 98dbd51..8c16645 100644
--- a/test/SemaCXX/return.cpp
+++ b/test/SemaCXX/return.cpp
@@ -112,3 +112,11 @@
     ~S() { return f(); } // expected-error {{destructor '~S' must not return void expression}}
   };
 }
+
+void cxx_unresolved_expr() {
+  // The use of an undeclared variable tricks clang into building a
+  // CXXUnresolvedConstructExpr, and the missing ')' gives it an invalid source
+  // location for its rparen.  Check that emitting a diag on the range of the
+  // expr doesn't assert.
+  return int(undeclared, 4; // expected-error {{expected ')'}} expected-note{{to match this '('}} expected-error {{void function 'cxx_unresolved_expr' should not return a value}} expected-error {{use of undeclared identifier 'undeclared'}}
+}
diff --git a/test/SemaCXX/runtimediag-ppe.cpp b/test/SemaCXX/runtimediag-ppe.cpp
index 0e8451b..2788963 100644
--- a/test/SemaCXX/runtimediag-ppe.cpp
+++ b/test/SemaCXX/runtimediag-ppe.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-unused-value %s
 
 // Make sure diagnostics that we don't print based on runtime control
 // flow are delayed correctly in cases where we can't immediately tell whether
diff --git a/test/SemaCXX/scope-check.cpp b/test/SemaCXX/scope-check.cpp
index ac70099..c7638ae 100644
--- a/test/SemaCXX/scope-check.cpp
+++ b/test/SemaCXX/scope-check.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -fcxx-exceptions %s -Wno-unreachable-code
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -fcxx-exceptions -std=gnu++11 %s -Wno-unreachable-code
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -fcxx-exceptions -fms-extensions %s -Wno-unreachable-code
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -fcxx-exceptions -fms-extensions -std=gnu++11 %s -Wno-unreachable-code
 
 namespace testInvalid {
 Invalid inv; // expected-error {{unknown type name}}
@@ -441,3 +441,192 @@
     }
   }
 }
+
+namespace seh {
+
+// Jumping into SEH try blocks is not permitted.
+
+void jump_into_except() {
+  goto into_try_except_try; // expected-error {{cannot jump from this goto statement to its label}}
+  __try { // expected-note {{jump bypasses initialization of __try block}}
+  into_try_except_try:
+    ;
+  } __except(0) {
+  }
+
+  goto into_try_except_except; // expected-error {{cannot jump from this goto statement to its label}}
+  __try {
+  } __except(0) { // expected-note {{jump bypasses initialization of __except block}}
+  into_try_except_except:
+    ;
+  }
+}
+
+void jump_into_finally() {
+  goto into_try_except_try; // expected-error {{cannot jump from this goto statement to its label}}
+  __try { // expected-note {{jump bypasses initialization of __try block}}
+  into_try_except_try:
+    ;
+  } __finally {
+  }
+
+  goto into_try_except_finally; // expected-error {{cannot jump from this goto statement to its label}}
+  __try {
+  } __finally { // expected-note {{jump bypasses initialization of __finally block}}
+  into_try_except_finally:
+    ;
+  }
+}
+
+// Jumping out of SEH try blocks ok in general. (Jumping out of a __finally
+// has undefined behavior.)
+
+void jump_out_of_except() {
+  __try {
+    goto out_of_except_try;
+  } __except(0) {
+  }
+out_of_except_try:
+  ;
+
+  __try {
+  } __except(0) {
+    goto out_of_except_except;
+  }
+out_of_except_except:
+  ;
+}
+
+void jump_out_of_finally() {
+  __try {
+  goto out_of_finally_try;
+  } __finally {
+  }
+out_of_finally_try:
+  ;
+
+  __try {
+  } __finally {
+    // FIXME: This should warn that jumping out of __finally has undefined
+    // behavior.
+    // FIXME: Once that warns, check that
+    //   __try { __try {} __finally { __leave; } } __except (0) {}
+    // warns in the same way.
+    goto out_of_finally_finally;
+  }
+out_of_finally_finally:
+  ;
+}
+
+// Jumping between protected scope and handler is not permitted.
+
+void jump_try_except() {
+  __try {
+    goto from_try_to_except; // expected-error {{cannot jump from this goto statement to its label}}
+  } __except(0) { // expected-note {{jump bypasses initialization of __except block}}
+  from_try_to_except:
+    ;
+  }
+
+  __try { // expected-note {{jump bypasses initialization of __try block}}
+  from_except_to_try:
+    ;
+  } __except(0) {
+    goto from_except_to_try; // expected-error {{cannot jump from this goto statement to its label}}
+  }
+}
+
+void jump_try_finally() {
+  __try {
+    goto from_try_to_finally; // expected-error {{cannot jump from this goto statement to its label}}
+  } __finally { // expected-note {{jump bypasses initialization of __finally block}}
+  from_try_to_finally:
+    ;
+  }
+
+  __try { // expected-note {{jump bypasses initialization of __try block}}
+  from_finally_to_try:
+    ;
+  } __finally {
+    goto from_finally_to_try; // expected-error {{cannot jump from this goto statement to its label}}
+  }
+}
+
+void nested() {
+  // These are not permitted.
+  __try {
+    __try {
+    } __finally {
+      goto outer_except; // expected-error {{cannot jump from this goto statement to its label}}
+    }
+  } __except(0) { // expected-note {{jump bypasses initialization of __except bloc}}
+  outer_except:
+    ;
+  }
+
+  __try {
+    __try{
+    } __except(0) {
+      goto outer_finally; // expected-error {{cannot jump from this goto statement to its label}}
+    }
+  } __finally { // expected-note {{jump bypasses initialization of __finally bloc}}
+  outer_finally:
+    ;
+  }
+
+  // These are permitted.
+  __try {
+    __try {
+    } __finally {
+      // FIXME: This should warn that jumping out of __finally has undefined
+      // behavior.
+      goto after_outer_except;
+    }
+  } __except(0) {
+  }
+after_outer_except:
+  ;
+
+  __try {
+    __try{
+    } __except(0) {
+      goto after_outer_finally;
+    }
+  } __finally {
+  }
+after_outer_finally:
+  ;
+}
+
+// This section is academic, as MSVC doesn't support indirect gotos.
+
+void indirect_jumps(void **ip) {
+  static void *ips[] = { &&l };
+
+  __try { // expected-note {{jump exits __try block}}
+    // FIXME: Should this be allowed? Jumping out of the guarded section of a
+    // __try/__except doesn't require unwinding.
+    goto *ip; // expected-error {{cannot jump from this indirect goto statement to one of its possible targets}}
+  } __except(0) {
+  }
+
+  __try {
+  } __except(0) { // expected-note {{jump exits __except block}}
+    // FIXME: What about here?
+    goto *ip; // expected-error {{cannot jump from this indirect goto statement to one of its possible targets}}
+  }
+
+  __try { // expected-note {{jump exits __try block}}
+    goto *ip; // expected-error {{cannot jump from this indirect goto statement to one of its possible targets}}
+  } __finally {
+  }
+
+  __try {
+  } __finally { // expected-note {{jump exits __finally block}}
+    goto *ip; // expected-error {{cannot jump from this indirect goto statement to one of its possible targets}}
+  }
+l: // expected-note 4 {{possible target of indirect goto statement}}
+  ;
+}
+
+} // namespace seh
diff --git a/test/SemaCXX/statements.cpp b/test/SemaCXX/statements.cpp
index 953a4a8..15b0b50 100644
--- a/test/SemaCXX/statements.cpp
+++ b/test/SemaCXX/statements.cpp
@@ -20,3 +20,20 @@
   struct A {};
   void a() { goto out; A x; out: return; }
 }
+
+void test3() {
+    __asm__ ("":"+r" (test3)); // expected-error{{invalid lvalue in asm output}}
+}
+
+void test4();                // expected-note{{possible target for call}}
+void test4(int) {            // expected-note{{possible target for call}}
+  // expected-error@+1{{overloaded function could not be resolved}}
+  __asm__ ("":"+r" (test4)); // expected-error{{invalid lvalue in asm output}}
+}
+void test5() {
+  char buf[1];
+  __asm__ ("":"+r" (buf));
+}
+
+struct MMX_t {};
+void test6() { __asm__("" : "=m"(*(MMX_t *)0)); }
diff --git a/test/SemaCXX/static-cast.cpp b/test/SemaCXX/static-cast.cpp
index 06fd863..b3fe49a 100644
--- a/test/SemaCXX/static-cast.cpp
+++ b/test/SemaCXX/static-cast.cpp
@@ -9,8 +9,8 @@
 struct G1 : public B {};
 struct G2 : public B {};
 struct H : public G1, public G2 {}; // Ambiguous path to B.
-struct I;                           // Incomplete.
-struct J;                           // Incomplete.
+struct I;                           // Incomplete.  expected-note {{'I' is incomplete}}
+struct J;                           // Incomplete.  expected-note {{'J' is incomplete}}
 
 enum Enum { En1, En2 };
 enum Onom { On1, On2 };
@@ -92,9 +92,13 @@
   (void)static_cast<E&>(*((A*)0)); // expected-error {{cannot cast private base class 'A' to 'E'}}
   (void)static_cast<H*>((A*)0); // expected-error {{ambiguous cast from base 'A' to derived 'H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
   (void)static_cast<H&>(*((A*)0)); // expected-error {{ambiguous cast from base 'A' to derived 'H':\n    struct A -> struct B -> struct G1 -> struct H\n    struct A -> struct B -> struct G2 -> struct H}}
-  (void)static_cast<E*>((B*)0); // expected-error {{static_cast from 'B *' to 'E *' is not allowed}}
+  (void)static_cast<E*>((B*)0); // expected-error {{static_cast from 'B *' to 'E *', which are not related by inheritance, is not allowed}}
   (void)static_cast<E&>(*((B*)0)); // expected-error {{non-const lvalue reference to type 'E' cannot bind to a value of unrelated type 'B'}}
 
+
+  (void)static_cast<E*>((J*)0); // expected-error {{static_cast from 'J *' to 'E *', which are not related by inheritance, is not allowed}}
+  (void)static_cast<I*>((B*)0); // expected-error {{static_cast from 'B *' to 'I *', which are not related by inheritance, is not allowed}}
+
   // TODO: Test inaccessible base in context where it's accessible, i.e.
   // member function and friend.
 
diff --git a/test/SemaCXX/string-plus-int.cpp b/test/SemaCXX/string-plus-int.cpp
index 5752f8f..fe9c719 100644
--- a/test/SemaCXX/string-plus-int.cpp
+++ b/test/SemaCXX/string-plus-int.cpp
@@ -64,3 +64,8 @@
   consume(A B + sizeof(A) - 1);
 }
 
+template <typename T>
+void PR21848() {
+  (void)(sizeof(T) + ""); // expected-warning {{to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
+}
+template void PR21848<int>(); // expected-note {{in instantiation of function template specialization 'PR21848<int>' requested here}}
diff --git a/test/SemaCXX/struct-class-redecl.cpp b/test/SemaCXX/struct-class-redecl.cpp
index e1b95ba..706ec56 100644
--- a/test/SemaCXX/struct-class-redecl.cpp
+++ b/test/SemaCXX/struct-class-redecl.cpp
@@ -7,6 +7,12 @@
 template<typename T> struct Y; // expected-note{{did you mean class here?}}
 template<class U> class Y { }; // expected-warning{{previously declared}}
 
+template <typename>
+struct Z {   // expected-note{{previous definition is here}}
+  struct Z { // expected-error{{nested redefinition of 'Z'}}
+  };
+};
+
 class A;
 class A;  // expected-note{{previous use is here}}
 struct A;  // expected-warning{{struct 'A' was previously declared as a class}}
diff --git a/test/SemaCXX/type-traits.cpp b/test/SemaCXX/type-traits.cpp
index 4833c14..2265c28 100644
--- a/test/SemaCXX/type-traits.cpp
+++ b/test/SemaCXX/type-traits.cpp
@@ -1857,6 +1857,9 @@
   { int arr[T(__is_trivially_copyable(HasNonPOD))]; }
   { int arr[T(__is_trivially_copyable(DerivesHasCons))]; }
   { int arr[T(__is_trivially_copyable(DerivesHasRef))]; }
+  { int arr[T(__is_trivially_copyable(NonTrivialDefault))]; }
+  { int arr[T(__is_trivially_copyable(NonTrivialDefault[]))]; }
+  { int arr[T(__is_trivially_copyable(NonTrivialDefault[3]))]; }
 
   { int arr[F(__is_trivially_copyable(HasCopyAssign))]; }
   { int arr[F(__is_trivially_copyable(HasMoveAssign))]; }
diff --git a/test/SemaCXX/typeid.cpp b/test/SemaCXX/typeid.cpp
index d3a2a28..48fcce0 100644
--- a/test/SemaCXX/typeid.cpp
+++ b/test/SemaCXX/typeid.cpp
@@ -21,3 +21,9 @@
   (void)typeid(X&); // expected-error{{'typeid' of incomplete type 'X'}}
   (void)typeid(x); // expected-error{{'typeid' of incomplete type 'X'}}
 }
+
+void h(int i) {
+  char V[i];
+  typeid(V);        // expected-error{{'typeid' of variably modified type 'char [i]'}}
+  typeid(char [i]); // expected-error{{'typeid' of variably modified type 'char [i]'}}
+}
diff --git a/test/SemaCXX/typo-correction-delayed.cpp b/test/SemaCXX/typo-correction-delayed.cpp
index 984d68b..64e6dd5 100644
--- a/test/SemaCXX/typo-correction-delayed.cpp
+++ b/test/SemaCXX/typo-correction-delayed.cpp
@@ -48,3 +48,148 @@
   callee(xxxxxx,   // expected-error-re {{use of undeclared identifier 'xxxxxx'{{$}}}}
          zzzzzz);  // expected-error-re {{use of undeclared identifier 'zzzzzz'{{$}}}}
 }
+
+class string {};
+struct Item {
+  void Nest();
+  string text();
+  Item* next();  // expected-note {{'next' declared here}}
+};
+void testExprFilter(Item *i) {
+  Item *j;
+  j = i->Next();  // expected-error {{no member named 'Next' in 'Item'; did you mean 'next'?}}
+}
+
+// Test that initializer expressions are handled correctly and that the type
+// being initialized is taken into account when choosing a correction.
+namespace initializerCorrections {
+struct Node {
+  string text() const;
+  // Node* Next() is not implemented yet
+};
+void f(Node *node) {
+  // text is only an edit distance of 1 from Next, but would trigger type
+  // conversion errors if used in this initialization expression.
+  Node *next = node->Next();  // expected-error-re {{no member named 'Next' in 'initializerCorrections::Node'{{$}}}}
+}
+
+struct LinkedNode {
+  LinkedNode* next();  // expected-note {{'next' declared here}}
+  string text() const;
+};
+void f(LinkedNode *node) {
+  // text and next are equidistant from Next, but only one results in a valid
+  // initialization expression.
+  LinkedNode *next = node->Next();  // expected-error {{no member named 'Next' in 'initializerCorrections::LinkedNode'; did you mean 'next'?}}
+}
+
+struct NestedNode {
+  NestedNode* Nest();
+  NestedNode* next();
+  string text() const;
+};
+void f(NestedNode *node) {
+  // There are two equidistant, usable corrections for Next: next and Nest
+  NestedNode *next = node->Next();  // expected-error-re {{no member named 'Next' in 'initializerCorrections::NestedNode'{{$}}}}
+}
+}
+
+namespace PR21669 {
+void f(int *i) {
+  // Check that arguments to a builtin with custom type checking are corrected
+  // properly, since calls to such builtins bypass much of the normal code path
+  // for building and checking the call.
+  __atomic_load(i, i, something_something);  // expected-error-re {{use of undeclared identifier 'something_something'{{$}}}}
+}
+}
+
+const int DefaultArg = 9;  // expected-note {{'DefaultArg' declared here}}
+template <int I = defaultArg> struct S {};  // expected-error {{use of undeclared identifier 'defaultArg'; did you mean 'DefaultArg'?}}
+S<1> s;
+
+namespace foo {}
+void test_paren_suffix() {
+  foo::bar({5, 6});  // expected-error-re {{no member named 'bar' in namespace 'foo'{{$}}}} \
+                     // expected-error {{expected expression}}
+}
+
+const int kNum = 10;  // expected-note {{'kNum' declared here}}
+class SomeClass {
+  int Kind;
+public:
+  explicit SomeClass() : Kind(kSum) {}  // expected-error {{use of undeclared identifier 'kSum'; did you mean 'kNum'?}}
+};
+
+// There used to be an issue with typo resolution inside overloads.
+struct AssertionResult { ~AssertionResult(); };
+AssertionResult Overload(const char *a);
+AssertionResult Overload(int a);
+void UseOverload() {
+  // expected-note@+1 {{'result' declared here}}
+  const char *result;
+  // expected-error@+1 {{use of undeclared identifier 'resulta'; did you mean 'result'?}}
+  Overload(resulta);
+}
+
+namespace PR21925 {
+struct X {
+  int get() { return 7; }  // expected-note {{'get' declared here}}
+};
+void test() {
+  X variable;  // expected-note {{'variable' declared here}}
+
+  // expected-error@+2 {{use of undeclared identifier 'variableX'; did you mean 'variable'?}}
+  // expected-error@+1 {{no member named 'getX' in 'PR21925::X'; did you mean 'get'?}}
+  int x = variableX.getX();
+}
+}
+
+namespace PR21905 {
+int (*a) () = (void)Z;  // expected-error-re {{use of undeclared identifier 'Z'{{$}}}}
+}
+
+namespace PR21947 {
+int blue;  // expected-note {{'blue' declared here}}
+__typeof blur y;  // expected-error {{use of undeclared identifier 'blur'; did you mean 'blue'?}}
+}
+
+namespace PR22092 {
+a = b ? : 0;  // expected-error {{C++ requires a type specifier for all declarations}} \
+              // expected-error-re {{use of undeclared identifier 'b'{{$}}}}
+}
+
+extern long clock (void);
+struct Pointer {
+  void set_xpos(int);
+  void set_ypos(int);
+};
+void MovePointer(Pointer &Click, int x, int y) {  // expected-note 2 {{'Click' declared here}}
+  click.set_xpos(x);  // expected-error {{use of undeclared identifier 'click'; did you mean 'Click'?}}
+  click.set_ypos(x);  // expected-error {{use of undeclared identifier 'click'; did you mean 'Click'?}}
+}
+
+namespace PR22250 {
+// expected-error@+4 {{use of undeclared identifier 'size_t'; did you mean 'sizeof'?}}
+// expected-error-re@+3 {{use of undeclared identifier 'y'{{$}}}}
+// expected-error-re@+2 {{use of undeclared identifier 'z'{{$}}}}
+// expected-error@+1 {{expected ';' after top level declarator}}
+int getenv_s(size_t *y, char(&z)) {}
+}
+
+namespace PR22291 {
+template <unsigned I> void f() {
+  unsigned *prio_bits_array;  // expected-note {{'prio_bits_array' declared here}}
+  // expected-error@+1 {{use of undeclared identifier 'prio_op_array'; did you mean 'prio_bits_array'?}}
+  __atomic_store_n(prio_op_array + I, false, __ATOMIC_RELAXED);
+}
+}
+
+namespace PR22297 {
+double pow(double x, double y);
+struct TimeTicks {
+  static void Now();  // expected-note {{'Now' declared here}}
+};
+void f() {
+  TimeTicks::now();  // expected-error {{no member named 'now' in 'PR22297::TimeTicks'; did you mean 'Now'?}}
+}
+}
diff --git a/test/SemaCXX/typo-correction-pt2.cpp b/test/SemaCXX/typo-correction-pt2.cpp
deleted file mode 100644
index 5d3f123..0000000
--- a/test/SemaCXX/typo-correction-pt2.cpp
+++ /dev/null
@@ -1,334 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wno-c++11-extensions %s
-//
-// FIXME: This file is overflow from test/SemaCXX/typo-correction.cpp due to a
-// hard-coded limit of 20 different typo corrections Sema::CorrectTypo will
-// attempt within a single file (which is to avoid having very broken files take
-// minutes to finally be rejected by the parser).
-
-namespace PR12951 {
-// If there are two corrections that have the same identifier and edit distance
-// and only differ by their namespaces, don't suggest either as a correction
-// since both are equally likely corrections.
-namespace foobar { struct Thing {}; }
-namespace bazquux { struct Thing {}; }
-void f() { Thing t; } // expected-error{{unknown type name 'Thing'}}
-}
-
-namespace bogus_keyword_suggestion {
-void test() {
-   status = "OK";  // expected-error-re {{use of undeclared identifier 'status'{{$}}}}
-   return status;  // expected-error-re {{use of undeclared identifier 'status'{{$}}}}
- }
-}
-
-namespace PR13387 {
-struct A {
-  void CreateFoo(float, float);
-  void CreateBar(float, float);
-};
-struct B : A {
-  using A::CreateFoo;
-  void CreateFoo(int, int);  // expected-note {{'CreateFoo' declared here}}
-};
-void f(B &x) {
-  x.Createfoo(0,0);  // expected-error {{no member named 'Createfoo' in 'PR13387::B'; did you mean 'CreateFoo'?}}
-}
-}
-
-struct DataStruct {void foo();};
-struct T {
- DataStruct data_struct;
- void f();
-};
-// should be void T::f();
-void f() {
- data_struct->foo();  // expected-error-re{{use of undeclared identifier 'data_struct'{{$}}}}
-}
-
-namespace PR12287 {
-class zif {
-  void nab(int);
-};
-void nab();  // expected-note{{'::PR12287::nab' declared here}}
-void zif::nab(int) {
-  nab();  // expected-error{{too few arguments to function call, expected 1, have 0; did you mean '::PR12287::nab'?}}
-}
-}
-
-namespace TemplateFunction {
-template <class T>
-void A(T) { }  // expected-note {{'::TemplateFunction::A' declared here}}
-
-template <class T>
-void B(T) { }  // expected-note {{'::TemplateFunction::B' declared here}}
-
-class Foo {
- public:
-  void A(int, int) {}
-  void B() {}
-};
-
-void test(Foo F, int num) {
-  F.A(num);  // expected-error {{too few arguments to function call, expected 2, have 1; did you mean '::TemplateFunction::A'?}}
-  F.B(num);  // expected-error {{too many arguments to function call, expected 0, have 1; did you mean '::TemplateFunction::B'?}}
-}
-}
-namespace using_suggestion_val_dropped_specifier {
-void FFF() {} // expected-note {{'::using_suggestion_val_dropped_specifier::FFF' declared here}}
-namespace N { }
-using N::FFF; // expected-error {{no member named 'FFF' in namespace 'using_suggestion_val_dropped_specifier::N'; did you mean '::using_suggestion_val_dropped_specifier::FFF'?}}
-}
-
-namespace class_member_typo_corrections {
-class Outer {
-public:
-  class Inner {};  // expected-note {{'Outer::Inner' declared here}}
-  Inner MyMethod(Inner arg);
-};
-
-Inner Outer::MyMethod(Inner arg) {  // expected-error {{unknown type name 'Inner'; did you mean 'Outer::Inner'?}}
-  return Inner();
-}
-
-class Result {
-public:
-  enum ResultType {
-    ENTITY,  // expected-note {{'Result::ENTITY' declared here}}
-    PREDICATE,  // expected-note {{'Result::PREDICATE' declared here}}
-    LITERAL  // expected-note {{'Result::LITERAL' declared here}}
-  };
-
-  ResultType type();
-};
-
-void test() {
-  Result result_cell;
-  switch (result_cell.type()) {
-  case ENTITY:  // expected-error {{use of undeclared identifier 'ENTITY'; did you mean 'Result::ENTITY'?}}
-  case LITERAL:  // expected-error {{use of undeclared identifier 'LITERAL'; did you mean 'Result::LITERAL'?}}
-  case PREDICAT:  // expected-error {{use of undeclared identifier 'PREDICAT'; did you mean 'Result::PREDICATE'?}}
-    break;
-  }
-}
-
-class Figure {
-  enum ResultType {
-    SQUARE,
-    TRIANGLE,
-    CIRCLE
-  };
-
-public:
-  ResultType type();
-};
-
-void testAccess() {
-  Figure obj;
-  switch (obj.type()) {  // expected-warning {{enumeration values 'SQUARE', 'TRIANGLE', and 'CIRCLE' not handled in switch}}
-  case SQUARE:  // expected-error-re {{use of undeclared identifier 'SQUARE'{{$}}}}
-  case TRIANGLE:  // expected-error-re {{use of undeclared identifier 'TRIANGLE'{{$}}}}
-  case CIRCE:  // expected-error-re {{use of undeclared identifier 'CIRCE'{{$}}}}
-    break;
-  }
-}
-}
-
-long readline(const char *, char *, unsigned long);
-void assign_to_unknown_var() {
-    deadline_ = 1;  // expected-error-re {{use of undeclared identifier 'deadline_'{{$}}}}
-}
-
-namespace no_ns_before_dot {
-namespace re2 {}
-void test() {
-    req.set_check(false);  // expected-error-re {{use of undeclared identifier 'req'{{$}}}}
-}
-}
-
-namespace PR17394 {
-  class A {
-  protected:
-    long zzzzzzzzzz;
-  };
-  class B : private A {};
-  B zzzzzzzzzy<>; // expected-error {{expected ';' after top level declarator}}{}
-}
-
-namespace correct_fields_in_member_funcs {
-struct S {
-  int my_member;  // expected-note {{'my_member' declared here}}
-  void f() { my_menber = 1; }  // expected-error {{use of undeclared identifier 'my_menber'; did you mean 'my_member'?}}
-};
-}
-
-namespace PR17019 {
-  template<class F>
-  struct evil {
-    evil(F de) {  // expected-note {{'de' declared here}}
-      de_;  // expected-error {{use of undeclared identifier 'de_'; did you mean 'de'?}} \
-            // expected-warning {{expression result unused}}
-    }
-    ~evil() {
-      de_->bar()  // expected-error {{use of undeclared identifier 'de_'}}
-    }
-  };
-
-  void meow() {
-    evil<int> Q(0); // expected-note {{in instantiation of member function}}
-  }
-}
-
-namespace fix_class_name_qualifier {
-class MessageHeaders {};
-class MessageUtils {
- public:
-  static void ParseMessageHeaders(int, int); // expected-note {{'MessageUtils::ParseMessageHeaders' declared here}}
-};
-
-void test() {
-  // No, we didn't mean to call MessageHeaders::MessageHeaders.
-  MessageHeaders::ParseMessageHeaders(5, 4); // expected-error {{no member named 'ParseMessageHeaders' in 'fix_class_name_qualifier::MessageHeaders'; did you mean 'MessageUtils::ParseMessageHeaders'?}}
-}
-}
-
-namespace PR18213 {  // expected-note {{'PR18213' declared here}}
-struct WrapperInfo {
-  int i;
-};
-
-template <typename T> struct Wrappable {
-  static WrapperInfo kWrapperInfo;
-};
-
-// Note the space before "::PR18213" is intended and needed, as it highlights
-// the actual typo, which is the leading "::".
-// TODO: Suggest removing the "::" from "::PR18213" (the right correction)
-// instead of incorrectly suggesting dropping "PR18213::WrapperInfo::".
-template <>
-PR18213::WrapperInfo ::PR18213::Wrappable<int>::kWrapperInfo = { 0 };  // expected-error {{no member named 'PR18213' in 'PR18213::WrapperInfo'; did you mean simply 'PR18213'?}} \
-                                                                       // expected-error {{C++ requires a type specifier for all declarations}}
-}
-
-namespace PR18651 {
-struct {
-  int x;
-} a, b;
-
-int y = x;  // expected-error-re {{use of undeclared identifier 'x'{{$}}}}
-}
-
-namespace PR18685 {
-template <class C, int I, int J>
-class SetVector {
- public:
-  SetVector() {}
-};
-
-template <class C, int I>
-class SmallSetVector : public SetVector<C, I, 8> {};
-
-class foo {};
-SmallSetVector<foo*, 2> fooSet;
-}
-
-PR18685::BitVector Map;  // expected-error-re {{no type named 'BitVector' in namespace 'PR18685'{{$}}}}
-
-namespace shadowed_template {
-template <typename T> class Fizbin {};  // expected-note {{'::shadowed_template::Fizbin' declared here}}
-class Baz {
-   int Fizbin();
-   // TODO: Teach the parser to recover from the typo correction instead of
-   // continuing to treat the template name as an implicit-int declaration.
-   Fizbin<int> qux;  // expected-error {{unknown type name 'Fizbin'; did you mean '::shadowed_template::Fizbin'?}} \
-                     // expected-error {{expected member name or ';' after declaration specifiers}}
-};
-}
-
-namespace PR18852 {
-void func() {
-  struct foo {
-    void bar() {}
-  };
-  bar();  // expected-error-re {{use of undeclared identifier 'bar'{{$}}}}
-}
-
-class Thread {
- public:
-  void Start();
-  static void Stop();  // expected-note {{'Thread::Stop' declared here}}
-};
-
-class Manager {
- public:
-  void Start(int);  // expected-note {{'Start' declared here}}
-  void Stop(int);  // expected-note {{'Stop' declared here}}
-};
-
-void test(Manager *m) {
-  // Don't suggest Thread::Start as a correction just because it has the same
-  // (unqualified) name and accepts the right number of args; this is a method
-  // call on an object in an unrelated class.
-  m->Start();  // expected-error-re {{too few arguments to function call, expected 1, have 0{{$}}}}
-  m->Stop();  // expected-error-re {{too few arguments to function call, expected 1, have 0{{$}}}}
-  Stop();  // expected-error {{use of undeclared identifier 'Stop'; did you mean 'Thread::Stop'?}}
-}
-
-}
-
-namespace std {
-class bernoulli_distribution {
- public:
-  double p() const;
-};
-}
-void test() {
-  // Make sure that typo correction doesn't suggest changing 'p' to
-  // 'std::bernoulli_distribution::p' as that is most likely wrong.
-  if (p)  // expected-error-re {{use of undeclared identifier 'p'{{$}}}}
-    return;
-}
-
-namespace PR19681 {
-  struct TypoA {};
-  struct TypoB {
-    void test();
-  private:
-    template<typename T> void private_memfn(T);  // expected-note{{declared here}}
-  };
-  void TypoB::test() {
-    // FIXME: should suggest 'PR19681::TypoB::private_memfn' instead of '::PR19681::TypoB::private_memfn'
-    (void)static_cast<void(TypoB::*)(int)>(&TypoA::private_memfn);  // expected-error{{no member named 'private_memfn' in 'PR19681::TypoA'; did you mean '::PR19681::TypoB::private_memfn'?}}
-  }
-}
-
-namespace testWantFunctionLikeCasts {
-  long test(bool a) {
-    if (a)
-      return struc(5.7);  // expected-error-re {{use of undeclared identifier 'struc'{{$}}}}
-    else
-      return lon(8.0);  // expected-error {{use of undeclared identifier 'lon'; did you mean 'long'?}}
-  }
-}
-
-namespace testCXXDeclarationSpecifierParsing {
-namespace test {
-  struct SomeSettings {};  // expected-note {{'test::SomeSettings' declared here}}
-}
-class Test {};
-int bar() {
-  Test::SomeSettings some_settings; // expected-error {{no type named 'SomeSettings' in 'testCXXDeclarationSpecifierParsing::Test'; did you mean 'test::SomeSettings'?}}
-}
-}
-
-namespace testNonStaticMemberHandling {
-struct Foo {
-  bool usesMetadata;  // expected-note {{'usesMetadata' declared here}}
-};
-int test(Foo f) {
-  if (UsesMetadata)  // expected-error-re {{use of undeclared identifier 'UsesMetadata'{{$}}}}
-    return 5;
-  if (f.UsesMetadata)  // expected-error {{no member named 'UsesMetadata' in 'testNonStaticMemberHandling::Foo'; did you mean 'usesMetadata'?}}
-    return 11;
-  return 0;
-}
-};
diff --git a/test/SemaCXX/typo-correction.cpp b/test/SemaCXX/typo-correction.cpp
index 4f19283..3249001 100644
--- a/test/SemaCXX/typo-correction.cpp
+++ b/test/SemaCXX/typo-correction.cpp
@@ -1,8 +1,9 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wno-c++11-extensions %s
-//
-// WARNING: Do not add more typo correction test cases to this file lest you run
-// afoul the hard-coded limit (escape hatch) of 20 different typos whose
-// correction was attempted by Sema::CorrectTypo
+// RUN: %clang_cc1 -fspell-checking-limit 0 -verify -Wno-c++11-extensions %s
+
+namespace PR21817{
+int a(-rsing[2]); // expected-error {{undeclared identifier 'rsing'; did you mean 'using'?}}
+                  // expected-error@-1 {{expected expression}}
+}
 
 struct errc {
   int v_;
@@ -97,7 +98,7 @@
 // Demonstrate a case where using only the cached value returns the wrong thing
 // when the cached value was the result of a previous callback object that only
 // accepts a subset of the current callback object.
-namespace {
+namespace cache_invalidation_test {
 using namespace unknown_type_test;
 void bar(long i);
 void before_caching_classname() {
@@ -284,13 +285,352 @@
   }
 }
 
-// This test should have one correction, followed by an error without a
-// suggestion due to exceeding the maximum number of typos for which correction
-// is attempted.
-namespace CorrectTypo_has_reached_its_limit {
-int flibberdy();  // expected-note{{'flibberdy' declared here}}
-int no_correction() {
-  return hibberdy() +  // expected-error{{use of undeclared identifier 'hibberdy'; did you mean 'flibberdy'?}}
-         gibberdy();  // expected-error-re{{use of undeclared identifier 'gibberdy'{{$}}}}
+namespace PR12951 {
+// If there are two corrections that have the same identifier and edit distance
+// and only differ by their namespaces, don't suggest either as a correction
+// since both are equally likely corrections.
+namespace foobar { struct Thing {}; }
+namespace bazquux { struct Thing {}; }
+void f() { Thing t; } // expected-error{{unknown type name 'Thing'}}
+}
+
+namespace bogus_keyword_suggestion {
+void test() {
+   status = "OK";  // expected-error-re {{use of undeclared identifier 'status'{{$}}}}
+   return status;  // expected-error-re {{use of undeclared identifier 'status'{{$}}}}
+ }
+}
+
+namespace PR13387 {
+struct A {
+  void CreateFoo(float, float);
+  void CreateBar(float, float);
 };
+struct B : A {
+  using A::CreateFoo;
+  void CreateFoo(int, int);  // expected-note {{'CreateFoo' declared here}}
+};
+void f(B &x) {
+  x.Createfoo(0,0);  // expected-error {{no member named 'Createfoo' in 'PR13387::B'; did you mean 'CreateFoo'?}}
+}
+}
+
+struct DataStruct {void foo();};
+struct T {
+ DataStruct data_struct;
+ void f();
+};
+// should be void T::f();
+void f() {
+ data_struct->foo();  // expected-error-re{{use of undeclared identifier 'data_struct'{{$}}}}
+}
+
+namespace PR12287 {
+class zif {
+  void nab(int);
+};
+void nab();  // expected-note{{'::PR12287::nab' declared here}}
+void zif::nab(int) {
+  nab();  // expected-error{{too few arguments to function call, expected 1, have 0; did you mean '::PR12287::nab'?}}
+}
+}
+
+namespace TemplateFunction {
+template <class T>
+void A(T) { }  // expected-note {{'::TemplateFunction::A' declared here}}
+
+template <class T>
+void B(T) { }  // expected-note {{'::TemplateFunction::B' declared here}}
+
+class Foo {
+ public:
+  void A(int, int) {}
+  void B() {}
+};
+
+void test(Foo F, int num) {
+  F.A(num);  // expected-error {{too few arguments to function call, expected 2, have 1; did you mean '::TemplateFunction::A'?}}
+  F.B(num);  // expected-error {{too many arguments to function call, expected 0, have 1; did you mean '::TemplateFunction::B'?}}
+}
+}
+namespace using_suggestion_val_dropped_specifier {
+void FFF() {} // expected-note {{'::using_suggestion_val_dropped_specifier::FFF' declared here}}
+namespace N { }
+using N::FFF; // expected-error {{no member named 'FFF' in namespace 'using_suggestion_val_dropped_specifier::N'; did you mean '::using_suggestion_val_dropped_specifier::FFF'?}}
+}
+
+namespace class_member_typo_corrections {
+class Outer {
+public:
+  class Inner {};  // expected-note {{'Outer::Inner' declared here}}
+  Inner MyMethod(Inner arg);
+};
+
+Inner Outer::MyMethod(Inner arg) {  // expected-error {{unknown type name 'Inner'; did you mean 'Outer::Inner'?}}
+  return Inner();
+}
+
+class Result {
+public:
+  enum ResultType {
+    ENTITY,  // expected-note {{'Result::ENTITY' declared here}}
+    PREDICATE,  // expected-note {{'Result::PREDICATE' declared here}}
+    LITERAL  // expected-note {{'Result::LITERAL' declared here}}
+  };
+
+  ResultType type();
+};
+
+void test() {
+  Result result_cell;
+  switch (result_cell.type()) {
+  case ENTITY:  // expected-error {{use of undeclared identifier 'ENTITY'; did you mean 'Result::ENTITY'?}}
+  case LITERAL:  // expected-error {{use of undeclared identifier 'LITERAL'; did you mean 'Result::LITERAL'?}}
+  case PREDICAT:  // expected-error {{use of undeclared identifier 'PREDICAT'; did you mean 'Result::PREDICATE'?}}
+    break;
+  }
+}
+
+class Figure {
+  enum ResultType {
+    SQUARE,
+    TRIANGLE,
+    CIRCLE
+  };
+
+public:
+  ResultType type();
+};
+
+void testAccess() {
+  Figure obj;
+  switch (obj.type()) {  // expected-warning {{enumeration values 'SQUARE', 'TRIANGLE', and 'CIRCLE' not handled in switch}}
+  case SQUARE:  // expected-error-re {{use of undeclared identifier 'SQUARE'{{$}}}}
+  case TRIANGLE:  // expected-error-re {{use of undeclared identifier 'TRIANGLE'{{$}}}}
+  case CIRCE:  // expected-error-re {{use of undeclared identifier 'CIRCE'{{$}}}}
+    break;
+  }
+}
+}
+
+long readline(const char *, char *, unsigned long);
+void assign_to_unknown_var() {
+    deadline_ = 1;  // expected-error-re {{use of undeclared identifier 'deadline_'{{$}}}}
+}
+
+namespace no_ns_before_dot {
+namespace re2 {}
+void test() {
+    req.set_check(false);  // expected-error-re {{use of undeclared identifier 'req'{{$}}}}
+}
+}
+
+namespace PR17394 {
+  class A {
+  protected:
+    long zzzzzzzzzz;
+  };
+  class B : private A {};
+  B zzzzzzzzzy<>; // expected-error {{expected ';' after top level declarator}}{}
+}
+
+namespace correct_fields_in_member_funcs {
+struct S {
+  int my_member;  // expected-note {{'my_member' declared here}}
+  void f() { my_menber = 1; }  // expected-error {{use of undeclared identifier 'my_menber'; did you mean 'my_member'?}}
+};
+}
+
+namespace PR17019 {
+  template<class F>
+  struct evil {
+    evil(F de) {  // expected-note {{'de' declared here}}
+      de_;  // expected-error {{use of undeclared identifier 'de_'; did you mean 'de'?}} \
+            // expected-warning {{expression result unused}}
+    }
+    ~evil() {
+      de_->bar()  // expected-error {{use of undeclared identifier 'de_'}}
+    }
+  };
+
+  void meow() {
+    evil<int> Q(0); // expected-note {{in instantiation of member function}}
+  }
+}
+
+namespace fix_class_name_qualifier {
+class MessageHeaders {};
+class MessageUtils {
+ public:
+  static void ParseMessageHeaders(int, int); // expected-note {{'MessageUtils::ParseMessageHeaders' declared here}}
+};
+
+void test() {
+  // No, we didn't mean to call MessageHeaders::MessageHeaders.
+  MessageHeaders::ParseMessageHeaders(5, 4); // expected-error {{no member named 'ParseMessageHeaders' in 'fix_class_name_qualifier::MessageHeaders'; did you mean 'MessageUtils::ParseMessageHeaders'?}}
+}
+}
+
+namespace PR18213 {  // expected-note {{'PR18213' declared here}}
+struct WrapperInfo {
+  int i;
+};
+
+template <typename T> struct Wrappable {
+  static WrapperInfo kWrapperInfo;
+};
+
+// Note the space before "::PR18213" is intended and needed, as it highlights
+// the actual typo, which is the leading "::".
+// TODO: Suggest removing the "::" from "::PR18213" (the right correction)
+// instead of incorrectly suggesting dropping "PR18213::WrapperInfo::".
+template <>
+PR18213::WrapperInfo ::PR18213::Wrappable<int>::kWrapperInfo = { 0 };  // expected-error {{no member named 'PR18213' in 'PR18213::WrapperInfo'; did you mean simply 'PR18213'?}} \
+                                                                       // expected-error {{C++ requires a type specifier for all declarations}}
+}
+
+namespace PR18651 {
+struct {
+  int x;
+} a, b;
+
+int y = x;  // expected-error-re {{use of undeclared identifier 'x'{{$}}}}
+}
+
+namespace PR18685 {
+template <class C, int I, int J>
+class SetVector {
+ public:
+  SetVector() {}
+};
+
+template <class C, int I>
+class SmallSetVector : public SetVector<C, I, 8> {};
+
+class foo {};
+SmallSetVector<foo*, 2> fooSet;
+}
+
+PR18685::BitVector Map;  // expected-error-re {{no type named 'BitVector' in namespace 'PR18685'{{$}}}}
+
+namespace shadowed_template {
+template <typename T> class Fizbin {};  // expected-note {{'::shadowed_template::Fizbin' declared here}}
+class Baz {
+   int Fizbin();
+   // TODO: Teach the parser to recover from the typo correction instead of
+   // continuing to treat the template name as an implicit-int declaration.
+   Fizbin<int> qux;  // expected-error {{unknown type name 'Fizbin'; did you mean '::shadowed_template::Fizbin'?}} \
+                     // expected-error {{expected member name or ';' after declaration specifiers}}
+};
+}
+
+namespace PR18852 {
+void func() {
+  struct foo {
+    void bar() {}
+  };
+  bar();  // expected-error-re {{use of undeclared identifier 'bar'{{$}}}}
+}
+
+class Thread {
+ public:
+  void Start();
+  static void Stop();  // expected-note {{'Thread::Stop' declared here}}
+};
+
+class Manager {
+ public:
+  void Start(int);  // expected-note {{'Start' declared here}}
+  void Stop(int);  // expected-note {{'Stop' declared here}}
+};
+
+void test(Manager *m) {
+  // Don't suggest Thread::Start as a correction just because it has the same
+  // (unqualified) name and accepts the right number of args; this is a method
+  // call on an object in an unrelated class.
+  m->Start();  // expected-error-re {{too few arguments to function call, expected 1, have 0{{$}}}}
+  m->Stop();  // expected-error-re {{too few arguments to function call, expected 1, have 0{{$}}}}
+  Stop();  // expected-error {{use of undeclared identifier 'Stop'; did you mean 'Thread::Stop'?}}
+}
+
+}
+
+namespace std {
+class bernoulli_distribution {
+ public:
+  double p() const;
+};
+}
+void test() {
+  // Make sure that typo correction doesn't suggest changing 'p' to
+  // 'std::bernoulli_distribution::p' as that is most likely wrong.
+  if (p)  // expected-error-re {{use of undeclared identifier 'p'{{$}}}}
+    return;
+}
+
+namespace PR19681 {
+  struct TypoA {};
+  struct TypoB {
+    void test();
+  private:
+    template<typename T> void private_memfn(T);  // expected-note{{declared here}}
+  };
+  void TypoB::test() {
+    // FIXME: should suggest 'PR19681::TypoB::private_memfn' instead of '::PR19681::TypoB::private_memfn'
+    (void)static_cast<void(TypoB::*)(int)>(&TypoA::private_memfn);  // expected-error{{no member named 'private_memfn' in 'PR19681::TypoA'; did you mean '::PR19681::TypoB::private_memfn'?}}
+  }
+}
+
+namespace testWantFunctionLikeCasts {
+  long test(bool a) {
+    if (a)
+      return struc(5.7);  // expected-error-re {{use of undeclared identifier 'struc'{{$}}}}
+    else
+      return lon(8.0);  // expected-error {{use of undeclared identifier 'lon'; did you mean 'long'?}}
+  }
+}
+
+namespace testCXXDeclarationSpecifierParsing {
+namespace test {
+  struct SomeSettings {};  // expected-note {{'test::SomeSettings' declared here}}
+}
+class Test {};
+int bar() {
+  Test::SomeSettings some_settings; // expected-error {{no type named 'SomeSettings' in 'testCXXDeclarationSpecifierParsing::Test'; did you mean 'test::SomeSettings'?}}
+}
+}
+
+namespace testNonStaticMemberHandling {
+struct Foo {
+  bool usesMetadata;  // expected-note {{'usesMetadata' declared here}}
+};
+int test(Foo f) {
+  if (UsesMetadata)  // expected-error-re {{use of undeclared identifier 'UsesMetadata'{{$}}}}
+    return 5;
+  if (f.UsesMetadata)  // expected-error {{no member named 'UsesMetadata' in 'testNonStaticMemberHandling::Foo'; did you mean 'usesMetadata'?}}
+    return 11;
+  return 0;
+}
+};
+
+namespace testMemberExprDeclarationNameInfo {
+  // The AST should only have the corrected name with no mention of 'data_'.
+  void f(int);
+  struct S {
+    int data;  // expected-note 2{{'data' declared here}}
+    void m_fn1() {
+      data_  // expected-error {{use of undeclared identifier 'data_'}}
+          [] =  // expected-error {{expected expression}}
+          f(data_);  // expected-error {{use of undeclared identifier 'data_'}}
+    }
+  };
+}
+
+namespace testArraySubscriptIndex {
+  struct S {
+    int data;  // expected-note {{'data' declared here}}
+    void m_fn1() {
+      (+)[data_];  // expected-error{{expected expression}} expected-error {{use of undeclared identifier 'data_'; did you mean 'data'}}
+    }
+  };
 }
diff --git a/test/SemaCXX/undefined-internal.cpp b/test/SemaCXX/undefined-internal.cpp
index d829380..0138967 100644
--- a/test/SemaCXX/undefined-internal.cpp
+++ b/test/SemaCXX/undefined-internal.cpp
@@ -163,7 +163,7 @@
 
     // Check that the checks work with unevaluated contexts
     (void)sizeof(p(A::used1));
-    (void)typeid(p(A::used1)); // xpected-note {{used here}}
+    (void)typeid(p(A::used1)); // expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}} xpected-note {{used here}}
 
     // Misc other testing
     a(A::unused, 1 ? A::used2 : A::used2); // xpected-note {{used here}}
diff --git a/test/SemaCXX/uninitialized.cpp b/test/SemaCXX/uninitialized.cpp
index 96dc011..018b1fe 100644
--- a/test/SemaCXX/uninitialized.cpp
+++ b/test/SemaCXX/uninitialized.cpp
@@ -1302,3 +1302,86 @@
 // expected-note@-1 {{in instantiation of member function 'template_class::C<int>::C' requested here}}
 
 }
+
+namespace base_class_access {
+struct A {
+  A();
+  A(int);
+
+  int i;
+  int foo();
+
+  static int bar();
+};
+
+struct B : public A {
+  B(int (*)[1]) : A() {}
+  B(int (*)[2]) : A(bar()) {}
+
+  B(int (*)[3]) : A(i) {}
+  // expected-warning@-1 {{base class 'base_class_access::A' is uninitialized when used here to access 'base_class_access::A::i'}}
+
+  B(int (*)[4]) : A(foo()) {}
+  // expected-warning@-1 {{base_class_access::A' is uninitialized when used here to access 'base_class_access::A::foo'}}
+};
+
+struct C {
+  C(int) {}
+};
+
+struct D : public C, public A {
+  D(int (*)[1]) : C(0) {}
+  D(int (*)[2]) : C(bar()) {}
+
+  D(int (*)[3]) : C(i) {}
+  // expected-warning@-1 {{base class 'base_class_access::A' is uninitialized when used here to access 'base_class_access::A::i'}}
+
+  D(int (*)[4]) : C(foo()) {}
+  // expected-warning@-1 {{base_class_access::A' is uninitialized when used here to access 'base_class_access::A::foo'}}
+};
+
+}
+
+namespace value {
+template <class T> T move(T t);
+template <class T> T notmove(T t);
+}
+namespace lvalueref {
+template <class T> T move(T& t);
+template <class T> T notmove(T& t);
+}
+namespace rvalueref {
+template <class T> T move(T&& t);
+template <class T> T notmove(T&& t);
+}
+
+namespace move_test {
+int a1 = std::move(a1); // expected-warning {{uninitialized}}
+int a2 = value::move(a2); // expected-warning {{uninitialized}}
+int a3 = value::notmove(a3); // expected-warning {{uninitialized}}
+int a4 = lvalueref::move(a4);
+int a5 = lvalueref::notmove(a5);
+int a6 = rvalueref::move(a6);
+int a7 = rvalueref::notmove(a7);
+
+void test() {
+  int a1 = std::move(a1); // expected-warning {{uninitialized}}
+  int a2 = value::move(a2); // expected-warning {{uninitialized}}
+  int a3 = value::notmove(a3); // expected-warning {{uninitialized}}
+  int a4 = lvalueref::move(a4);
+  int a5 = lvalueref::notmove(a5);
+  int a6 = rvalueref::move(a6);
+  int a7 = rvalueref::notmove(a7);
+}
+
+class A {
+  int a;
+  A(int (*) [1]) : a(std::move(a)) {} // expected-warning {{uninitialized}}
+  A(int (*) [2]) : a(value::move(a)) {} // expected-warning {{uninitialized}}
+  A(int (*) [3]) : a(value::notmove(a)) {} // expected-warning {{uninitialized}}
+  A(int (*) [4]) : a(lvalueref::move(a)) {}
+  A(int (*) [5]) : a(lvalueref::notmove(a)) {}
+  A(int (*) [6]) : a(rvalueref::move(a)) {}
+  A(int (*) [7]) : a(rvalueref::notmove(a)) {}
+};
+}
diff --git a/test/SemaCXX/using-decl-1.cpp b/test/SemaCXX/using-decl-1.cpp
index 40f80a7..e730c9d 100644
--- a/test/SemaCXX/using-decl-1.cpp
+++ b/test/SemaCXX/using-decl-1.cpp
@@ -255,3 +255,11 @@
     using A::goobar; // expected-error {{no member named 'goobar' in 'TypoCorrectTemplateMember::A'; did you mean 'foobar'?}}
   };
 }
+
+namespace use_instance_in_static {
+struct A { int n; };
+struct B : A {
+  using A::n;
+  static int f() { return n; } // expected-error {{invalid use of member 'n' in static member function}}
+};
+}
diff --git a/test/SemaCXX/vararg-non-pod.cpp b/test/SemaCXX/vararg-non-pod.cpp
index 66da996..39d4ccc 100644
--- a/test/SemaCXX/vararg-non-pod.cpp
+++ b/test/SemaCXX/vararg-non-pod.cpp
@@ -103,7 +103,7 @@
 int eat_base(...);
 
 void test_typeid(Base &base) {
-  (void)typeid(get_base(base)); // expected-warning{{cannot pass object of non-POD type 'Base' through variadic function; call will abort at runtime}}
+  (void)typeid(get_base(base)); // expected-warning{{cannot pass object of non-POD type 'Base' through variadic function; call will abort at runtime}} expected-warning{{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
   (void)typeid(eat_base(base)); // okay
 }
 
diff --git a/test/SemaCXX/virtual-override.cpp b/test/SemaCXX/virtual-override.cpp
index e95acab..ec884f3 100644
--- a/test/SemaCXX/virtual-override.cpp
+++ b/test/SemaCXX/virtual-override.cpp
@@ -46,7 +46,7 @@
 
 struct a { };
 struct a1 : a { };
-struct b : a, a1 { };
+struct b : a, a1 { }; // expected-warning{{direct base 'T4::a' is inaccessible due to ambiguity:\n    struct T4::b -> struct T4::a\n    struct T4::b -> struct T4::a1 -> struct T4::a}}
   
 class A {
   virtual a* f(); // expected-note{{overridden virtual function is here}}
diff --git a/test/SemaCXX/vtable-instantiation.cc b/test/SemaCXX/vtable-instantiation.cpp
similarity index 89%
rename from test/SemaCXX/vtable-instantiation.cc
rename to test/SemaCXX/vtable-instantiation.cpp
index 2a1b989..78f2b3e 100644
--- a/test/SemaCXX/vtable-instantiation.cc
+++ b/test/SemaCXX/vtable-instantiation.cpp
@@ -41,7 +41,7 @@
 
   void f()
   {
-    Target<int*>* traits = &Provider<int*>::Instance;
+    Target<int*>* traits = &Provider<int*>::Instance; // expected-note{{requested here}}
   }
 }
 
@@ -60,7 +60,7 @@
   };
 
   template <typename Type>
-  GMG<Type> GMG<Type>::singleton;
+  GMG<Type> GMG<Type>::singleton; // expected-note{{requested here}}
 
   void test(void) {
     GMG<int>::Method(); // expected-note{{in instantiation of}}
diff --git a/test/SemaCXX/warn-consumed-parsing.cpp b/test/SemaCXX/warn-consumed-parsing.cpp
index 5c0a04f..1796041 100644
--- a/test/SemaCXX/warn-consumed-parsing.cpp
+++ b/test/SemaCXX/warn-consumed-parsing.cpp
@@ -37,6 +37,7 @@
   void callableWhen0()  CALLABLE_WHEN("unconsumed");
   void callableWhen1()  CALLABLE_WHEN(42); // expected-error {{'callable_when' attribute requires a string}}
   void callableWhen2()  CALLABLE_WHEN("foo"); // expected-warning {{'callable_when' attribute argument not supported: foo}}
+  void callableWhen3()  CALLABLE_WHEN(unconsumed);
   void consumes()       SET_TYPESTATE(consumed);
   bool testUnconsumed() TEST_TYPESTATE(consumed);
 };
diff --git a/test/SemaCXX/warn-reinterpret-base-class.cpp b/test/SemaCXX/warn-reinterpret-base-class.cpp
index 0231f19..d73b487 100644
--- a/test/SemaCXX/warn-reinterpret-base-class.cpp
+++ b/test/SemaCXX/warn-reinterpret-base-class.cpp
@@ -20,7 +20,7 @@
 };
 class DDVA : public virtual DA {
 };
-class DMA : public virtual A, public virtual DA {
+class DMA : public virtual A, public virtual DA { //expected-warning{{direct base 'A' is inaccessible due to ambiguity:\n    class DMA -> class A\n    class DMA -> class DA -> class A}}
 };
 
 class B;
diff --git a/test/SemaCXX/warn-self-move.cpp b/test/SemaCXX/warn-self-move.cpp
new file mode 100644
index 0000000..23778c1
--- /dev/null
+++ b/test/SemaCXX/warn-self-move.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -fsyntax-only -Wself-move -std=c++11 -verify %s
+
+// definitions for std::move
+namespace std {
+inline namespace foo {
+template <class T> struct remove_reference { typedef T type; };
+template <class T> struct remove_reference<T&> { typedef T type; };
+template <class T> struct remove_reference<T&&> { typedef T type; };
+
+template <class T> typename remove_reference<T>::type &&move(T &&t);
+}
+}
+
+void int_test() {
+  int x = 5;
+  x = std::move(x);  // expected-warning{{explicitly moving}}
+  (x) = std::move(x);  // expected-warning{{explicitly moving}}
+
+  using std::move;
+  x = move(x);  // expected-warning{{explicitly moving}}
+}
+
+int global;
+void global_int_test() {
+  global = std::move(global);  // expected-warning{{explicitly moving}}
+  (global) = std::move(global);  // expected-warning{{explicitly moving}}
+
+  using std::move;
+  global = move(global);  // expected-warning{{explicitly moving}}
+}
+
+class field_test {
+  int x;
+  field_test(field_test&& other) {
+    x = std::move(x);  // expected-warning{{explicitly moving}}
+    x = std::move(other.x);
+    other.x = std::move(x);
+    other.x = std::move(other.x);  // expected-warning{{explicitly moving}}
+  }
+};
+
+struct A {};
+struct B { A a; };
+struct C { C() {}; ~C() {} };
+void struct_test() {
+  A a;
+  a = std::move(a);  // expected-warning{{explicitly moving}}
+
+  B b;
+  b = std::move(b);  // expected-warning{{explicitly moving}}
+  b.a = std::move(b.a);  // expected-warning{{explicitly moving}}
+
+  C c;
+  c = std::move(c);  // expected-warning{{explicitly moving}}
+}
diff --git a/test/SemaCXX/warn-thread-safety-analysis.cpp b/test/SemaCXX/warn-thread-safety-analysis.cpp
index 091e473..4f31d40 100644
--- a/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ b/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -3,31 +3,31 @@
 // FIXME: should also run  %clang_cc1 -fsyntax-only -verify -Wthread-safety -std=c++11 -Wc++98-compat %s
 // FIXME: should also run  %clang_cc1 -fsyntax-only -verify -Wthread-safety %s
 
-#define LOCKABLE            __attribute__ ((lockable))
-#define SCOPED_LOCKABLE     __attribute__ ((scoped_lockable))
-#define GUARDED_BY(x)       __attribute__ ((guarded_by(x)))
-#define GUARDED_VAR         __attribute__ ((guarded_var))
-#define PT_GUARDED_BY(x)    __attribute__ ((pt_guarded_by(x)))
-#define PT_GUARDED_VAR      __attribute__ ((pt_guarded_var))
-#define ACQUIRED_AFTER(...) __attribute__ ((acquired_after(__VA_ARGS__)))
-#define ACQUIRED_BEFORE(...) __attribute__ ((acquired_before(__VA_ARGS__)))
-#define EXCLUSIVE_LOCK_FUNCTION(...)    __attribute__ ((exclusive_lock_function(__VA_ARGS__)))
-#define SHARED_LOCK_FUNCTION(...)       __attribute__ ((shared_lock_function(__VA_ARGS__)))
-#define ASSERT_EXCLUSIVE_LOCK(...)      __attribute__ ((assert_exclusive_lock(__VA_ARGS__)))
-#define ASSERT_SHARED_LOCK(...)         __attribute__ ((assert_shared_lock(__VA_ARGS__)))
-#define EXCLUSIVE_TRYLOCK_FUNCTION(...) __attribute__ ((exclusive_trylock_function(__VA_ARGS__)))
-#define SHARED_TRYLOCK_FUNCTION(...)    __attribute__ ((shared_trylock_function(__VA_ARGS__)))
-#define UNLOCK_FUNCTION(...)            __attribute__ ((unlock_function(__VA_ARGS__)))
-#define LOCK_RETURNED(x)    __attribute__ ((lock_returned(x)))
-#define LOCKS_EXCLUDED(...) __attribute__ ((locks_excluded(__VA_ARGS__)))
-#define EXCLUSIVE_LOCKS_REQUIRED(...) \
-  __attribute__ ((exclusive_locks_required(__VA_ARGS__)))
-#define SHARED_LOCKS_REQUIRED(...) \
-  __attribute__ ((shared_locks_required(__VA_ARGS__)))
-#define NO_THREAD_SAFETY_ANALYSIS  __attribute__ ((no_thread_safety_analysis))
+#define LOCKABLE             __attribute__((lockable))
+#define SCOPED_LOCKABLE      __attribute__((scoped_lockable))
+#define GUARDED_BY(x)        __attribute__((guarded_by(x)))
+#define GUARDED_VAR          __attribute__((guarded_var))
+#define PT_GUARDED_BY(x)     __attribute__((pt_guarded_by(x)))
+#define PT_GUARDED_VAR       __attribute__((pt_guarded_var))
+#define ACQUIRED_AFTER(...)  __attribute__((acquired_after(__VA_ARGS__)))
+#define ACQUIRED_BEFORE(...) __attribute__((acquired_before(__VA_ARGS__)))
+#define EXCLUSIVE_LOCK_FUNCTION(...)    __attribute__((exclusive_lock_function(__VA_ARGS__)))
+#define SHARED_LOCK_FUNCTION(...)       __attribute__((shared_lock_function(__VA_ARGS__)))
+#define ASSERT_EXCLUSIVE_LOCK(...)      __attribute__((assert_exclusive_lock(__VA_ARGS__)))
+#define ASSERT_SHARED_LOCK(...)         __attribute__((assert_shared_lock(__VA_ARGS__)))
+#define EXCLUSIVE_TRYLOCK_FUNCTION(...) __attribute__((exclusive_trylock_function(__VA_ARGS__)))
+#define SHARED_TRYLOCK_FUNCTION(...)    __attribute__((shared_trylock_function(__VA_ARGS__)))
+#define UNLOCK_FUNCTION(...)            __attribute__((unlock_function(__VA_ARGS__)))
+#define EXCLUSIVE_UNLOCK_FUNCTION(...)  __attribute__((release_capability(__VA_ARGS__)))
+#define SHARED_UNLOCK_FUNCTION(...)     __attribute__((release_shared_capability(__VA_ARGS__)))
+#define LOCK_RETURNED(x)                __attribute__((lock_returned(x)))
+#define LOCKS_EXCLUDED(...)             __attribute__((locks_excluded(__VA_ARGS__)))
+#define EXCLUSIVE_LOCKS_REQUIRED(...)   __attribute__((exclusive_locks_required(__VA_ARGS__)))
+#define SHARED_LOCKS_REQUIRED(...)      __attribute__((shared_locks_required(__VA_ARGS__)))
+#define NO_THREAD_SAFETY_ANALYSIS       __attribute__((no_thread_safety_analysis))
 
 
-class  __attribute__((lockable)) Mutex {
+class LOCKABLE Mutex {
  public:
   void Lock() __attribute__((exclusive_lock_function));
   void ReaderLock() __attribute__((shared_lock_function));
@@ -43,16 +43,18 @@
   void AssertReaderHeld() ASSERT_SHARED_LOCK();
 };
 
-class __attribute__((scoped_lockable)) MutexLock {
+class SCOPED_LOCKABLE MutexLock {
  public:
-  MutexLock(Mutex *mu) __attribute__((exclusive_lock_function(mu)));
-  ~MutexLock() __attribute__((unlock_function));
+  MutexLock(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu);
+  MutexLock(Mutex *mu, bool adopt) EXCLUSIVE_LOCKS_REQUIRED(mu);
+  ~MutexLock() UNLOCK_FUNCTION();
 };
 
-class __attribute__((scoped_lockable)) ReaderMutexLock {
+class SCOPED_LOCKABLE ReaderMutexLock {
  public:
-  ReaderMutexLock(Mutex *mu) __attribute__((exclusive_lock_function(mu)));
-  ~ReaderMutexLock() __attribute__((unlock_function));
+  ReaderMutexLock(Mutex *mu) SHARED_LOCK_FUNCTION(mu);
+  ReaderMutexLock(Mutex *mu, bool adopt) SHARED_LOCKS_REQUIRED(mu);
+  ~ReaderMutexLock() UNLOCK_FUNCTION();
 };
 
 class SCOPED_LOCKABLE ReleasableMutexLock {
@@ -4835,7 +4837,7 @@
     read2(10, *foosp);        // expected-warning {{reading the value pointed to by 'foosp' requires holding mutex 'mu'}}
     destroy(mymove(*foosp));  // expected-warning {{reading the value pointed to by 'foosp' requires holding mutex 'mu'}}
 
-    // TODO -- these requires better smart pointer handling.
+    // TODO -- these require better smart pointer handling.
     copy(*foosp.get());
     write1(*foosp.get());
     write2(10, *foosp.get());
@@ -4848,3 +4850,244 @@
 
 }  // end namespace PassByRefTest
 
+
+namespace AcquiredBeforeAfterText {
+
+class Foo {
+  Mutex mu1 ACQUIRED_BEFORE(mu2, mu3);
+  Mutex mu2;
+  Mutex mu3;
+
+  void test1() {
+    mu1.Lock();
+    mu2.Lock();
+    mu3.Lock();
+
+    mu3.Unlock();
+    mu2.Unlock();
+    mu1.Unlock();
+  }
+
+  void test2() {
+    mu2.Lock();
+    mu1.Lock();    // expected-warning {{mutex 'mu1' must be acquired before 'mu2'}}
+    mu1.Unlock();
+    mu2.Unlock();
+  }
+
+  void test3() {
+    mu3.Lock();
+    mu1.Lock();     // expected-warning {{mutex 'mu1' must be acquired before 'mu3'}}
+    mu1.Unlock();
+    mu3.Unlock();
+  }
+
+  void test4() EXCLUSIVE_LOCKS_REQUIRED(mu1) {
+    mu2.Lock();
+    mu2.Unlock();
+  }
+
+  void test5() EXCLUSIVE_LOCKS_REQUIRED(mu2) {
+    mu1.Lock();    // expected-warning {{mutex 'mu1' must be acquired before 'mu2'}}
+    mu1.Unlock();
+  }
+
+  void test6() EXCLUSIVE_LOCKS_REQUIRED(mu2) {
+    mu1.AssertHeld();
+  }
+
+  void test7() EXCLUSIVE_LOCKS_REQUIRED(mu1, mu2, mu3) { }
+
+  void test8() EXCLUSIVE_LOCKS_REQUIRED(mu3, mu2, mu1) { }
+};
+
+
+class Foo2 {
+  Mutex mu1;
+  Mutex mu2 ACQUIRED_AFTER(mu1);
+  Mutex mu3 ACQUIRED_AFTER(mu1);
+
+  void test1() {
+    mu1.Lock();
+    mu2.Lock();
+    mu3.Lock();
+
+    mu3.Unlock();
+    mu2.Unlock();
+    mu1.Unlock();
+  }
+
+  void test2() {
+    mu2.Lock();
+    mu1.Lock();     // expected-warning {{mutex 'mu1' must be acquired before 'mu2'}}
+    mu1.Unlock();
+    mu2.Unlock();
+  }
+
+  void test3() {
+    mu3.Lock();
+    mu1.Lock();     // expected-warning {{mutex 'mu1' must be acquired before 'mu3'}}
+    mu1.Unlock();
+    mu3.Unlock();
+  }
+};
+
+
+class Foo3 {
+  Mutex mu1 ACQUIRED_BEFORE(mu2);
+  Mutex mu2;
+  Mutex mu3 ACQUIRED_AFTER(mu2) ACQUIRED_BEFORE(mu4);
+  Mutex mu4;
+
+  void test1() {
+    mu1.Lock();
+    mu2.Lock();
+    mu3.Lock();
+    mu4.Lock();
+
+    mu4.Unlock();
+    mu3.Unlock();
+    mu2.Unlock();
+    mu1.Unlock();
+  }
+
+  void test2() {
+    mu4.Lock();
+    mu2.Lock();     // expected-warning {{mutex 'mu2' must be acquired before 'mu4'}}
+
+    mu2.Unlock();
+    mu4.Unlock();
+  }
+
+  void test3() {
+    mu4.Lock();
+    mu1.Lock();     // expected-warning {{mutex 'mu1' must be acquired before 'mu4'}}
+
+    mu1.Unlock();
+    mu4.Unlock();
+  }
+
+  void test4() {
+    mu3.Lock();
+    mu1.Lock();     // expected-warning {{mutex 'mu1' must be acquired before 'mu3'}}
+
+    mu1.Unlock();
+    mu3.Unlock();
+  }
+};
+
+
+// Test transitive DAG traversal with AFTER
+class Foo4 {
+  Mutex mu1;
+  Mutex mu2 ACQUIRED_AFTER(mu1);
+  Mutex mu3 ACQUIRED_AFTER(mu1);
+  Mutex mu4 ACQUIRED_AFTER(mu2, mu3);
+  Mutex mu5 ACQUIRED_AFTER(mu4);
+  Mutex mu6 ACQUIRED_AFTER(mu4);
+  Mutex mu7 ACQUIRED_AFTER(mu5, mu6);
+  Mutex mu8 ACQUIRED_AFTER(mu7);
+
+  void test() {
+    mu8.Lock();
+    mu1.Lock();    // expected-warning {{mutex 'mu1' must be acquired before 'mu8'}}
+    mu1.Unlock();
+    mu8.Unlock();
+  }
+};
+
+
+// Test transitive DAG traversal with BEFORE
+class Foo5 {
+  Mutex mu1 ACQUIRED_BEFORE(mu2, mu3);
+  Mutex mu2 ACQUIRED_BEFORE(mu4);
+  Mutex mu3 ACQUIRED_BEFORE(mu4);
+  Mutex mu4 ACQUIRED_BEFORE(mu5, mu6);
+  Mutex mu5 ACQUIRED_BEFORE(mu7);
+  Mutex mu6 ACQUIRED_BEFORE(mu7);
+  Mutex mu7 ACQUIRED_BEFORE(mu8);
+  Mutex mu8;
+
+  void test() {
+    mu8.Lock();
+    mu1.Lock();  // expected-warning {{mutex 'mu1' must be acquired before 'mu8'}}
+    mu1.Unlock();
+    mu8.Unlock();
+  }
+};
+
+
+class Foo6 {
+  Mutex mu1 ACQUIRED_AFTER(mu3);     // expected-warning {{Cycle in acquired_before/after dependencies, starting with 'mu1'}}
+  Mutex mu2 ACQUIRED_AFTER(mu1);     // expected-warning {{Cycle in acquired_before/after dependencies, starting with 'mu2'}}
+  Mutex mu3 ACQUIRED_AFTER(mu2);     // expected-warning {{Cycle in acquired_before/after dependencies, starting with 'mu3'}}
+
+  Mutex mu_b ACQUIRED_BEFORE(mu_b);  // expected-warning {{Cycle in acquired_before/after dependencies, starting with 'mu_b'}}
+  Mutex mu_a ACQUIRED_AFTER(mu_a);   // expected-warning {{Cycle in acquired_before/after dependencies, starting with 'mu_a'}}
+
+  void test0() {
+    mu_a.Lock();
+    mu_b.Lock();
+    mu_b.Unlock();
+    mu_a.Unlock();
+  }
+
+  void test1a() {
+    mu1.Lock();
+    mu1.Unlock();
+  }
+
+  void test1b() {
+    mu1.Lock();
+    mu_a.Lock();
+    mu_b.Lock();
+    mu_b.Unlock();
+    mu_a.Unlock();
+    mu1.Unlock();
+  }
+
+  void test() {
+    mu2.Lock();
+    mu2.Unlock();
+  }
+
+  void test3() {
+    mu3.Lock();
+    mu3.Unlock();
+  }
+};
+
+}  // end namespace AcquiredBeforeAfterTest
+
+
+namespace ScopedAdoptTest {
+
+class Foo {
+  Mutex mu;
+  int a GUARDED_BY(mu);
+  int b;
+
+  void test1() EXCLUSIVE_UNLOCK_FUNCTION(mu) {
+    MutexLock slock(&mu, true);
+    a = 0;
+  }
+
+  void test2() SHARED_UNLOCK_FUNCTION(mu) {
+    ReaderMutexLock slock(&mu, true);
+    b = a;
+  }
+
+  void test3() EXCLUSIVE_LOCKS_REQUIRED(mu) {  // expected-note {{mutex acquired here}}
+    MutexLock slock(&mu, true);
+    a = 0;
+  }  // expected-warning {{expecting mutex 'mu' to be held at the end of function}}
+
+  void test4() SHARED_LOCKS_REQUIRED(mu) {     // expected-note {{mutex acquired here}}
+    ReaderMutexLock slock(&mu, true);
+    b = a;
+  }  // expected-warning {{expecting mutex 'mu' to be held at the end of function}}
+
+};
+
+}  // end namespace ScopedAdoptTest
+
diff --git a/test/SemaCXX/warn-unused-result.cpp b/test/SemaCXX/warn-unused-result.cpp
index 1af0a01..7bdb424 100644
--- a/test/SemaCXX/warn-unused-result.cpp
+++ b/test/SemaCXX/warn-unused-result.cpp
@@ -132,7 +132,7 @@
   D d;
   C c;
   (void)typeid(f(), c); // Should not warn.
-  (void)typeid(f(), d); // expected-warning {{ignoring return value}}
+  (void)typeid(f(), d); // expected-warning {{ignoring return value}} expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
 
   // The sizeof expression operand is never evaluated.
   (void)sizeof(f(), c); // Should not warn.
diff --git a/test/SemaCXX/warn-unused-value-cxx11.cpp b/test/SemaCXX/warn-unused-value-cxx11.cpp
index 115ddf3..d929b4f 100644
--- a/test/SemaCXX/warn-unused-value-cxx11.cpp
+++ b/test/SemaCXX/warn-unused-value-cxx11.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -Wunused-value %s
-// expected-no-diagnostics
 
 void f() __attribute__((const));
 
@@ -13,4 +12,33 @@
 void g() {
   foo(1);
 }
+
+void h() {
+  int i = 0;
+  (void)noexcept(++i); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+  decltype(i++) j = 0; // expected-warning {{expression with side effects has no effect in an unevaluated context}}
 }
+
+struct S {
+  S operator++(int);
+  S(int i);
+  S();
+
+  int& f();
+  S g();
+};
+
+void j() {
+  S s;
+  int i = 0;
+  (void)noexcept(s++); // Ok
+  (void)noexcept(i++); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+  (void)noexcept(i = 5); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+  (void)noexcept(s = 5); // Ok
+
+  (void)sizeof(s.f()); // Ok
+  (void)sizeof(s.f() = 5); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+  (void)noexcept(s.g() = 5); // Ok
+}
+
+}
\ No newline at end of file
diff --git a/test/SemaCXX/warn-unused-value.cpp b/test/SemaCXX/warn-unused-value.cpp
index 4e1347c..efabd50 100644
--- a/test/SemaCXX/warn-unused-value.cpp
+++ b/test/SemaCXX/warn-unused-value.cpp
@@ -39,13 +39,13 @@
         void method() const {
          X* x;
          &x[0];  // expected-warning {{expression result unused}}
-        }  
+        }
       };
       typedef basic_string<char> string;
-      void func(const std::string& str) { 
+      void func(const std::string& str) {
         str.method();  // expected-note {{in instantiation of member function}}
       }
-    } 
+    }
   }
 }
 
@@ -69,3 +69,31 @@
   Unused(1, 1); // expected-warning {{expression result unused}}
 }
 }
+
+namespace std {
+  struct type_info {};
+}
+
+namespace test4 {
+struct Good { Good &f(); };
+struct Bad { virtual Bad& f(); };
+
+void f() {
+  int i = 0;
+  (void)typeid(++i); // expected-warning {{expression with side effects has no effect in an unevaluated context}}
+
+  Good g;
+  (void)typeid(g.f()); // Ok; not a polymorphic use of a glvalue.
+
+  // This is a polymorphic use of a glvalue, which results in the typeid being
+  // evaluated instead of unevaluated.
+  Bad b;
+  (void)typeid(b.f()); // expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
+
+  // A dereference of a volatile pointer is a side effecting operation, however
+  // since it is idiomatic code, and the alternatives induce higher maintenance
+  // costs, it is allowed.
+  int * volatile x;
+  (void)sizeof(*x); // Ok
+}
+}
diff --git a/test/SemaCXX/warn-weak-vtables.cpp b/test/SemaCXX/warn-weak-vtables.cpp
index 671ff29..d306653 100644
--- a/test/SemaCXX/warn-weak-vtables.cpp
+++ b/test/SemaCXX/warn-weak-vtables.cpp
@@ -20,15 +20,14 @@
     virtual void f() { }
   };
 
-  A *a;
-  a->f();
+  A a;
 }
 
 // Use the vtables
-void uses(A &a, B<int> &b, C &c) {
-  a.f();
-  b.f();
-  c.f();
+void uses_abc() {
+  A a;
+  B<int> b;
+  C c;
 }
 
 // <rdar://problem/9979458>
@@ -52,10 +51,9 @@
 
 Parent::~Parent() {}
 
-void uses(Parent &p, Derived &d, VeryDerived &vd) {
-  p.getFoo();
-  d.getFoo();
-  vd.getFoo();
+void uses_derived() {
+  Derived d;
+  VeryDerived vd;
 }
 
 template<typename T> struct TemplVirt {
@@ -72,8 +70,8 @@
   virtual void f() {}
 };
 
-void uses(TemplVirt<float>& f, TemplVirt<bool>& b, TemplVirt<long>& l) {
-  f.f();
-  b.f();
-  l.f();
+void uses_templ() {
+  TemplVirt<float> f;
+  TemplVirt<bool> b;
+  TemplVirt<long> l;
 }
diff --git a/test/SemaObjC/access-property-getter.m b/test/SemaObjC/access-property-getter.m
index afaf82e..41827bb 100644
--- a/test/SemaObjC/access-property-getter.m
+++ b/test/SemaObjC/access-property-getter.m
@@ -34,3 +34,20 @@
      return 0;
 }
 @end
+
+// rdar://19137815
+#pragma clang diagnostic ignored "-Wunused-getter-return-value"
+
+@interface NSObject @end
+
+@interface I : NSObject
+@property (copy) id window;
+@end
+
+@implementation I
+- (void) Meth {
+  [self window];
+  self.window;
+}
+@end
+
diff --git a/test/SemaObjC/arc-decls.m b/test/SemaObjC/arc-decls.m
index 7fcf576..c1c319d 100644
--- a/test/SemaObjC/arc-decls.m
+++ b/test/SemaObjC/arc-decls.m
@@ -54,13 +54,13 @@
 // rdar://15757510
 
 @interface J
-@property (retain) id newFoo; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
-@property (strong) id copyBar;  // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
-@property (copy) id allocBaz; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
+@property (retain) id newFoo; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note{{explicitly declare getter '-newFoo' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
+@property (strong) id copyBar;  // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note{{explicitly declare getter '-copyBar' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
+@property (copy) id allocBaz; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note{{explicitly declare getter '-allocBaz' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
 @property (copy, nonatomic) id new;
-@property (retain) id newDFoo; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
-@property (strong) id copyDBar; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
-@property (copy) id allocDBaz; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
+@property (retain) id newDFoo; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note{{explicitly declare getter '-newDFoo' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
+@property (strong) id copyDBar; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note{{explicitly declare getter '-copyDBar' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
+@property (copy) id allocDBaz; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note{{explicitly declare getter '-allocDBaz' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
 @end
 
 @implementation J
@@ -76,6 +76,29 @@
 @end
 
 
+@interface MethodFamilyDiags
+@property (retain) id newFoo; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
+- (id)newFoo; // expected-note {{explicitly declare getter '-newFoo' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
+
+#define OBJC_METHOD_FAMILY_NONE __attribute__((objc_method_family(none)))
+- (id)newBar; // expected-note {{explicitly declare getter '-newBar' with 'OBJC_METHOD_FAMILY_NONE' to return an 'unowned' object}}
+@property (retain) id newBar; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}}
+
+@property (retain) id newBaz; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note {{explicitly declare getter '-newBaz' with 'OBJC_METHOD_FAMILY_NONE' to return an 'unowned' object}}
+#undef OBJC_METHOD_FAMILY_NONE
+
+@property (retain, readonly) id newGarply; // expected-error {{property follows Cocoa naming convention for returning 'owned' objects}} expected-note {{explicitly declare getter '-newGarply' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object}}
+@end
+
+@interface MethodFamilyDiags (Redeclarations)
+- (id)newGarply; // no note here
+@end
+
+@implementation MethodFamilyDiags
+@synthesize newGarply;
+@end
+
+
 // rdar://10187884
 @interface Super
 - (void)bar:(id)b; // expected-note {{parameter declared here}}
diff --git a/test/SemaObjC/arc-dict-bridged-cast.m b/test/SemaObjC/arc-dict-bridged-cast.m
index e00c47f..e683343 100644
--- a/test/SemaObjC/arc-dict-bridged-cast.m
+++ b/test/SemaObjC/arc-dict-bridged-cast.m
@@ -28,19 +28,12 @@
 
 NSMutableString *test() {
   NSDictionary *infoDictionary;
-  infoDictionary[kCFBundleNameKey] = 0; // expected-error {{indexing expression is invalid because subscript type 'CFStringRef' (aka 'const struct __CFString *') is not an integral or Objective-C pointer type}} \
-                                        // expected-error {{implicit conversion of C pointer type 'CFStringRef' (aka 'const struct __CFString *') to Objective-C pointer type '__strong id<NSCopying>' requires a bridged cast}} \
-                                        // expected-note {{use __bridge to convert directly (no change in ownership)}} \
-                                        // expected-note {{use CFBridgingRelease call to transfer ownership of a +1 'CFStringRef' (aka 'const struct __CFString *') into ARC}}
+  infoDictionary[kCFBundleNameKey] = 0; // expected-error {{indexing expression is invalid because subscript type 'CFStringRef' (aka 'const struct __CFString *') is not an integral or Objective-C pointer type}}
   return infoDictionary[CFStringCreateMutable(((void*)0), 100)]; // expected-error {{indexing expression is invalid because subscript type 'CFMutableStringRef' (aka 'struct __CFString *') is not an integral or Objective-C pointer type}} \
                                        // expected-error {{implicit conversion of C pointer type 'CFMutableStringRef' (aka 'struct __CFString *') to Objective-C pointer type '__strong id<NSCopying>' requires a bridged cast}} \
                                         // expected-note {{use CFBridgingRelease call to transfer ownership of a +1 'CFMutableStringRef' (aka 'struct __CFString *') into ARC}}
 					
 }
 
-// CHECK: fix-it:"{{.*}}":{31:18-31:18}:"(__bridge __strong id<NSCopying>)("
-// CHECK: fix-it:"{{.*}}":{31:34-31:34}:")"
-// CHECK: fix-it:"{{.*}}":{31:18-31:18}:"CFBridgingRelease("
-// CHECK: fix-it:"{{.*}}":{31:34-31:34}:")"
-// CHECK: fix-it:"{{.*}}":{35:25-35:25}:"CFBridgingRelease("
-// CHECK: fix-it:"{{.*}}":{35:63-35:63}:")"
+// CHECK: fix-it:"{{.*}}":{32:25-32:25}:"CFBridgingRelease("
+// CHECK: fix-it:"{{.*}}":{32:63-32:63}:")"
diff --git a/test/SemaObjC/arc-repeated-weak.mm b/test/SemaObjC/arc-repeated-weak.mm
index 64df92a..264c598 100644
--- a/test/SemaObjC/arc-repeated-weak.mm
+++ b/test/SemaObjC/arc-repeated-weak.mm
@@ -425,3 +425,17 @@
 }
 @end
 
+// rdar://19053620
+@interface NSNull
++ (NSNull *)null;
+@end
+
+@interface INTF @end
+
+@implementation INTF
+- (void) Meth : (id) data
+{
+  data = data ?: NSNull.null;
+}
+@end
+
diff --git a/test/SemaObjC/arc-unbridged-cast.m b/test/SemaObjC/arc-unbridged-cast.m
index 6a39e70..3c0e3f2 100644
--- a/test/SemaObjC/arc-unbridged-cast.m
+++ b/test/SemaObjC/arc-unbridged-cast.m
@@ -32,15 +32,20 @@
 CFStringRef auditedCreateString(void);
 #pragma clang arc_cf_code_audited end
 
+extern const CFStringRef kUserConst;
+
 void test1(int cond) {
   id x;
   x = (id) auditedString();
+  x = (id) kUserConst;
   x = (id) (cond ? auditedString() : (void*) 0);
   x = (id) (cond ? (void*) 0 : auditedString());
   x = (id) (cond ? (CFStringRef) @"help" : auditedString());
+  x = (id) (cond ? (CFStringRef) @"help" : kUserConst);
 
   x = (id) unauditedString(); // expected-error {{requires a bridged cast}} expected-note {{use __bridge to}} expected-note {{use CFBridgingRelease call to}}
   x = (id) (cond ? unauditedString() : (void*) 0); // expected-error {{requires a bridged cast}} expected-note {{use __bridge to}} expected-note {{use CFBridgingRelease call to}}
+  x = (id) (cond ? unauditedString() : kUserConst); // expected-error {{requires a bridged cast}} expected-note {{use __bridge to}} expected-note {{use CFBridgingRelease call to}}
   x = (id) (cond ? (void*) 0 : unauditedString()); // expected-error {{requires a bridged cast}} expected-note {{use __bridge to}} expected-note {{use CFBridgingRelease call to}}
   x = (id) (cond ? (CFStringRef) @"help" : unauditedString()); // expected-error {{requires a bridged cast}} expected-note {{use __bridge to}} expected-note {{use CFBridgingRelease call to}}
 
@@ -68,11 +73,13 @@
   x = (id) (cond ? [object makeString] : (void*) 0);
   x = (id) (cond ? (void*) 0 : [object makeString]);
   x = (id) (cond ? (CFStringRef) @"help" : [object makeString]);  
+  x = (id) (cond ? kUserConst : [object makeString]);
 
   x = (id) [object newString];
   x = (id) (cond ? [object newString] : (void*) 0);
   x = (id) (cond ? (void*) 0 : [object newString]);
   x = (id) (cond ? (CFStringRef) @"help" : [object newString]); // a bit questionable
+  x = (id) (cond ? kUserConst : [object newString]); // expected-error{{requires a bridged cast}} expected-note{{use __bridge to}} expected-note{{use CFBridgingRelease call to}}
 }
 
 // rdar://problem/10246264
diff --git a/test/SemaObjC/attr-deprecated-pch.m b/test/SemaObjC/attr-deprecated-pch.m
new file mode 100644
index 0000000..2b48aea
--- /dev/null
+++ b/test/SemaObjC/attr-deprecated-pch.m
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -fsyntax-only -DBOTH -verify %s
+// If the decls come from a pch, the behavior shouldn't change:
+// RUN: %clang_cc1 -x objective-c-header %s -emit-pch -o %t
+// RUN: %clang_cc1 -DUSES -include-pch %t -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+// The slightly strange ifdefs are so that the command that builds the gch file
+// doesn't need any -D switches, for these would get embedded in the gch.
+
+#ifndef USES
+@interface Interface1
+- (void)partiallyUnavailableMethod;
+@end
+@interface Interface2
+- (void)partiallyUnavailableMethod __attribute__((unavailable));
+@end
+#endif
+
+#if defined(USES) || defined(BOTH)
+void f(id a) {
+  [a partiallyUnavailableMethod];  // no warning, `a` could be an Interface1.
+}
+#endif
diff --git a/test/SemaObjC/attr-deprecated.m b/test/SemaObjC/attr-deprecated.m
index 4d54d5d..14d33d3 100644
--- a/test/SemaObjC/attr-deprecated.m
+++ b/test/SemaObjC/attr-deprecated.m
@@ -258,3 +258,40 @@
 }
 @end
 
+@implementation UndeclaredImpl // expected-warning{{cannot find interface declaration}}
+- (void)partiallyUnavailableMethod {}
+@end
+
+@interface InterfaceWithSameMethodAsUndeclaredImpl
+- (void)partiallyUnavailableMethod __attribute__((unavailable));
+@end
+
+void f(id a) {
+  [a partiallyUnavailableMethod]; // no warning, `a` could be an UndeclaredImpl.
+}
+
+@interface InterfaceWithImplementation
+- (void)anotherPartiallyUnavailableMethod;
+@end
+@implementation InterfaceWithImplementation
+- (void)anotherPartiallyUnavailableMethod {}
+@end
+
+@interface InterfaceWithSameMethodAsInterfaceWithImplementation
+- (void)anotherPartiallyUnavailableMethod __attribute__((unavailable));
+@end
+
+void g(id a) {
+  [a anotherPartiallyUnavailableMethod]; // no warning, `a` could be an InterfaceWithImplementation.
+}
+
+typedef struct {} S1 __attribute__((unavailable)); // expected-note2{{marked unavailable here}}
+typedef struct {} S2 __attribute__((deprecated)); // expected-note2{{marked deprecated here}}
+@interface ExtensionForMissingInterface() // expected-error{{cannot find interface declaration}}
+- (void)method1:(S1) x; // expected-error{{is unavailable}}
+- (void)method2:(S2) x; // expected-warning{{is deprecated}}
+@end
+@interface CategoryForMissingInterface(Cat) // expected-error{{cannot find interface declaration}}
+- (void)method1:(S1) x; // expected-error{{is unavailable}}
+- (void)method2:(S2) x; // expected-warning{{is deprecated}}
+@end
diff --git a/test/SemaObjC/attr-designated-init.m b/test/SemaObjC/attr-designated-init.m
index 5350657..a8673e1 100644
--- a/test/SemaObjC/attr-designated-init.m
+++ b/test/SemaObjC/attr-designated-init.m
@@ -410,3 +410,11 @@
   return [super init];
 }
 @end
+
+@interface ExtensionForMissingInterface() // expected-error{{cannot find interface declaration}}
+- (instancetype)init NS_DESIGNATED_INITIALIZER;
+@end
+
+@interface CategoryForMissingInterface(Cat) // expected-error{{cannot find interface declaration}}
+- (instancetype)init NS_DESIGNATED_INITIALIZER; // expected-error{{only applies to init methods of interface or class extension declarations}}
+@end
diff --git a/test/SemaObjC/attr-malloc.m b/test/SemaObjC/attr-malloc.m
index a504b33..0874a47 100644
--- a/test/SemaObjC/attr-malloc.m
+++ b/test/SemaObjC/attr-malloc.m
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -verify -fsyntax-only -fblocks %s
 
 @interface TestAttrMallocOnMethods {}
-- (id) test1 __attribute((malloc)); //  expected-warning {{functions returning a pointer type}}
-- (int) test2 __attribute((malloc)); //  expected-warning {{functions returning a pointer type}}
+- (id) test1 __attribute((malloc)); //  expected-warning {{attribute only applies to functions}}
+- (int) test2 __attribute((malloc)); //  expected-warning {{attribute only applies to functions}}
 @end
 
 id bar(void) __attribute((malloc)); // no-warning
@@ -10,7 +10,7 @@
 typedef void (^bptr)(void);
 bptr baz(void) __attribute((malloc)); // no-warning
 
-__attribute((malloc)) id (*f)(); //  expected-warning {{functions returning a pointer type}}
-__attribute((malloc)) bptr (*g)(); //  expected-warning {{functions returning a pointer type}}
-__attribute((malloc)) void *(^h)(); //  expected-warning {{functions returning a pointer type}}
+__attribute((malloc)) id (*f)(); //  expected-warning {{attribute only applies to functions}}
+__attribute((malloc)) bptr (*g)(); //  expected-warning {{attribute only applies to functions}}
+__attribute((malloc)) void *(^h)(); //  expected-warning {{attribute only applies to functions}}
 
diff --git a/test/SemaObjC/format-ostrace-warning.m b/test/SemaObjC/format-ostrace-warning.m
new file mode 100644
index 0000000..c749881
--- /dev/null
+++ b/test/SemaObjC/format-ostrace-warning.m
@@ -0,0 +1,54 @@
+// RUN: %clang_cc1 -Wcstring-format-directive -verify -fsyntax-only %s
+// rdar://19904147
+
+typedef __builtin_va_list __darwin_va_list;
+typedef __builtin_va_list va_list;
+
+va_list argList;
+
+typedef const struct __CFString * CFStringRef;
+typedef struct __CFString * CFMutableStringRef;
+typedef const struct __CFAllocator * CFAllocatorRef;
+
+
+typedef const struct __CFDictionary * CFDictionaryRef;
+
+CFStringRef CFSTR ( const char *cStr );
+
+
+extern
+CFStringRef CStringCreateWithFormat(CFAllocatorRef alloc, CFDictionaryRef formatOptions, const char* format, ...) __attribute__((format(os_trace, 3, 4)));
+
+extern
+CFStringRef CStringCreateWithFormatAndArguments(CFAllocatorRef alloc, CFDictionaryRef formatOptions, const char* format, va_list arguments) __attribute__((format(os_trace, 3, 0)));
+
+extern
+void CStringAppendFormat(CFMutableStringRef theString, CFDictionaryRef formatOptions, const char* format, ...) __attribute__((format(os_trace, 3, 4)));
+
+extern
+void CStringAppendFormatAndArguments(CFMutableStringRef theString, CFDictionaryRef formatOptions, const char* format, va_list arguments) __attribute__((format(os_trace, 3, 0)));
+
+void Test1(va_list argList) {
+  CFAllocatorRef alloc;
+  CStringCreateWithFormatAndArguments (alloc, 0, "%s\n", argList);
+  CStringAppendFormatAndArguments ((CFMutableStringRef)@"AAAA", 0, "Hello %s there %d\n", argList);
+  CStringCreateWithFormatAndArguments (alloc, 0, "%c\n", argList);
+  CStringAppendFormatAndArguments ((CFMutableStringRef)@"AAAA", 0, "%d\n", argList);
+}
+
+extern void MyOSLog(const char* format, ...) __attribute__((format(os_trace, 1, 2)));
+extern void MyFStringCreateWithFormat(const char *format, ...) __attribute__((format(os_trace, 1, 2)));
+extern void XMyOSLog(int, const char* format, ...) __attribute__((format(os_trace, 2, 3)));
+extern void os_trace(const char *format, ...) __attribute__((format(os_trace, 1, 2)));
+
+void Test2() {
+  MyOSLog("%s\n", "Hello");
+
+  MyFStringCreateWithFormat("%s", "Hello"); 
+  XMyOSLog(4, "%s\n", "Hello");
+
+  os_trace("testing %@, %s, %d, %@, %m", CFSTR("object"), "string", 3, "it"); // expected-warning {{format specifies type 'id' but the argument has type 'char *'}}
+
+  os_trace("testing %@, %s, %d, %@, %m", CFSTR("object"), "string", 3, @"ok");
+}
+
diff --git a/test/SemaObjC/method-lookup-3.m b/test/SemaObjC/method-lookup-3.m
index b3d9c46..ff2c489 100644
--- a/test/SemaObjC/method-lookup-3.m
+++ b/test/SemaObjC/method-lookup-3.m
@@ -71,3 +71,29 @@
 void test4(id x) {
   (void) [x test4]; //expected-warning {{multiple methods named 'test4' found}}
 }
+
+// rdar://19265296
+#pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
+@interface NSObject 
++ (id)alloc;
++ (id)class;
+- (id) init;
+@end
+
+@class NSString;
+@interface A : NSObject
+- (instancetype)initWithType:(NSString *)whatever;
+@end
+
+@interface Test : NSObject @end
+
+@implementation Test
++ (instancetype)foo
+{
+    return [[[self class] alloc] initWithType:3];
+}
+- (instancetype)initWithType:(int)whatever
+{
+    return [super init];
+}
+@end
diff --git a/test/SemaObjC/objc-array-literal.m b/test/SemaObjC/objc-array-literal.m
index 706207d..2971fcc 100644
--- a/test/SemaObjC/objc-array-literal.m
+++ b/test/SemaObjC/objc-array-literal.m
@@ -9,6 +9,18 @@
 typedef unsigned int NSUInteger;
 #endif
 
+void checkNSArrayUnavailableDiagnostic() {
+  id obj;
+  id arr = @[obj]; // expected-error {{NSArray must be available to use Objective-C array literals}}
+}
+
+@class NSArray;
+
+void checkNSArrayFDDiagnostic() {
+  id obj;
+  id arr = @[obj]; // expected-error {{declaration of 'arrayWithObjects:count:' is missing in NSArray class}}
+}
+
 @class NSString;
 
 extern void NSLog(NSString *format, ...) __attribute__((format(__NSString__, 1, 2)));
diff --git a/test/SemaObjC/objc-dictionary-literal.m b/test/SemaObjC/objc-dictionary-literal.m
index f9fd57f..87f127f 100644
--- a/test/SemaObjC/objc-dictionary-literal.m
+++ b/test/SemaObjC/objc-dictionary-literal.m
@@ -5,6 +5,20 @@
 
 #define nil ((void *)0)
 
+void checkNSDictionaryUnavailableDiagnostic() {
+  id key;
+  id value;
+  id dict = @{ key : value }; // expected-error {{NSDictionary must be available to use Objective-C dictionary literals}}
+}
+
+@class NSDictionary;
+
+void checkNSDictionaryFDDiagnostic() {
+  id key;
+  id value;
+  id dic = @{ key : value }; // expected-error {{declaration of 'dictionaryWithObjects:forKeys:count:' is missing in NSDictionary class}}
+}
+
 @interface NSNumber
 + (NSNumber *)numberWithChar:(char)value;
 + (NSNumber *)numberWithInt:(int)value;
diff --git a/test/SemaObjC/objc-literal-nsnumber.m b/test/SemaObjC/objc-literal-nsnumber.m
index a2d3728..57bc07b 100644
--- a/test/SemaObjC/objc-literal-nsnumber.m
+++ b/test/SemaObjC/objc-literal-nsnumber.m
@@ -9,6 +9,24 @@
 typedef int NSInteger;
 #endif
 
+void checkNSNumberUnavailableDiagnostic() {
+  id num = @1000; // expected-error {{NSNumber must be available to use Objective-C literals}}
+
+  int x = 1000;
+  id num1 = @(x); // expected-error {{NSNumber must be available to use Objective-C literals}}\
+                  // expected-error {{illegal type 'int' used in a boxed expression}}
+}
+
+@class NSNumber;
+
+void checkNSNumberFDDiagnostic() {
+  id num = @1000; // expected-error {{NSNumber must be available to use Objective-C literals}}
+
+  int x = 1000;
+  id num1 = @(x); // expected-error {{declaration of 'numberWithInt:' is missing in NSNumber class}}\
+                  // expected-error {{illegal type 'int' used in a boxed expression}}
+}
+
 @interface NSObject
 + (NSObject*)nsobject;
 @end
diff --git a/test/SemaObjC/objcbridge-attribute-arc.m b/test/SemaObjC/objcbridge-attribute-arc.m
index ee2bf07..e08bd3d 100644
--- a/test/SemaObjC/objcbridge-attribute-arc.m
+++ b/test/SemaObjC/objcbridge-attribute-arc.m
@@ -9,28 +9,30 @@
 
 typedef struct __attribute__ ((objc_bridge)) __CFArray *CFArrayRef; // expected-error {{'objc_bridge' attribute takes one argument}}
 
-typedef void *  __attribute__ ((objc_bridge(NSURL))) CFURLRef;  // expected-error {{'objc_bridge' attribute only applies to struct or union}}
+typedef void *  __attribute__ ((objc_bridge(NSURL))) CFURLRef;  // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
-typedef void * CFStringRef __attribute__ ((objc_bridge(NSString))); // expected-error {{'objc_bridge' attribute only applies to struct or union}}
+typedef void * CFStringRef __attribute__ ((objc_bridge(NSString))); // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
 typedef struct __attribute__((objc_bridge(NSLocale, NSError))) __CFLocale *CFLocaleRef;// expected-error {{use of undeclared identifier 'NSError'}}
 
-typedef struct __CFData __attribute__((objc_bridge(NSData))) CFDataRef; // expected-error {{'objc_bridge' attribute only applies to struct or union}}
+typedef struct __CFData __attribute__((objc_bridge(NSData))) CFDataRef; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
 typedef struct __attribute__((objc_bridge(NSDictionary))) __CFDictionary * CFDictionaryRef;
 
-typedef struct __CFSetRef * CFSetRef __attribute__((objc_bridge(NSSet))); // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+typedef struct __CFSetRef * CFSetRef __attribute__((objc_bridge(NSSet))); // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
-typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) * CFUColorRef; // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) * CFUColorRef; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
-typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) *CFUColor1Ref; // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) * CFUColorRef; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
+
+typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) *CFUColor1Ref; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
 typedef union __attribute__((objc_bridge(NSUColor))) __CFUPrimeColor XXX;
 typedef XXX *CFUColor2Ref;
 
 @interface I
 {
-   __attribute__((objc_bridge(NSError))) void * color; // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+   __attribute__((objc_bridge(NSError))) void * color; // expected-error {{'objc_bridge' attribute only applies to structs, unions, and typedefs}};
 }
 @end
 
@@ -221,3 +223,19 @@
   (void)(__bridge Class)cf; // expected-warning {{'CFErrorRef2' (aka 'struct __CFErrorRef *') bridges to NSError, not 'Class'}}
   (void)(__bridge CFErrorRef)c; // expected-warning {{'__unsafe_unretained Class' cannot bridge to 'CFErrorRef' (aka 'struct __CFErrorRef *')}}
 }
+
+// rdar://19157264
+#if __has_feature(objc_bridge_id)
+typedef struct __attribute__((objc_bridge(id))) __CFFoo *CFFooRef;
+#endif
+
+id convert(CFFooRef obj) {
+  (void)(NSError *)obj; // expected-error {{cast of C pointer type 'CFFooRef' (aka 'struct __CFFoo *') to Objective-C pointer type 'NSError *' requires a bridged cast}} \
+                        // expected-note {{use __bridge to convert directly (no change in ownership)}} \
+                        // expected-note {{use __bridge_transfer to transfer ownership of a +1 'CFFooRef' (aka 'struct __CFFoo *') into ARC}}
+  (void) (__bridge NSError *)obj;
+  (void) (id)obj;       // expected-error {{cast of C pointer type 'CFFooRef' (aka 'struct __CFFoo *') to Objective-C pointer type 'id' requires a bridged cast}} \
+                        // expected-note {{use __bridge to convert directly (no change in ownership)}} \
+                        // expected-note {{use __bridge_transfer to transfer ownership of a +1 'CFFooRef' (aka 'struct __CFFoo *') into ARC}}
+  return (__bridge id)obj;
+}
diff --git a/test/SemaObjC/objcbridge-attribute.m b/test/SemaObjC/objcbridge-attribute.m
index a268cae..2969ebe 100644
--- a/test/SemaObjC/objcbridge-attribute.m
+++ b/test/SemaObjC/objcbridge-attribute.m
@@ -9,28 +9,36 @@
 
 typedef struct __attribute__ ((objc_bridge)) __CFArray *CFArrayRef; // expected-error {{'objc_bridge' attribute takes one argument}}
 
-typedef void *  __attribute__ ((objc_bridge(NSURL))) CFURLRef;  // expected-error {{'objc_bridge' attribute only applies to struct or union}}
+typedef void *  __attribute__ ((objc_bridge(NSURL))) CFURLRef;  // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
-typedef void * CFStringRef __attribute__ ((objc_bridge(NSString))); // expected-error {{'objc_bridge' attribute only applies to struct or union}}
+typedef void * CFStringRef __attribute__ ((objc_bridge(NSString))); // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
 typedef struct __attribute__((objc_bridge(NSLocale, NSError))) __CFLocale *CFLocaleRef;// expected-error {{use of undeclared identifier 'NSError'}}
 
-typedef struct __CFData __attribute__((objc_bridge(NSData))) CFDataRef; // expected-error {{'objc_bridge' attribute only applies to struct or union}}
+typedef struct __CFData __attribute__((objc_bridge(NSData))) CFDataRef; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
 typedef struct __attribute__((objc_bridge(NSDictionary))) __CFDictionary * CFDictionaryRef; // expected-note {{declared here}}
 
-typedef struct __CFSetRef * CFSetRef __attribute__((objc_bridge(NSSet))); // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+typedef struct __CFSetRef * CFSetRef __attribute__((objc_bridge(NSSet))); // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
-typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) * CFUColorRef; // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) * CFUColorRef; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
-typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) *CFUColor1Ref; // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+typedef union __CFUColor __attribute__((objc_bridge(NSUColor))) *CFUColor1Ref; // expected-error {{parameter of 'objc_bridge' attribute must be 'id' when used on a typedef}}
 
 typedef union __attribute__((objc_bridge(NSUColor))) __CFUPrimeColor XXX;
 typedef XXX *CFUColor2Ref;
 
+typedef const void *ConstVoidRef __attribute__((objc_bridge(id)));
+typedef void *VoidRef __attribute__((objc_bridge(id)));
+typedef struct Opaque *OpaqueRef __attribute__((objc_bridge(id))); // expected-error {{'objc_bridge(id)' is only allowed on structs and typedefs of void pointers}}
+
+#if !__has_feature(objc_bridge_id_on_typedefs)
+#error objc_bridge(id) on typedefs feature not found!
+#endif
+
 @interface I
 {
-   __attribute__((objc_bridge(NSError))) void * color; // expected-error {{'objc_bridge' attribute only applies to struct or union}};
+   __attribute__((objc_bridge(NSError))) void * color; // expected-error {{'objc_bridge' attribute only applies to structs, unions, and typedefs}};
 }
 @end
 
diff --git a/test/SemaObjC/selector-3.m b/test/SemaObjC/selector-3.m
index dfd216a..80332ec 100644
--- a/test/SemaObjC/selector-3.m
+++ b/test/SemaObjC/selector-3.m
@@ -134,3 +134,24 @@
     SEL s = @selector(compare:);
     (void)s;
 }
+
+// rdar://16607480
+@class NSString;
+@interface SELCanary : NSObject
+@property (readonly, nonatomic) NSString *name;
+@property (nonatomic, getter = isHidden) char hidden;
+@property (nonatomic, copy, getter = hasFish, setter = setFish:) NSString *ridiculousFish;
+@end
+
+@implementation SELCanary
+- (void) Meth {
+ SEL properties[] = {
+  @selector(name),
+  @selector(isHidden),
+  @selector(setHidden:),
+  @selector(hasFish),
+  @selector(setFish:)
+ };
+}
+@end
+
diff --git a/test/SemaObjC/super-property-notation.m b/test/SemaObjC/super-property-notation.m
index 2b13a5c..7d7b84d 100644
--- a/test/SemaObjC/super-property-notation.m
+++ b/test/SemaObjC/super-property-notation.m
@@ -50,3 +50,9 @@
   [super setFoo:foo]; // works with no warning
 }
 @end
+
+@implementation IFaceNotFound (Foo) // expected-error {{cannot find interface declaration for 'IFaceNotFound'}}
+-(int) foo {
+  return super.foo; // expected-error {{expected identifier or '('}}
+}
+@end
diff --git a/test/SemaObjC/unused.m b/test/SemaObjC/unused.m
index 6ea3fe8..f31e470 100644
--- a/test/SemaObjC/unused.m
+++ b/test/SemaObjC/unused.m
@@ -91,8 +91,7 @@
 
 void test3(PropertyObject *o)
 {
-  [o length]; // expected-warning {{property access result unused - getters should not be used for side effects}}
-  (void)[o length];
+  [o length]; // No warning. property name used in direct method call.
 }
 
 void test4(id o)
@@ -102,5 +101,30 @@
 
 void test5(id <P> p)
 {
-    [p property]; // expected-warning {{property access result unused - getters should not be used for side effects}}
+    [p property]; // No warning. property name used in direct method call.
 }
+
+// rdar://19773512
+@interface Model
+@property (nonatomic, retain, setter=setOrCreateGroup:, getter=getOrCreateGroup) id group;
+@end
+
+@implementation Model {
+    id _group;
+}
+- (void)method {
+    [self getOrCreateGroup];
+    self.getOrCreateGroup; // expected-warning {{property access result unused - getters should not be used for side effects}}
+    self.group; // expected-warning {{property access result unused - getters should not be used for side effects}}
+    self.group = (void*)0;
+    [self setOrCreateGroup : ((void*)0)];
+    
+}
+- (id)getOrCreateGroup {
+    if (!_group) {
+        _group = @"group";
+    }
+    return _group;
+}
+@end
+
diff --git a/test/SemaObjCXX/arc-ppe.mm b/test/SemaObjCXX/arc-ppe.mm
index c9ff811..193f273 100644
--- a/test/SemaObjCXX/arc-ppe.mm
+++ b/test/SemaObjCXX/arc-ppe.mm
@@ -13,4 +13,4 @@
 
 class Poly { virtual ~Poly(); };
 Poly& P(void*);
-void test2() { (void)typeid(P((void*)(id*)0)); } // expected-error {{pointer to non-const type 'id'}}
+void test2() { (void)typeid(P((void*)(id*)0)); } // expected-error {{pointer to non-const type 'id'}} expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
diff --git a/test/SemaObjCXX/propert-dot-error.mm b/test/SemaObjCXX/propert-dot-error.mm
index e28204c..02e7ddd 100644
--- a/test/SemaObjCXX/propert-dot-error.mm
+++ b/test/SemaObjCXX/propert-dot-error.mm
@@ -64,6 +64,6 @@
 void testD(D *d) {
   d.Forward::property = 17; // expected-error{{property access cannot be qualified with 'Forward::'}}
   d->Forward::ivar = 12; // expected-error{{instance variable access cannot be qualified with 'Forward::'}}
-  d.D::property = 17; // expected-error{{'D' is not a class, namespace, or scoped enumeration}}
-  d->D::ivar = 12; // expected-error{{'D' is not a class, namespace, or scoped enumeration}}
+  d.D::property = 17; // expected-error{{'D' is not a class, namespace, or enumeration}}
+  d->D::ivar = 12; // expected-error{{'D' is not a class, namespace, or enumeration}}
 }
diff --git a/test/SemaOpenCL/address-spaces-conversions-cl2.0.cl b/test/SemaOpenCL/address-spaces-conversions-cl2.0.cl
new file mode 100644
index 0000000..50363f2
--- /dev/null
+++ b/test/SemaOpenCL/address-spaces-conversions-cl2.0.cl
@@ -0,0 +1,227 @@
+// RUN: %clang_cc1 %s -ffake-address-space-map -verify -pedantic -fsyntax-only -DCONSTANT -cl-std=CL2.0
+// RUN: %clang_cc1 %s -ffake-address-space-map -verify -pedantic -fsyntax-only -DGLOBAL -cl-std=CL2.0
+// RUN: %clang_cc1 %s -ffake-address-space-map -verify -pedantic -fsyntax-only -DGENERIC -cl-std=CL2.0
+
+/* OpenCLC v2.0 adds a set of restrictions for conversions between pointers to
+*  different address spaces, mainly described in Sections 6.5.5 and 6.5.6.
+*
+*  It adds notion of overlapping address spaces. The main differention is that
+*  an unnamed address space is added, called '__generic'. Pointers to the
+*  generic address space can be interchangabley used with pointers to any
+*  other address space except for __constant address space (Section 6.5.5).
+*
+*  Based on this there are 3 sets of tests: __generic, named (__global in this
+*  case), and __constant, that should cover all program paths for CL address
+*  space conversions used in initialisations, assignments, casts, comparisons
+*  and arithmetic operations.
+*/
+
+#ifdef GENERIC
+#define AS generic
+#endif
+
+#ifdef GLOBAL
+#define AS global
+#endif
+
+#ifdef CONSTANT
+#define AS constant
+#endif
+
+void f_glob(global int *arg_glob) {}
+#ifndef GLOBAL
+// expected-note@-2{{passing argument to parameter 'arg_glob' here}}
+#endif
+
+void f_loc(local int *arg_loc) {
+} // expected-note@-1{{passing argument to parameter 'arg_loc' here}}
+
+void f_const(constant int *arg_const) {}
+#ifndef CONSTANT
+// expected-note@-2{{passing argument to parameter 'arg_const' here}}
+#endif
+
+void f_priv(private int *arg_priv) {
+} // expected-note@-1{{passing argument to parameter 'arg_priv' here}}
+
+void f_gen(generic int *arg_gen) {}
+#ifdef CONSTANT
+// expected-note@-2{{passing argument to parameter 'arg_gen' here}}
+#endif
+
+void test_conversion(global int *arg_glob, local int *arg_loc,
+                     constant int *arg_const, private int *arg_priv,
+                     generic int *arg_gen) {
+
+  AS int *var_init1 = arg_glob;
+#ifdef CONSTANT
+// expected-error@-2{{initializing '__constant int *' with an expression of type '__global int *' changes address space of pointer}}
+#endif
+
+  AS int *var_init2 = arg_loc;
+#ifndef GENERIC
+// expected-error-re@-2{{initializing '__{{global|constant}} int *' with an expression of type '__local int *' changes address space of pointer}}
+#endif
+
+  AS int *var_init3 = arg_const;
+#ifndef CONSTANT
+// expected-error-re@-2{{initializing '__{{global|generic}} int *' with an expression of type '__constant int *' changes address space of pointer}}
+#endif
+
+  AS int *var_init4 = arg_priv;
+#ifndef GENERIC
+// expected-error-re@-2{{initializing '__{{global|constant}} int *' with an expression of type 'int *' changes address space of pointer}}
+#endif
+
+  AS int *var_init5 = arg_gen;
+#ifndef GENERIC
+// expected-error-re@-2{{initializing '__{{global|constant}} int *' with an expression of type '__generic int *' changes address space of pointer}}
+#endif
+
+  AS int *var_cast1 = (AS int *)arg_glob;
+#ifdef CONSTANT
+// expected-error@-2{{casting '__global int *' to type '__constant int *' changes address space of pointer}}
+#endif
+
+  AS int *var_cast2 = (AS int *)arg_loc;
+#ifndef GENERIC
+// expected-error-re@-2{{casting '__local int *' to type '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  AS int *var_cast3 = (AS int *)arg_const;
+#ifndef CONSTANT
+// expected-error-re@-2{{casting '__constant int *' to type '__{{global|generic}} int *' changes address space of pointer}}
+#endif
+
+  AS int *var_cast4 = (AS int *)arg_priv;
+#ifndef GENERIC
+// expected-error-re@-2{{casting 'int *' to type '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  AS int *var_cast5 = (AS int *)arg_gen;
+#ifdef CONSTANT
+// expected-error@-2{{casting '__generic int *' to type '__constant int *' changes address space of pointer}}
+#endif
+
+  AS int *var_impl;
+  var_impl = arg_glob;
+#ifdef CONSTANT
+// expected-error@-2{{assigning '__global int *' to '__constant int *' changes address space of pointer}}
+#endif
+
+  var_impl = arg_loc;
+#ifndef GENERIC
+// expected-error-re@-2{{assigning '__local int *' to '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  var_impl = arg_const;
+#ifndef CONSTANT
+// expected-error-re@-2{{assigning '__constant int *' to '__{{global|generic}} int *' changes address space of pointer}}
+#endif
+
+  var_impl = arg_priv;
+#ifndef GENERIC
+// expected-error-re@-2{{assigning 'int *' to '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  var_impl = arg_gen;
+#ifndef GENERIC
+// expected-error-re@-2{{assigning '__generic int *' to '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  var_cast1 = (AS int *)arg_glob;
+#ifdef CONSTANT
+// expected-error@-2{{casting '__global int *' to type '__constant int *' changes address space of pointer}}
+#endif
+
+  var_cast2 = (AS int *)arg_loc;
+#ifndef GENERIC
+// expected-error-re@-2{{casting '__local int *' to type '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  var_cast3 = (AS int *)arg_const;
+#ifndef CONSTANT
+// expected-error-re@-2{{casting '__constant int *' to type '__{{global|generic}} int *' changes address space of pointer}}
+#endif
+
+  var_cast4 = (AS int *)arg_priv;
+#ifndef GENERIC
+// expected-error-re@-2{{casting 'int *' to type '__{{global|constant}} int *' changes address space of pointer}}
+#endif
+
+  var_cast5 = (AS int *)arg_gen;
+#ifdef CONSTANT
+// expected-error@-2{{casting '__generic int *' to type '__constant int *' changes address space of pointer}}
+#endif
+
+  AS int *var_cmp;
+  int b = var_cmp != arg_glob;
+#ifdef CONSTANT
+// expected-error@-2{{comparison between  ('__constant int *' and '__global int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_cmp != arg_loc;
+#ifndef GENERIC
+// expected-error-re@-2{{comparison between  ('__{{global|constant}} int *' and '__local int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_cmp == arg_const;
+#ifndef CONSTANT
+// expected-error-re@-2{{comparison between  ('__{{global|generic}} int *' and '__constant int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_cmp <= arg_priv;
+#ifndef GENERIC
+// expected-error-re@-2{{comparison between  ('__{{global|constant}} int *' and 'int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_cmp >= arg_gen;
+#ifdef CONSTANT
+// expected-error@-2{{comparison between  ('__constant int *' and '__generic int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  AS int *var_sub;
+  b = var_sub - arg_glob;
+#ifdef CONSTANT
+// expected-error@-2{{arithmetic operation with operands of type  ('__constant int *' and '__global int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_sub - arg_loc;
+#ifndef GENERIC
+// expected-error-re@-2{{arithmetic operation with operands of type  ('__{{global|constant}} int *' and '__local int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_sub - arg_const;
+#ifndef CONSTANT
+// expected-error-re@-2{{arithmetic operation with operands of type  ('__{{global|generic}} int *' and '__constant int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_sub - arg_priv;
+#ifndef GENERIC
+// expected-error-re@-2{{arithmetic operation with operands of type  ('__{{global|constant}} int *' and 'int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  b = var_sub - arg_gen;
+#ifdef CONSTANT
+// expected-error@-2{{arithmetic operation with operands of type  ('__constant int *' and '__generic int *') which are pointers to non-overlapping address spaces}}
+#endif
+
+  f_glob(var_sub);
+#ifndef GLOBAL
+// expected-error-re@-2{{passing '__{{constant|generic}} int *' to parameter of type '__global int *' changes address space of pointer}}
+#endif
+
+  f_loc(var_sub); // expected-error-re{{passing '__{{global|constant|generic}} int *' to parameter of type '__local int *' changes address space of pointer}}
+
+  f_const(var_sub);
+#ifndef CONSTANT
+// expected-error-re@-2{{passing '__{{global|generic}} int *' to parameter of type '__constant int *' changes address space of pointer}}
+#endif
+
+  f_priv(var_sub); // expected-error-re{{passing '__{{global|constant|generic}} int *' to parameter of type 'int *' changes address space of pointer}}
+
+  f_gen(var_sub);
+#ifdef CONSTANT
+// expected-error@-2{{passing '__constant int *' to parameter of type '__generic int *' changes address space of pointer}}
+#endif
+}
diff --git a/test/SemaOpenCL/amdgpu-num-register-attrs.cl b/test/SemaOpenCL/amdgpu-num-register-attrs.cl
new file mode 100644
index 0000000..ec8f8c0
--- /dev/null
+++ b/test/SemaOpenCL/amdgpu-num-register-attrs.cl
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -triple r600-- -verify -fsyntax-only %s
+
+typedef __attribute__((amdgpu_num_vgpr(128))) struct FooStruct { // expected-error {{'amdgpu_num_vgpr' attribute only applies to kernel functions}}
+  int x;
+  float y;
+} FooStruct;
+
+
+__attribute__((amdgpu_num_vgpr("ABC"))) kernel void foo2() {} // expected-error {{'amdgpu_num_vgpr' attribute requires an integer constant}}
+__attribute__((amdgpu_num_sgpr("ABC"))) kernel void foo3() {} // expected-error {{'amdgpu_num_sgpr' attribute requires an integer constant}}
+
+
+__attribute__((amdgpu_num_vgpr(40))) void foo4() {} // expected-error {{'amdgpu_num_vgpr' attribute only applies to kernel functions}}
+__attribute__((amdgpu_num_sgpr(64))) void foo5() {} // expected-error {{'amdgpu_num_sgpr' attribute only applies to kernel functions}}
+
+__attribute__((amdgpu_num_vgpr(40))) kernel void foo7() {}
+__attribute__((amdgpu_num_sgpr(64))) kernel void foo8() {}
+__attribute__((amdgpu_num_vgpr(40), amdgpu_num_sgpr(64))) kernel void foo9() {}
+
+// Check 0 VGPR is accepted.
+__attribute__((amdgpu_num_vgpr(0))) kernel void foo10() {}
+
+// Check 0 SGPR is accepted.
+__attribute__((amdgpu_num_sgpr(0))) kernel void foo11() {}
+
+// Check both 0 SGPR and VGPR is accepted.
+__attribute__((amdgpu_num_vgpr(0), amdgpu_num_sgpr(0))) kernel void foo12() {}
+
+// Too large VGPR value.
+__attribute__((amdgpu_num_vgpr(4294967296))) kernel void foo13() {} // expected-error {{integer constant expression evaluates to value 4294967296 that cannot be represented in a 32-bit unsigned integer type}}
+
+__attribute__((amdgpu_num_sgpr(4294967296))) kernel void foo14() {} // expected-error {{integer constant expression evaluates to value 4294967296 that cannot be represented in a 32-bit unsigned integer type}}
+
+__attribute__((amdgpu_num_sgpr(4294967296), amdgpu_num_vgpr(4294967296))) kernel void foo15() {} // expected-error 2 {{integer constant expression evaluates to value 4294967296 that cannot be represented in a 32-bit unsigned integer type}}
+
+
+// Make sure it is accepted with kernel keyword before the attribute.
+kernel __attribute__((amdgpu_num_vgpr(40))) void foo16() {}
+
+kernel __attribute__((amdgpu_num_sgpr(40))) void foo17() {}
diff --git a/test/SemaOpenCL/cond.cl b/test/SemaOpenCL/cond.cl
index 802ad9b..a1e32df 100644
--- a/test/SemaOpenCL/cond.cl
+++ b/test/SemaOpenCL/cond.cl
@@ -1,6 +1,132 @@
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only
-// expected-no-diagnostics
 
-typedef __attribute__((ext_vector_type(4))) float float4;
+typedef unsigned char uchar;
+typedef unsigned char uchar2 __attribute__((ext_vector_type(2)));
 
-float4 foo(float4 a, float4 b, float4 c, float4 d) { return a < b ? c : d; }
+typedef char char2 __attribute__((ext_vector_type(2)));
+typedef char char3 __attribute__((ext_vector_type(3)));
+
+typedef int int2 __attribute__((ext_vector_type(2)));
+
+typedef float float2 __attribute__((ext_vector_type(2)));
+
+// ** Positive tests **
+
+// all scalars, but widths do not match.
+int ptest01(char C, char X, int Y)
+{
+  return C ? X : Y;
+}
+
+char ptest02(int C, char X, char Y)
+{
+  return C ? X : Y;
+}
+
+// scalar condition and mixed-width vectors and scalars
+int2 ptest03(char C, char X, int2 Y)
+{
+  return C ? X : Y;
+}
+
+// uniform vectors
+char2 ptest04(char2 X, char2 Y, char2 C)
+{
+  return C ? X : Y;
+}
+
+// vector condition and mixed scalar operands
+int2 ptest05(int2 C, int X, char Y)
+{
+  return C ? X : Y;
+}
+
+// vector condition and matching scalar operands
+float2 ptest06(int2 C, float X, float Y)
+{
+  return C ? X : Y;
+}
+
+// vector condition and mixed scalar operands
+float2 ptest07(int2 C, int X, float Y)
+{
+  return C ? X : Y;
+}
+
+// vector condition and mixed scalar and vector operands
+float2 ptest08(int2 C, int X, float2 Y)
+{
+  return C ? X : Y;
+}
+
+// Actual comparison expression
+float2 ptest09(float2 A, float2 B, float2 C, float2 D)
+{
+  return A < B ? C : D;
+}
+
+// ** Negative tests **
+
+int2 ntest01(char2 C, int X, int Y)
+{
+  return C ? X : Y; // expected-error {{vector condition type 'char2' (vector of 2 'char' values) and result type (vector of 2 'int' values) do not have elements of the same size}}
+}
+
+int2 ntest02(char2 C, int2 X, int2 Y)
+{
+  return C ? X : Y; // expected-error {{vector condition type 'char2' (vector of 2 'char' values) and result type 'int2' (vector of 2 'int' values) do not have elements of the same size}}
+}
+
+uchar2 ntest03(int2 C, uchar X, uchar Y)
+{
+  return C ? X : Y; // expected-error {{vector condition type 'int2' (vector of 2 'int' values) and result type (vector of 2 'unsigned char' values) do not have elements of the same size}}
+}
+
+float2 ntest04(int2 C, int2 X, float2 Y)
+{
+  return C ? X : Y; // expected-error {{can't convert between vector values of different size ('int2' (vector of 2 'int' values) and 'float2' (vector of 2 'float' values))}}
+}
+
+float2 ntest05(int2 C, int2 X, float Y)
+{
+  return C ? X : Y; // expected-error {{can't convert between vector values of different size ('int2' (vector of 2 'int' values) and 'float')}}
+}
+
+char2 ntest06(int2 C, char2 X, char2 Y)
+{
+  return C ? X : Y; // expected-error {{vector condition type 'int2' (vector of 2 'int' values) and result type 'char2' (vector of 2 'char' values) do not have elements of the same size}}
+}
+
+float ntest07(float C, float X, float Y)
+{
+  return C ? X : Y; // expected-error {{used type 'float' where floating point type is not allowed}}
+}
+
+float2 ntest08(float2 C, float2 X, float2 Y)
+{
+  return C ? X : Y; // expected-error {{used type 'float2' (vector of 2 'float' values) where floating point type is not allowed}}
+}
+
+// Trying to create a int2 vector out of pointers.
+int2 ntest09(int2 C, global int *X, global int *Y)
+{
+  return C ? X : Y; // expected-error {{used type '__global int *' where integer or floating point type is required}}
+}
+
+char3 ntest10(char C, char3 X, char2 Y)
+{
+  return C ? X : Y; // expected-error {{can't convert between vector values of different size ('char3' (vector of 3 'char' values) and 'char2' (vector of 2 'char' values))}}
+}
+
+char3 ntest11(char2 C, char3 X, char Y)
+{
+  return C ? X : Y; // expected-error {{vector condition type 'char2' (vector of 2 'char' values) and result type 'char3' (vector of 3 'char' values) do not have the same number of elements}}
+}
+
+int foo1(int);
+int foo2(int);
+
+unsigned int ntest12(int2 C)
+{
+  return (unsigned int)(C ? foo1 : foo2); // expected-error {{taking address of function is not allowed}}
+}
diff --git a/test/SemaOpenCL/extension-fp64-cl1.1.cl b/test/SemaOpenCL/extension-fp64-cl1.1.cl
new file mode 100644
index 0000000..7e852ae
--- /dev/null
+++ b/test/SemaOpenCL/extension-fp64-cl1.1.cl
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL1.1
+
+void f1(double da) { // expected-error {{type 'double' requires cl_khr_fp64 extension}}
+  double d; // expected-error {{type 'double' requires cl_khr_fp64 extension}}
+  (void) 1.0; // expected-warning {{double precision constant requires cl_khr_fp64}}
+}
+
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
+
+void f2(void) {
+  double d;
+  (void) 1.0;
+}
+
+#pragma OPENCL EXTENSION cl_khr_fp64 : disable
+
+void f3(void) {
+  double d; // expected-error {{type 'double' requires cl_khr_fp64 extension}}
+}
diff --git a/test/SemaOpenCL/optional-core-fp64-cl1.2.cl b/test/SemaOpenCL/optional-core-fp64-cl1.2.cl
new file mode 100644
index 0000000..e0f7f1d
--- /dev/null
+++ b/test/SemaOpenCL/optional-core-fp64-cl1.2.cl
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL1.2
+// expected-no-diagnostics
+
+void f1(double da) {
+  double d;
+  (void) 1.0;
+}
+
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
+
+void f2(void) {
+  double d;
+  (void) 1.0;
+}
+
+#pragma OPENCL EXTENSION cl_khr_fp64 : disable
+
+void f3(void) {
+  double d;
+}
diff --git a/test/SemaOpenCL/optional-core-fp64-cl2.0.cl b/test/SemaOpenCL/optional-core-fp64-cl2.0.cl
new file mode 100644
index 0000000..832529d
--- /dev/null
+++ b/test/SemaOpenCL/optional-core-fp64-cl2.0.cl
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL2.0
+// expected-no-diagnostics
+
+void f1(double da) {
+  double d;
+  (void) 1.0;
+}
+
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
+
+void f2(void) {
+  double d;
+  (void) 1.0;
+}
+
+#pragma OPENCL EXTENSION cl_khr_fp64 : disable
+
+void f3(void) {
+  double d;
+}
diff --git a/test/SemaOpenCL/shifts.cl b/test/SemaOpenCL/shifts.cl
index 5b0c6fb..26f59a5 100644
--- a/test/SemaOpenCL/shifts.cl
+++ b/test/SemaOpenCL/shifts.cl
@@ -1,17 +1,61 @@
-// RUN: %clang_cc1 -x cl -O0 -emit-llvm  %s -o - -triple x86_64-linux-gnu | FileCheck %s
-// OpenCL essentially reduces all shift amounts to the last word-size bits before evaluating.
-// Test this both for variables and constants evaluated in the front-end.
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only
 
-// CHECK: @gtest1 = constant i64 2147483648
-__constant const unsigned long gtest1 = 1UL << 31;
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only
 
-// CHECK: @negativeShift32
-int negativeShift32(int a,int b) {
-  // CHECK: %array0 = alloca [256 x i8]
-  char array0[((int)1)<<40];
-  // CHECK: %array1 = alloca [256 x i8]
-  char array1[((int)1)<<(-24)];
+typedef __attribute__((ext_vector_type(2))) char char2;
+typedef __attribute__((ext_vector_type(3))) char char3;
 
-  // CHECK: ret i32 65536
-  return ((int)1)<<(-16);
+typedef __attribute__((ext_vector_type(2))) int int2;
+
+typedef __attribute__((ext_vector_type(2))) float float2;
+
+// ** Positive tests **
+
+char2 ptest01(char2 c, char s) {
+  return c << s;
+}
+
+char2 ptest02(char2 c, char2 s) {
+  return c << s;
+}
+
+char2 ptest03(char2 c, int s) {
+  return c << s;
+}
+
+char2 ptest04(char2 c, int2 s) {
+  return c << s;
+}
+
+int2 ptest05(int2 c, char2 s) {
+  return c << s;
+}
+
+char2 ptest06(char2 c) {
+  return c << 1;
+}
+
+void ptest07() {
+  char3 v = {1,1,1};
+  char3 w = {1,2,3};
+
+  v <<= w;
+}
+
+// ** Negative tests **
+
+char2 ntest01(char c, char2 s) {
+  return c << s; // expected-error {{requested shift is a vector of type 'char2' (vector of 2 'char' values) but the first operand is not a vector ('char')}}
+}
+
+char3 ntest02(char3 c, char2 s) {
+  return c << s; // expected-error {{vector operands do not have the same number of elements ('char3' (vector of 3 'char' values) and 'char2' (vector of 2 'char' values))}}
+}
+
+float2 ntest03(float2 c, char s) {
+  return c << s; // expected-error {{used type 'float2' (vector of 2 'float' values) where integer is required}}
+}
+
+int2 ntest04(int2 c, float s) {
+  return c << s; // expected-error {{used type 'float' where integer is required}}
 }
diff --git a/test/SemaTemplate/anonymous-union.cpp b/test/SemaTemplate/anonymous-union.cpp
index 97ecd6e..75d53aa 100644
--- a/test/SemaTemplate/anonymous-union.cpp
+++ b/test/SemaTemplate/anonymous-union.cpp
@@ -8,7 +8,7 @@
   };
 };
 template <typename T>
-struct T1 : public T0, public T { 
+struct T1 : public T0, public T { //expected-warning{{direct base 'T0' is inaccessible due to ambiguity:\n    struct T1<struct A> -> struct T0\n    struct T1<struct A> -> struct A -> struct T0}}
   void f0() { 
     m0 = 0; // expected-error{{ambiguous conversion}}
   } 
@@ -16,7 +16,7 @@
 
 struct A : public T0 { };
 
-void f1(T1<A> *S) { S->f0(); } // expected-note{{instantiation of member function}}
+void f1(T1<A> *S) { S->f0(); } // expected-note{{instantiation of member function}} expected-note{{in instantiation of template class 'T1<A>' requested here}}
 
 namespace rdar8635664 {
   template<typename T>
diff --git a/test/SemaTemplate/class-template-decl.cpp b/test/SemaTemplate/class-template-decl.cpp
index c67361b..4f861de 100644
--- a/test/SemaTemplate/class-template-decl.cpp
+++ b/test/SemaTemplate/class-template-decl.cpp
@@ -146,3 +146,9 @@
     };
   };
 }
+
+extern "C" template <typename T> // expected-error{{templates must have C++ linkage}}
+void DontCrashOnThis() {
+  T &pT = T();
+  pT;
+}
diff --git a/test/SemaTemplate/constructor-template.cpp b/test/SemaTemplate/constructor-template.cpp
index cf3fdfb..c5306a6 100644
--- a/test/SemaTemplate/constructor-template.cpp
+++ b/test/SemaTemplate/constructor-template.cpp
@@ -54,7 +54,7 @@
 struct X2 {
   X2(); // expected-note{{candidate constructor}}
   X2(X2&);	// expected-note {{candidate constructor}}
-  template<typename T> X2(T);
+  template<typename T> X2(T); // expected-note {{candidate template ignored: instantiation would take its own class type by value}}
 };
 
 X2 test(bool Cond, X2 x2) {
@@ -126,3 +126,51 @@
   }
 
 }
+
+// Don't blow out the stack trying to call an illegal constructor
+// instantiation.  We intentionally allow implicit instantiations to
+// exist, so make sure they're unusable.
+//
+// rdar://19199836
+namespace self_by_value {
+  template <class T, class U> struct A {
+    A() {}
+    A(const A<T,U> &o) {}
+    A(A<T,T> o) {}
+  };
+
+  void helper(A<int,float>);
+
+  void test1(A<int,int> a) {
+    helper(a);
+  }
+  void test2() {
+    helper(A<int,int>());
+  }
+}
+
+namespace self_by_value_2 {
+  template <class T, class U> struct A {
+    A() {} // expected-note {{not viable: requires 0 arguments}}
+    A(A<T,U> &o) {} // expected-note {{not viable: expects an l-value}}
+    A(A<T,T> o) {} // expected-note {{ignored: instantiation takes its own class type by value}}
+  };
+
+  void helper_A(A<int,int>); // expected-note {{passing argument to parameter here}}
+  void test_A() {
+    helper_A(A<int,int>()); // expected-error {{no matching constructor}}
+  }
+}
+
+namespace self_by_value_3 {
+  template <class T, class U> struct A {
+    A() {}
+    A(A<T,U> &o) {}
+    A(A<T,T> o) {}
+  };
+
+  void helper_A(A<int,int>);
+  void test_A(A<int,int> b) {
+    helper_A(b);
+  }
+}
diff --git a/test/SemaTemplate/deduction.cpp b/test/SemaTemplate/deduction.cpp
index c59f10d..e33d157 100644
--- a/test/SemaTemplate/deduction.cpp
+++ b/test/SemaTemplate/deduction.cpp
@@ -202,3 +202,8 @@
     using T = S<int, int>;
   }
 }
+
+namespace PR18645 {
+  template<typename F> F Quux(F &&f);
+  auto Baz = Quux(Quux<float>);
+}
diff --git a/test/SemaTemplate/dependent-names.cpp b/test/SemaTemplate/dependent-names.cpp
index 011e073..d5c9d66 100644
--- a/test/SemaTemplate/dependent-names.cpp
+++ b/test/SemaTemplate/dependent-names.cpp
@@ -414,3 +414,8 @@
   template<typename T> decltype(*T()) f() {} // expected-error {{redefinition}}
   template<typename T> decltype(T() * T()) g() {} // expected-error {{redefinition}}
 }
+
+template <typename> struct CT2 {
+  template <class U> struct X;
+};
+template <typename T> int CT2<int>::X<>; // expected-error {{template parameter list matching the non-templated nested type 'CT2<int>' should be empty}}
diff --git a/test/SemaTemplate/destructor-template.cpp b/test/SemaTemplate/destructor-template.cpp
index 4e1af9a..853ba49 100644
--- a/test/SemaTemplate/destructor-template.cpp
+++ b/test/SemaTemplate/destructor-template.cpp
@@ -52,9 +52,13 @@
 }
 
 namespace PR7904 {
-  struct Foo {
-    template <int i> ~Foo() {} // expected-error{{destructor cannot be declared as a template}}
-  };
+  struct Foo {};
+  template <class T>
+  Foo::~Foo() { // expected-error{{destructor cannot be declared as a template}}
+    T t;
+    T &pT = t;
+    pT;
+  }
   Foo f;
 }
 
diff --git a/test/SemaTemplate/enum-bool.cpp b/test/SemaTemplate/enum-bool.cpp
new file mode 100644
index 0000000..31a96e3
--- /dev/null
+++ b/test/SemaTemplate/enum-bool.cpp
@@ -0,0 +1,11 @@
+// %RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o %t
+
+enum E : bool { A };
+template <E>
+struct S {
+  struct Inner {
+    Inner() {}
+  };
+};
+
+template class S<A>;
diff --git a/test/SemaTemplate/explicit-instantiation.cpp b/test/SemaTemplate/explicit-instantiation.cpp
index 71121ad..040a932 100644
--- a/test/SemaTemplate/explicit-instantiation.cpp
+++ b/test/SemaTemplate/explicit-instantiation.cpp
@@ -164,3 +164,19 @@
 // expected-error@+1 0-1 {{exception specification in explicit instantiation does not match instantiated one}}
 template void Foo(double a) noexcept;
 #endif
+
+#if __cplusplus >= 201103L
+namespace PR21942 {
+template <int>
+struct A {
+  virtual void foo() final;
+};
+
+template <>
+void A<0>::foo() {} // expected-note{{overridden virtual function is here}}
+
+struct B : A<0> {
+  virtual void foo() override; // expected-error{{declaration of 'foo' overrides a 'final' function}}
+};
+}
+#endif
diff --git a/test/SemaTemplate/explicit-specialization-member.cpp b/test/SemaTemplate/explicit-specialization-member.cpp
index e8dc4d2..f302836 100644
--- a/test/SemaTemplate/explicit-specialization-member.cpp
+++ b/test/SemaTemplate/explicit-specialization-member.cpp
@@ -17,7 +17,7 @@
   {
     static locale::id id; // expected-error{{use of undeclared identifier}}
   };
-  numpunct<char>::~numpunct(); // expected-error{{expected the class name after '~' to name a destructor}}
+  numpunct<char>::~numpunct();
 }
 
 namespace PR12331 {
diff --git a/test/SemaTemplate/function-template-specialization-noreturn.cpp b/test/SemaTemplate/function-template-specialization-noreturn.cpp
index 3e1f618..672da27 100644
--- a/test/SemaTemplate/function-template-specialization-noreturn.cpp
+++ b/test/SemaTemplate/function-template-specialization-noreturn.cpp
@@ -6,3 +6,15 @@
 
 template <int N> void __attribute__((noreturn)) f3() { __builtin_unreachable(); }
 template <> void f3<1>() { } // expected-warning {{function declared 'noreturn' should not return}}
+
+#if __cplusplus >= 201103L
+namespace PR21942 {
+template <int>
+struct A {
+  void foo[[noreturn]]();
+};
+
+template <>
+void A<0>::foo() {} // expected-warning{{function declared 'noreturn' should not return}}
+}
+#endif
diff --git a/test/SemaTemplate/instantiate-method.cpp b/test/SemaTemplate/instantiate-method.cpp
index 58cb897..9618844 100644
--- a/test/SemaTemplate/instantiate-method.cpp
+++ b/test/SemaTemplate/instantiate-method.cpp
@@ -182,3 +182,28 @@
   };
   S<const int> s; // expected-note {{instantiation}}
 }
+
+namespace PR22040 {
+  template <typename T> struct Foobar {
+    template <> void bazqux(typename T::type) {}  // expected-error {{cannot specialize a function 'bazqux' within class scope}} expected-error 2{{cannot be used prior to '::' because it has no members}}
+  };
+
+  void test() {
+    // FIXME: we should suppress the "no member" errors
+    Foobar<void>::bazqux();  // expected-error{{no member named 'bazqux' in }}  expected-note{{in instantiation of template class }}
+    Foobar<int>::bazqux();  // expected-error{{no member named 'bazqux' in }}  expected-note{{in instantiation of template class }}
+    Foobar<int>::bazqux(3);  // expected-error{{no member named 'bazqux' in }}
+  }
+}
+
+template <typename>
+struct SpecializationOfGlobalFnInClassScope {
+  template <>
+  void ::Fn(); // expected-error{{cannot have a qualified name}}
+};
+
+class AbstractClassWithGlobalFn {
+  template <typename>
+  void ::f(); // expected-error{{cannot have a qualified name}}
+  virtual void f1() = 0;
+};
diff --git a/test/SemaTemplate/instantiate-non-dependent-types.cpp b/test/SemaTemplate/instantiate-non-dependent-types.cpp
index 432b905..1efd2a5 100644
--- a/test/SemaTemplate/instantiate-non-dependent-types.cpp
+++ b/test/SemaTemplate/instantiate-non-dependent-types.cpp
@@ -21,7 +21,7 @@
     T *q = new T();
     t.T::~T();
     q->~T();
-    // expected-error@+2 {{'int' is not a class, namespace, or scoped enumeration}}
+    // expected-error@+2 {{'int' is not a class, namespace, or enumeration}}
     // expected-error@+1 {{no member named '~Colors' in 'Colors'}}
     q->A::~A();
     // expected-error@+2 {{no member named '~int' in 'Q'}}
diff --git a/test/SemaTemplate/instantiate-static-var.cpp b/test/SemaTemplate/instantiate-static-var.cpp
index f309f29..a7b3433 100644
--- a/test/SemaTemplate/instantiate-static-var.cpp
+++ b/test/SemaTemplate/instantiate-static-var.cpp
@@ -114,3 +114,15 @@
   template class X1<char>;
 
 }
+
+typedef char MyString[100];
+template <typename T>
+struct StaticVarWithTypedefString {
+  static MyString str;
+};
+template <typename T>
+MyString StaticVarWithTypedefString<T>::str = "";
+
+void testStaticVarWithTypedefString() {
+  (void)StaticVarWithTypedefString<int>::str;
+}
diff --git a/test/SemaTemplate/ms-lookup-template-base-classes.cpp b/test/SemaTemplate/ms-lookup-template-base-classes.cpp
index 979782f..6245108 100644
--- a/test/SemaTemplate/ms-lookup-template-base-classes.cpp
+++ b/test/SemaTemplate/ms-lookup-template-base-classes.cpp
@@ -303,12 +303,12 @@
 }
 
 namespace two_types_in_base {
-template <typename T> struct A { typedef T NameFromBase; };
-template <typename T> struct B { struct NameFromBase { T m; }; };
+template <typename T> struct A { typedef T NameFromBase; }; // expected-note {{member found by ambiguous name lookup}}
+template <typename T> struct B { struct NameFromBase { T m; }; }; // expected-note {{member found by ambiguous name lookup}}
 template <typename T> struct C : A<T>, B<T> {
-  NameFromBase m; // expected-error {{unknown type name 'NameFromBase'}}
+  NameFromBase m; // expected-error {{member 'NameFromBase' found in multiple base classes of different types}} expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
 };
-static_assert(sizeof(C<int>) == 4, "");
+static_assert(sizeof(C<int>) == 4, ""); // expected-note {{in instantiation of template class 'two_types_in_base::C<int>' requested here}}
 }
 
 namespace type_and_decl_in_base {
@@ -386,9 +386,66 @@
 struct A { typedef int NameFromBase; };
 template <typename T>
 struct B : A {};
-// FIXME: MSVC accepts this.
 template <typename T>
-struct C : B<T> { NameFromBase m; }; // expected-error {{unknown type name 'NameFromBase'}}
+struct C : B<T> { NameFromBase m; }; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+}
+
+namespace type_in_second_dependent_base {
+template <typename T>
+struct A {};
+template<typename T>
+struct B { typedef T NameFromBase; };
+template <typename T>
+struct D : A<T>, B<T> { NameFromBase m; }; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+}
+
+namespace type_in_second_non_dependent_base {
+struct A {};
+struct B { typedef int NameFromBase; };
+template<typename T>
+struct C : A, B {};
+template <typename T>
+struct D : C<T> { NameFromBase m; }; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+}
+
+namespace type_in_virtual_base_of_dependent_base {
+template <typename T>
+struct A { typedef T NameFromBase; };
+template <typename T>
+struct B : virtual A<T> {};
+template <typename T>
+struct C : B<T>, virtual A<T> { NameFromBase m; }; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+C<int> c;
+}
+
+namespace type_in_base_of_multiple_dependent_bases {
+template <typename T>
+struct A { typedef T NameFromBase; };
+template <typename T>
+struct B : public A<T> {};
+template <typename T>
+struct C : B<T>, public A<T> { NameFromBase m; }; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}} expected-warning {{direct base 'A<int>' is inaccessible due to ambiguity:}}
+C<int> c; // expected-note {{in instantiation of template class 'type_in_base_of_multiple_dependent_bases::C<int>' requested here}}
+}
+
+namespace type_in_dependent_base_of_non_dependent_type {
+template<typename T> struct A { typedef int NameFromBase; };
+template<typename T> struct B : A<T> {
+  struct C;
+  template<typename TT>
+  struct D : C {
+    NameFromBase m; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+  };
+  struct E : C {
+    NameFromBase m; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+  };
+};
+template<typename T> struct B<T>::C : B {
+  NameFromBase m; // expected-warning {{use of identifier 'NameFromBase' found via unqualified lookup into dependent bases of class templates is a Microsoft extension}}
+};
+template<typename T> struct F : B<T>::C {
+  NameFromBase m; // expected-error {{unknown type name 'NameFromBase'}}
+};
 }
 
 namespace lookup_in_function_contexts {
diff --git a/test/SemaTemplate/overloaded-functions.cpp b/test/SemaTemplate/overloaded-functions.cpp
new file mode 100644
index 0000000..2656575
--- /dev/null
+++ b/test/SemaTemplate/overloaded-functions.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace {
+template <bool, typename>
+void Foo() {}
+
+template <int size>
+void Foo() {
+  int arr[size];
+  // expected-error@-1 {{'arr' declared as an array with a negative size}}
+}
+}
+
+void test_foo() {
+  Foo<-1>();
+  // expected-note@-1 {{in instantiation of function template specialization '(anonymous namespace)::Foo<-1>' requested here}}
+}
+
+template <bool, typename>
+void Bar() {}
+
+template <int size>
+void Bar() {
+  int arr[size];
+  // expected-error@-1 {{'arr' declared as an array with a negative size}}
+}
+
+void test_bar() {
+  Bar<-1>();
+  // expected-note@-1 {{in instantiation of function template specialization 'Bar<-1>' requested here}}
+}
+
diff --git a/test/SemaTemplate/temp_arg_enum_printing.cpp b/test/SemaTemplate/temp_arg_enum_printing.cpp
new file mode 100644
index 0000000..a788975
--- /dev/null
+++ b/test/SemaTemplate/temp_arg_enum_printing.cpp
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -fsyntax-only -ast-print %s | FileCheck %s
+
+namespace NamedEnumNS
+{
+  
+enum NamedEnum
+{
+  Val0,
+  Val1
+};
+  
+template <NamedEnum E>
+void foo();
+  
+void test() {
+  // CHECK: template <NamedEnumNS::NamedEnum E = NamedEnumNS::NamedEnum::Val0>
+  NamedEnumNS::foo<Val0>();
+  // CHECK: template <NamedEnumNS::NamedEnum E = NamedEnumNS::NamedEnum::Val1>
+  NamedEnumNS::foo<(NamedEnum)1>();
+  // CHECK: template <NamedEnumNS::NamedEnum E = 2>
+  NamedEnumNS::foo<(NamedEnum)2>();
+}
+  
+} // NamedEnumNS
diff --git a/test/SemaTemplate/temp_arg_nontype_cxx1z.cpp b/test/SemaTemplate/temp_arg_nontype_cxx1z.cpp
new file mode 100644
index 0000000..5000927
--- /dev/null
+++ b/test/SemaTemplate/temp_arg_nontype_cxx1z.cpp
@@ -0,0 +1,150 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z %s
+
+template<typename T, T val> struct A {};
+
+template<typename T, typename U> constexpr bool is_same = false; // expected-note +{{here}}
+template<typename T> constexpr bool is_same<T, T> = true;
+
+namespace String {
+  A<const char*, "test"> a; // expected-error {{does not refer to any declaration}}
+  A<const char (&)[5], "test"> b; // expected-error {{does not refer to any declaration}}
+}
+
+namespace Array {
+  char arr[3];
+  char x;
+  A<const char*, arr> a;
+  A<const char(&)[3], arr> b;
+  A<const char*, &arr[0]> c;
+  A<const char*, &arr[1]> d; // expected-error {{refers to subobject '&arr[1]'}}
+  A<const char*, (&arr)[0]> e;
+  A<const char*, &x> f;
+  A<const char*, &(&x)[0]> g;
+  A<const char*, &(&x)[1]> h; // expected-error {{refers to subobject '&x + 1'}}
+  A<const char*, 0> i; // expected-error {{not allowed in a converted constant}}
+  A<const char*, nullptr> j;
+}
+
+namespace Function {
+  void f();
+  void g() noexcept;
+  void h();
+  void h(int);
+  template<typename...T> void i(T...);
+  typedef A<void (*)(), f> a;
+  typedef A<void (*)(), &f> a;
+  typedef A<void (*)(), g> b;
+  typedef A<void (*)(), &g> b;
+  typedef A<void (*)(), h> c;
+  typedef A<void (*)(), &h> c;
+  typedef A<void (*)(), i> d;
+  typedef A<void (*)(), &i> d;
+  typedef A<void (*)(), i<>> d;
+  typedef A<void (*)(), i<int>> e; // expected-error {{is not implicitly convertible}}
+
+  typedef A<void (*)(), 0> x; // expected-error {{not allowed in a converted constant}}
+  typedef A<void (*)(), nullptr> y;
+}
+
+void Func() {
+  A<const char*, __func__> a; // expected-error {{does not refer to any declaration}}
+}
+
+namespace LabelAddrDiff {
+  void f() {
+    a: b: A<int, __builtin_constant_p(true) ? (__INTPTR_TYPE__)&&b - (__INTPTR_TYPE__)&&a : 0> s; // expected-error {{label address difference}}
+  };
+}
+
+namespace Temp {
+  struct S { int n; };
+  constexpr S &addr(S &&s) { return s; }
+  A<S &, addr({})> a; // expected-error {{constant}} expected-note 2{{temporary}}
+  A<S *, &addr({})> b; // expected-error {{constant}} expected-note 2{{temporary}}
+  A<int &, addr({}).n> c; // expected-error {{constant}} expected-note 2{{temporary}}
+  A<int *, &addr({}).n> d; // expected-error {{constant}} expected-note 2{{temporary}}
+}
+
+namespace std { struct type_info; }
+
+namespace RTTI {
+  A<const std::type_info&, typeid(int)> a; // expected-error {{does not refer to any declaration}}
+  A<const std::type_info*, &typeid(int)> b; // expected-error {{does not refer to any declaration}}
+}
+
+namespace PtrMem {
+  struct B { int b; };
+  struct C : B {};
+  struct D : B {};
+  struct E : C, D { int e; };
+
+  constexpr int B::*b = &B::b;
+  constexpr int C::*cb = b;
+  constexpr int D::*db = b;
+  constexpr int E::*ecb = cb; // expected-note +{{here}}
+  constexpr int E::*edb = db; // expected-note +{{here}}
+
+  constexpr int E::*e = &E::e;
+  constexpr int D::*de = (int D::*)e;
+  constexpr int C::*ce = (int C::*)e;
+  constexpr int B::*bde = (int B::*)de; // expected-note +{{here}}
+  constexpr int B::*bce = (int B::*)ce; // expected-note +{{here}}
+
+  // FIXME: This should all be accepted, but we don't yet have a representation
+  // nor mangling for this form of template argument.
+  using Ab = A<int B::*, b>;
+  using Ab = A<int B::*, &B::b>;
+  using Abce = A<int B::*, bce>; // expected-error {{not supported}}
+  using Abde = A<int B::*, bde>; // expected-error {{not supported}}
+  static_assert(!is_same<Ab, Abce>, ""); // expected-error {{undeclared}} expected-error {{must be a type}}
+  static_assert(!is_same<Ab, Abde>, ""); // expected-error {{undeclared}} expected-error {{must be a type}}
+  static_assert(!is_same<Abce, Abde>, ""); // expected-error 2{{undeclared}} expected-error {{must be a type}}
+  static_assert(is_same<Abce, A<int B::*, (int B::*)(int C::*)&E::e>, ""); // expected-error {{undeclared}} expected-error {{not supported}}
+
+  using Ae = A<int E::*, e>;
+  using Ae = A<int E::*, &E::e>;
+  using Aecb = A<int E::*, ecb>; // expected-error {{not supported}}
+  using Aedb = A<int E::*, edb>; // expected-error {{not supported}}
+  static_assert(!is_same<Ae, Aecb>, ""); // expected-error {{undeclared}} expected-error {{must be a type}}
+  static_assert(!is_same<Ae, Aedb>, ""); // expected-error {{undeclared}} expected-error {{must be a type}}
+  static_assert(!is_same<Aecb, Aedb>, ""); // expected-error 2{{undeclared}} expected-error {{must be a type}}
+  static_assert(is_same<Aecb, A<int E::*, (int E::*)(int C::*)&B::b>, ""); // expected-error {{undeclared}} expected-error {{not supported}}
+
+  using An = A<int E::*, nullptr>;
+  using A0 = A<int E::*, (int E::*)0>;
+  static_assert(is_same<An, A0>);
+}
+
+namespace DeduceDifferentType {
+  template<int N> struct A {};
+  template<long N> int a(A<N>); // expected-note {{does not have the same type}}
+  int a_imp = a(A<3>()); // expected-error {{no matching function}}
+  int a_exp = a<3>(A<3>());
+
+  template<decltype(nullptr)> struct B {};
+  template<int *P> int b(B<P>); // expected-note {{could not match}} expected-note {{not implicitly convertible}}
+  int b_imp = b(B<nullptr>()); // expected-error {{no matching function}}
+  int b_exp = b<nullptr>(B<nullptr>()); // expected-error {{no matching function}}
+
+  struct X { constexpr operator int() { return 0; } } x;
+  template<X &> struct C {};
+  template<int N> int c(C<N>); // expected-note {{does not have the same type}} expected-note {{not implicitly convertible}}
+  int c_imp = c(C<x>()); // expected-error {{no matching function}}
+  int c_exp = c<x>(C<x>()); // expected-error {{no matching function}}
+
+  struct Z;
+  struct Y { constexpr operator Z&(); } y;
+  struct Z { constexpr operator Y&() { return y; } } z;
+  constexpr Y::operator Z&() { return z; }
+  template<Y &> struct D {};
+  template<Z &z> int d(D<z>); // expected-note {{does not have the same type}}
+  int d_imp = d(D<y>()); // expected-error {{no matching function}}
+  int d_exp = d<y>(D<y>());
+}
+
+namespace DeclMatch {
+  template<typename T, T> int f();
+  template<typename T> class X { friend int f<T, 0>(); static int n; };
+  template<typename T, T> int f() { return X<T>::n; }
+  int k = f<int, 0>(); // ok, friend
+}
diff --git a/test/SemaTemplate/virtual-member-functions.cpp b/test/SemaTemplate/virtual-member-functions.cpp
index a23bf4e..4044f9e 100644
--- a/test/SemaTemplate/virtual-member-functions.cpp
+++ b/test/SemaTemplate/virtual-member-functions.cpp
@@ -3,19 +3,17 @@
 
 namespace PR5557 {
 template <class T> struct A {
-  A();
-  virtual void anchor();
+  A(); // expected-note{{instantiation}}
   virtual int a(T x);
 };
 template<class T> A<T>::A() {}
-template<class T> void A<T>::anchor() { }
 
 template<class T> int A<T>::a(T x) { 
   return *x; // expected-error{{requires pointer operand}}
 }
 
-void f(A<int> x) {
-  x.anchor(); // expected-note{{instantiation}}
+void f() {
+  A<int> x; // expected-note{{instantiation}}
 }
 
 template<typename T>
@@ -27,6 +25,24 @@
 void X<int>::f() { }
 }
 
+// Like PR5557, but with a defined destructor instead of a defined constructor.
+namespace PR5557_dtor {
+template <class T> struct A {
+  A(); // Don't have an implicit constructor.
+  ~A(); // expected-note{{instantiation}}
+  virtual int a(T x);
+};
+template<class T> A<T>::~A() {}
+
+template<class T> int A<T>::a(T x) { 
+  return *x; // expected-error{{requires pointer operand}}
+}
+
+void f() {
+  A<int> x; // expected-note{{instantiation}}
+}
+}
+
 template<typename T>
 struct Base {
   virtual ~Base() { 
@@ -94,12 +110,12 @@
 namespace DynamicCast {
   struct Y {};
   template<typename T> struct X : virtual Y {
-    virtual void foo() { T x; } // expected-error {{variable has incomplete type 'void'}}
+    virtual void foo() { T x; }
   };
   template<typename T> struct X2 : virtual Y {
     virtual void foo() { T x; }
   };
-  Y* f(X<void>* x) { return dynamic_cast<Y*>(x); } // expected-note {{in instantiation of member function 'DynamicCast::X<void>::foo' requested here}}
+  Y* f(X<void>* x) { return dynamic_cast<Y*>(x); }
   Y* f2(X<void>* x) { return dynamic_cast<Y*>(x); }
 }
 
diff --git a/test/VFS/Inputs/UsesFoo.framework/Headers/UsesFoo.h b/test/VFS/Inputs/UsesFoo.framework/Headers/UsesFoo.h
new file mode 100644
index 0000000..375d3ea
--- /dev/null
+++ b/test/VFS/Inputs/UsesFoo.framework/Headers/UsesFoo.h
@@ -0,0 +1 @@
+@import Foo;
diff --git a/test/VFS/Inputs/UsesFoo.framework/Modules/module.modulemap b/test/VFS/Inputs/UsesFoo.framework/Modules/module.modulemap
new file mode 100644
index 0000000..55be29e
--- /dev/null
+++ b/test/VFS/Inputs/UsesFoo.framework/Modules/module.modulemap
@@ -0,0 +1,4 @@
+framework module UsesFoo {
+  umbrella header "UsesFoo.h"
+  export *
+}
diff --git a/test/VFS/external-names.c b/test/VFS/external-names.c
index 52d0a8c..81ec4ec 100644
--- a/test/VFS/external-names.c
+++ b/test/VFS/external-names.c
@@ -28,8 +28,8 @@
 // Debug info
 
 // RUN: %clang_cc1 -I %t -ivfsoverlay %t.external.yaml -triple %itanium_abi_triple -g -emit-llvm %s -o - | FileCheck -check-prefix=CHECK-DEBUG-EXTERNAL %s
-// CHECK-DEBUG-EXTERNAL: ![[Num:[0-9]*]] = metadata !{metadata !"{{.*}}Inputs{{.}}external-names.h
-// CHECK-DEBUG-EXTERNAL: metadata !{metadata !"0x29", metadata ![[Num]]{{.*}}DW_TAG_file_type
+// CHECK-DEBUG-EXTERNAL: ![[Num:[0-9]*]] = !{!"{{.*}}Inputs{{.}}external-names.h
+// CHECK-DEBUG-EXTERNAL: !{!"0x29", ![[Num]]{{.*}}DW_TAG_file_type
 
 // RUN: %clang_cc1 -I %t -ivfsoverlay %t.yaml -triple %itanium_abi_triple -g -emit-llvm %s -o - | FileCheck -check-prefix=CHECK-DEBUG %s
 // CHECK-DEBUG-NOT: Inputs
diff --git a/test/VFS/umbrella-mismatch.m b/test/VFS/umbrella-mismatch.m
index f3a4ab3..741b0e6 100644
--- a/test/VFS/umbrella-mismatch.m
+++ b/test/VFS/umbrella-mismatch.m
@@ -4,4 +4,4 @@
 // RUN: %clang_cc1 -Werror -fmodules -fmodules-cache-path=%t -ivfsoverlay %t.yaml -F %S/Inputs -fsyntax-only %s -verify
 // RUN: %clang_cc1 -Werror -fmodules -fmodules-cache-path=%t -F %S/Inputs -fsyntax-only %s -verify
 // expected-no-diagnostics
-@import Foo;
+@import UsesFoo;
diff --git a/test/lit.cfg b/test/lit.cfg
index 4567f17..51e1e4f 100644
--- a/test/lit.cfg
+++ b/test/lit.cfg
@@ -44,7 +44,7 @@
 config.test_format = lit.formats.ShTest(execute_external)
 
 # suffixes: A list of file extensions to treat as test files.
-config.suffixes = ['.c', '.cpp', '.m', '.mm', '.cu', '.ll', '.cl', '.s', '.S']
+config.suffixes = ['.c', '.cpp', '.m', '.mm', '.cu', '.ll', '.cl', '.s', '.S', '.modulemap']
 
 # excludes: A list of directories to exclude from the testsuite. The 'Inputs'
 # subdirectories contain auxiliary inputs for various tests in their parent
@@ -306,6 +306,7 @@
 # For example, don't match 'clang-check-' or '.clang-format'.
 NoPreHyphenDot = r"(?<!(-|\.))"
 NoPostHyphenDot = r"(?!(-|\.))"
+NoPostBar = r"(?!(/|\\))"
 
 for pattern in [r"\bFileCheck\b",
                 r"\bc-index-test\b",
@@ -313,7 +314,7 @@
                 NoPreHyphenDot + r"\bclang-format\b" + NoPostHyphenDot,
                 NoPreHyphenDot + r"\bclang-interpreter\b" + NoPostHyphenDot,
                 # FIXME: Some clang test uses opt?
-                NoPreHyphenDot + r"\bopt\b" + NoPostHyphenDot,
+                NoPreHyphenDot + r"\bopt\b" + NoPostBar + NoPostHyphenDot,
                 # Handle these specially as they are strings searched
                 # for during testing.
                 r"\| \bcount\b",
@@ -403,12 +404,16 @@
 if not re.match(r'.*-win32$', config.target_triple):
     config.available_features.add('non-ms-sdk')
 
+# Not set on native PS4 environment.
+if not re.match(r'.*-scei-ps4', config.target_triple):
+    config.available_features.add('non-ps4-sdk')
+
 # [PR8833] LLP64-incompatible tests
-if not re.match(r'^x86_64.*-(win32|mingw32)$', config.target_triple):
+if not re.match(r'^x86_64.*-(win32|mingw32|windows-gnu)$', config.target_triple):
     config.available_features.add('LP64')
 
 # [PR12920] "clang-driver" -- set if gcc driver is not used.
-if not re.match(r'.*-(cygwin|mingw32)$', config.target_triple):
+if not re.match(r'.*-(cygwin|mingw32|windows-gnu)$', config.target_triple):
     config.available_features.add('clang-driver')
 
 # [PR18856] Depends to remove opened file. On win32, a file could be removed
@@ -459,6 +464,9 @@
 else:
     config.available_features.add("not_ubsan")
 
+if config.enable_backtrace == "1":
+    config.available_features.add("backtrace")
+
 # Check if we should run long running tests.
 if lit_config.params.get("run_long_tests", None) == "true":
     config.available_features.add("long_tests")
diff --git a/test/lit.site.cfg.in b/test/lit.site.cfg.in
index 1f0b960..332bcec 100644
--- a/test/lit.site.cfg.in
+++ b/test/lit.site.cfg.in
@@ -18,6 +18,7 @@
 config.clang_staticanalyzer = @ENABLE_CLANG_STATIC_ANALYZER@
 config.clang_examples = @ENABLE_CLANG_EXAMPLES@
 config.enable_shared = @ENABLE_SHARED@
+config.enable_backtrace = "@ENABLE_BACKTRACES@"
 config.host_arch = "@HOST_ARCH@"
 
 # Support substitution of the tools and libs dirs with user parameters. This is
diff --git a/tools/clang-check/ClangCheck.cpp b/tools/clang-check/ClangCheck.cpp
index d92a8d5..7992026 100644
--- a/tools/clang-check/ClangCheck.cpp
+++ b/tools/clang-check/ClangCheck.cpp
@@ -25,10 +25,10 @@
 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Option/OptTable.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Signals.h"
-#include "llvm/ADT/STLExtras.h"
 
 using namespace clang::driver;
 using namespace clang::tooling;
@@ -155,12 +155,12 @@
 
   // Clear adjusters because -fsyntax-only is inserted by the default chain.
   Tool.clearArgumentsAdjusters();
-  Tool.appendArgumentsAdjuster(new ClangStripOutputAdjuster());
+  Tool.appendArgumentsAdjuster(getClangStripOutputAdjuster());
 
   // Running the analyzer requires --analyze. Other modes can work with the
   // -fsyntax-only option.
-  Tool.appendArgumentsAdjuster(new InsertArgumentAdjuster(
-      Analyze ? "--analyze" : "-fsyntax-only", InsertArgumentAdjuster::BEGIN));
+  Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(
+      Analyze ? "--analyze" : "-fsyntax-only", ArgumentInsertPosition::BEGIN));
 
   ClangCheckActionFactory CheckFactory;
   std::unique_ptr<FrontendActionFactory> FrontendFactory;
diff --git a/tools/clang-format/CMakeLists.txt b/tools/clang-format/CMakeLists.txt
index 6a24e13..6ef0c22 100644
--- a/tools/clang-format/CMakeLists.txt
+++ b/tools/clang-format/CMakeLists.txt
@@ -4,13 +4,21 @@
   ClangFormat.cpp
   )
 
-target_link_libraries(clang-format
+set(CLANG_FORMAT_LIB_DEPS
   clangBasic
   clangFormat
   clangRewrite
   clangToolingCore
   )
 
+target_link_libraries(clang-format
+  ${CLANG_FORMAT_LIB_DEPS}
+  )
+
+if( LLVM_USE_SANITIZE_COVERAGE )
+  add_subdirectory(fuzzer)
+endif()
+
 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)
diff --git a/tools/clang-format/ClangFormat.cpp b/tools/clang-format/ClangFormat.cpp
index cacc51f..f611f70 100644
--- a/tools/clang-format/ClangFormat.cpp
+++ b/tools/clang-format/ClangFormat.cpp
@@ -229,6 +229,10 @@
   if (OutputXML) {
     llvm::outs()
         << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
+    if (Cursor.getNumOccurrences() != 0)
+      llvm::outs() << "<cursor>"
+                   << tooling::shiftedCodePosition(Replaces, Cursor)
+                   << "</cursor>\n";
     for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                                E = Replaces.end();
          I != E; ++I) {
@@ -266,15 +270,7 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal();
 
-  // Hide unrelated options.
-  StringMap<cl::Option*> Options;
-  cl::getRegisteredOptions(Options);
-  for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
-       I != E; ++I) {
-    if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
-        I->first() != "version")
-      I->second->setHiddenFlag(cl::ReallyHidden);
-  }
+  cl::HideUnrelatedOptions(ClangFormatCategory);
 
   cl::SetVersionPrinter(PrintVersion);
   cl::ParseCommandLineOptions(
diff --git a/tools/clang-format/clang-format-diff.py b/tools/clang-format/clang-format-diff.py
index 247dace..23adb07 100755
--- a/tools/clang-format/clang-format-diff.py
+++ b/tools/clang-format/clang-format-diff.py
@@ -49,7 +49,7 @@
                       '(case sensitive, overrides -iregex)')
   parser.add_argument('-iregex', metavar='PATTERN', default=
                       r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|proto'
-                      r'|protodevel)',
+                      r'|protodevel|java)',
                       help='custom pattern selecting file paths to reformat '
                       '(case insensitive, overridden by -regex)')
   parser.add_argument('-v', '--verbose', action='store_true',
diff --git a/tools/clang-format/clang-format.el b/tools/clang-format/clang-format.el
index 4f6ff3b..add2436 100644
--- a/tools/clang-format/clang-format.el
+++ b/tools/clang-format/clang-format.el
@@ -1,58 +1,172 @@
-;;; Clang-format emacs integration for use with C/Objective-C/C++.
+;;; clang-format.el --- Format code using clang-format
 
-;; This defines a function clang-format-region that you can bind to a key.
-;; A minimal .emacs would contain:
+;; Keywords: tools, c
+;; Package-Requires: ((cl-lib "0.3"))
+
+;;; Commentary:
+
+;; This package allows to filter code through clang-format to fix its formatting.
+;; clang-format is a tool that formats C/C++/Obj-C code according to a set of
+;; style options, see <http://clang.llvm.org/docs/ClangFormatStyleOptions.html>.
+;; Note that clang-format 3.4 or newer is required.
+
+;; clang-format.el is available via MELPA and can be installed via
 ;;
-;;   (load "<path-to-clang>/tools/clang-format/clang-format.el")
+;;   M-x package-install clang-format
+;;
+;; when ("melpa" . "http://melpa.org/packages/") is included in
+;; `package-archives'. Alternatively, ensure the directory of this
+;; file is in your `load-path' and add
+;;
+;;   (require 'clang-format)
+;;
+;; to your .emacs configuration.
+
+;; You may also want to bind `clang-format-region' to a key:
+;;
 ;;   (global-set-key [C-M-tab] 'clang-format-region)
-;;
-;; Depending on your configuration and coding style, you might need to modify
-;; 'style' in clang-format, below.
 
-(require 'json)
+;;; Code:
 
-;; *Location of the clang-format binary. If it is on your PATH, a full path name
-;; need not be specified.
-(defvar clang-format-binary "clang-format")
+(require 'cl-lib)
+(require 'xml)
 
-(defun clang-format-region ()
-  "Use clang-format to format the currently active region."
-  (interactive)
-  (let ((beg (if mark-active
-                 (region-beginning)
-               (min (line-beginning-position) (1- (point-max)))))
-        (end (if mark-active
-                 (region-end)
-               (line-end-position))))
-    (clang-format beg end)))
+(defgroup clang-format nil
+  "Format code using clang-format."
+  :group 'tools)
 
-(defun clang-format-buffer ()
-  "Use clang-format to format the current buffer."
-  (interactive)
-  (clang-format (point-min) (point-max)))
+(defcustom clang-format-executable
+  (or (executable-find "clang-format")
+      "clang-format")
+  "Location of the clang-format executable.
 
-(defun clang-format (begin end)
-  "Use clang-format to format the code between BEGIN and END."
-  (let* ((orig-windows (get-buffer-window-list (current-buffer)))
-         (orig-window-starts (mapcar #'window-start orig-windows))
-         (orig-point (point))
-         (style "file"))
+A string containing the name or the full path of the executable."
+  :group 'clang-format
+  :type 'string
+  :risky t)
+
+(defcustom clang-format-style "file"
+  "Style argument to pass to clang-format.
+
+By default clang-format will load the style configuration from
+a file named .clang-format located in one of the parent directories
+of the buffer."
+  :group 'clang-format
+  :type 'string
+  :safe #'stringp)
+(make-variable-buffer-local 'clang-format-style)
+
+(defun clang-format--extract (xml-node)
+  "Extract replacements and cursor information from XML-NODE."
+  (unless (and (listp xml-node) (eq (xml-node-name xml-node) 'replacements))
+    (error "Expected <replacements> node"))
+  (let ((nodes (xml-node-children xml-node))
+        replacements
+        cursor)
+    (dolist (node nodes)
+      (when (listp node)
+        (let* ((children (xml-node-children node))
+               (text (car children)))
+          (cl-case (xml-node-name node)
+            ('replacement
+             (let* ((offset (xml-get-attribute-or-nil node 'offset))
+                    (length (xml-get-attribute-or-nil node 'length)))
+               (when (or (null offset) (null length))
+                 (error "<replacement> node does not have offset and length attributes"))
+               (when (cdr children)
+                 (error "More than one child node in <replacement> node"))
+
+               (setq offset (string-to-number offset))
+               (setq length (string-to-number length))
+               (push (list offset length text) replacements)))
+            ('cursor
+             (setq cursor (string-to-number text)))))))
+
+    ;; Sort by decreasing offset, length.
+    (setq replacements (sort (delq nil replacements)
+                             (lambda (a b)
+                               (or (> (car a) (car b))
+                                   (and (= (car a) (car b))
+                                        (> (cadr a) (cadr b)))))))
+
+    (cons replacements cursor)))
+
+(defun clang-format--replace (offset length &optional text)
+  (let ((start (byte-to-position (1+ offset)))
+        (end (byte-to-position (+ 1 offset length))))
+    (goto-char start)
+    (delete-region start end)
+    (when text
+      (insert text))))
+
+;;;###autoload
+(defun clang-format-region (char-start char-end &optional style)
+  "Use clang-format to format the code between START and END according to STYLE.
+If called interactively uses the region or the current statement if there
+is no active region.  If no style is given uses `clang-format-style'."
+  (interactive
+   (if (use-region-p)
+       (list (region-beginning) (region-end))
+     (list (point) (point))))
+
+  (unless style
+    (setq style clang-format-style))
+
+  (let ((start (1- (position-bytes char-start)))
+        (end (1- (position-bytes char-end)))
+        (cursor (1- (position-bytes (point))))
+        (temp-buffer (generate-new-buffer " *clang-format-temp*"))
+        (temp-file (make-temp-file "clang-format")))
     (unwind-protect
-        (call-process-region (point-min) (point-max) clang-format-binary
-                             t (list t nil) nil
-                             "-offset" (number-to-string (1- begin))
-                             "-length" (number-to-string (- end begin))
-                             "-cursor" (number-to-string (1- (point)))
-                             "-assume-filename" (buffer-file-name)
-                             "-style" style)
-      (goto-char (point-min))
-      (let ((json-output (json-read-from-string
-                           (buffer-substring-no-properties
-                             (point-min) (line-beginning-position 2)))))
-        (delete-region (point-min) (line-beginning-position 2))
-        (goto-char (1+ (cdr (assoc 'Cursor json-output))))
-        (dotimes (index (length orig-windows))
-          (set-window-start (nth index orig-windows)
-                            (nth index orig-window-starts)))))))
+        (let (status stderr operations)
+          (setq status
+                (call-process-region
+                 (point-min) (point-max) clang-format-executable
+                 nil `(,temp-buffer ,temp-file) nil
+
+                 "-output-replacements-xml"
+                 "-assume-filename" (or (buffer-file-name) "")
+                 "-style" style
+                 "-offset" (number-to-string start)
+                 "-length" (number-to-string (- end start))
+                 "-cursor" (number-to-string cursor)))
+          (setq stderr
+                (with-temp-buffer
+                  (insert-file-contents temp-file)
+                  (when (> (point-max) (point-min))
+                    (insert ": "))
+                  (buffer-substring-no-properties
+                   (point-min) (line-end-position))))
+
+          (cond
+           ((stringp status)
+            (error "(clang-format killed by signal %s%s)" status stderr))
+           ((not (equal 0 status))
+            (error "(clang-format failed with code %d%s)" status stderr))
+           (t (message "(clang-format succeeded%s)" stderr)))
+
+          (with-current-buffer temp-buffer
+            (setq operations (clang-format--extract (car (xml-parse-region)))))
+
+          (let ((replacements (car operations))
+                (cursor (cdr operations)))
+            (save-excursion
+              (mapc (lambda (rpl)
+                      (apply #'clang-format--replace rpl))
+                    replacements))
+            (when cursor
+              (goto-char (byte-to-position (1+ cursor))))))
+      (delete-file temp-file)
+      (when (buffer-name temp-buffer) (kill-buffer temp-buffer)))))
+
+;;;###autoload
+(defun clang-format-buffer (&optional style)
+  "Use clang-format to format the current buffer according to STYLE."
+  (interactive)
+  (clang-format-region (point-min) (point-max) style))
+
+;;;###autoload
+(defalias 'clang-format 'clang-format-region)
 
 (provide 'clang-format)
+;;; clang-format.el ends here
diff --git a/tools/clang-format/fuzzer/CMakeLists.txt b/tools/clang-format/fuzzer/CMakeLists.txt
new file mode 100644
index 0000000..c7772fc
--- /dev/null
+++ b/tools/clang-format/fuzzer/CMakeLists.txt
@@ -0,0 +1,11 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_executable(clang-format-fuzzer
+  EXCLUDE_FROM_ALL
+  ClangFormatFuzzer.cpp
+  )
+
+target_link_libraries(clang-format-fuzzer
+  ${CLANG_FORMAT_LIB_DEPS}
+  LLVMFuzzer
+  )
diff --git a/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp b/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
new file mode 100644
index 0000000..fff4283
--- /dev/null
+++ b/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
@@ -0,0 +1,25 @@
+//===-- ClangFormatFuzzer.cpp - Fuzz the Clang format tool ----------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file implements a function that runs Clang format on a single
+///  input. This function is then linked into the Fuzzer library.
+///
+//===----------------------------------------------------------------------===//
+
+#include "clang/Format/Format.h"
+
+extern "C" void TestOneInput(uint8_t *data, size_t size) {
+  // FIXME: fuzz more things: different styles, different style features.
+  std::string s((const char *)data, size);
+  auto Style = getGoogleStyle(clang::format::FormatStyle::LK_Cpp);
+  Style.ColumnLimit = 60;
+  applyAllReplacements(s, clang::format::reformat(
+                              Style, s, {clang::tooling::Range(0, s.size())}));
+}
diff --git a/tools/driver/driver.cpp b/tools/driver/driver.cpp
index e93fa80..e1f9367 100644
--- a/tools/driver/driver.cpp
+++ b/tools/driver/driver.cpp
@@ -18,8 +18,8 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
-#include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
+#include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Frontend/Utils.h"
diff --git a/tools/libclang/CIndex.cpp b/tools/libclang/CIndex.cpp
index 00ef8c0..6c603af 100644
--- a/tools/libclang/CIndex.cpp
+++ b/tools/libclang/CIndex.cpp
@@ -240,9 +240,8 @@
       FID = FileID();
   }
 
-  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
-    Entities = PPRec.getPreprocessedEntitiesInRange(R);
-  return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
+  const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
+  return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
                                            PPRec, FID);
 }
 
@@ -4208,6 +4207,8 @@
     return cxstring::createRef("OMPTargetDirective");
   case CXCursor_OMPTeamsDirective:
     return cxstring::createRef("OMPTeamsDirective");
+  case CXCursor_OverloadCandidate:
+      return cxstring::createRef("OverloadCandidate");
   }
 
   llvm_unreachable("Unhandled CXCursorKind");
@@ -6943,7 +6944,7 @@
 
   CXTUResourceUsage usage = { (void*) entries.get(),
                             (unsigned) entries->size(),
-                            entries->size() ? &(*entries)[0] : nullptr };
+                            !entries->empty() ? &(*entries)[0] : nullptr };
   entries.release();
   return usage;
 }
diff --git a/tools/libclang/CIndexCodeCompletion.cpp b/tools/libclang/CIndexCodeCompletion.cpp
index b6f71d2..47f2c14 100644
--- a/tools/libclang/CIndexCodeCompletion.cpp
+++ b/tools/libclang/CIndexCodeCompletion.cpp
@@ -619,10 +619,11 @@
       for (unsigned I = 0; I != NumCandidates; ++I) {
         CodeCompletionString *StoredCompletion
           = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
-                                                getCodeCompletionTUInfo());
+                                                getCodeCompletionTUInfo(),
+                                                includeBriefComments());
         
         CXCompletionResult R;
-        R.CursorKind = CXCursor_NotImplemented;
+        R.CursorKind = CXCursor_OverloadCandidate;
         R.CompletionString = StoredCompletion;
         StoredResults.push_back(R);
       }
diff --git a/tools/libclang/CIndexUSRs.cpp b/tools/libclang/CIndexUSRs.cpp
index 25881c3..d7b6585 100644
--- a/tools/libclang/CIndexUSRs.cpp
+++ b/tools/libclang/CIndexUSRs.cpp
@@ -15,9 +15,9 @@
 #include "CXCursor.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
+#include "clang/Frontend/ASTUnit.h"
 #include "clang/Index/USRGeneration.h"
 #include "clang/Lex/PreprocessingRecord.h"
-#include "clang/Frontend/ASTUnit.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
 
diff --git a/tools/libclang/CMakeLists.txt b/tools/libclang/CMakeLists.txt
index f1c3f4c..26f88a9 100644
--- a/tools/libclang/CMakeLists.txt
+++ b/tools/libclang/CMakeLists.txt
@@ -51,6 +51,11 @@
   list(APPEND LIBS clangARCMigrate)
 endif ()
 
+find_library(DL_LIBRARY_PATH dl)
+if (DL_LIBRARY_PATH)
+  list(APPEND LIBS dl)
+endif()
+
 option(LIBCLANG_BUILD_STATIC
   "Build libclang as a static library (in addition to a shared one)" OFF)
 
diff --git a/tools/libclang/CXComment.cpp b/tools/libclang/CXComment.cpp
index 4547031..9cc05ed 100644
--- a/tools/libclang/CXComment.cpp
+++ b/tools/libclang/CXComment.cpp
@@ -12,10 +12,10 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang-c/Index.h"
-#include "clang-c/Documentation.h"
 #include "CXComment.h"
 #include "CXCursor.h"
 #include "CXString.h"
+#include "clang-c/Documentation.h"
 #include "clang/AST/Decl.h"
 #include "clang/Index/CommentToXML.h"
 #include "llvm/ADT/StringExtras.h"
diff --git a/tools/libclang/CXComment.h b/tools/libclang/CXComment.h
index 0c54182..a937a80 100644
--- a/tools/libclang/CXComment.h
+++ b/tools/libclang/CXComment.h
@@ -15,8 +15,8 @@
 #define LLVM_CLANG_TOOLS_LIBCLANG_CXCOMMENT_H
 
 #include "CXTranslationUnit.h"
-#include "clang-c/Index.h"
 #include "clang-c/Documentation.h"
+#include "clang-c/Index.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Comment.h"
 #include "clang/Frontend/ASTUnit.h"
diff --git a/tools/libclang/CXLoadedDiagnostic.cpp b/tools/libclang/CXLoadedDiagnostic.cpp
index c923b26..fe5599a 100644
--- a/tools/libclang/CXLoadedDiagnostic.cpp
+++ b/tools/libclang/CXLoadedDiagnostic.cpp
@@ -16,8 +16,8 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Frontend/SerializedDiagnostics.h"
 #include "clang/Frontend/SerializedDiagnosticReader.h"
+#include "clang/Frontend/SerializedDiagnostics.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Twine.h"
diff --git a/tools/libclang/CXString.h b/tools/libclang/CXString.h
index f6b46f7..72ac0cf 100644
--- a/tools/libclang/CXString.h
+++ b/tools/libclang/CXString.h
@@ -63,7 +63,7 @@
 // In this case, call \c createRef(String.c_str()).
 //
 // If you need to make a copy, call \c createDup(StringRef(String)).
-CXString createRef(std::string String) LLVM_DELETED_FUNCTION;
+CXString createRef(std::string String) = delete;
 
 /// \brief Create a CXString object that is backed by a string buffer.
 CXString createCXString(CXStringBuf *buf);
diff --git a/tools/libclang/CXType.cpp b/tools/libclang/CXType.cpp
index 81cff5a..942dad2 100644
--- a/tools/libclang/CXType.cpp
+++ b/tools/libclang/CXType.cpp
@@ -525,8 +525,10 @@
       TCALLINGCONV(X86_64SysV);
       TCALLINGCONV(AAPCS);
       TCALLINGCONV(AAPCS_VFP);
-      TCALLINGCONV(PnaclCall);
       TCALLINGCONV(IntelOclBicc);
+    case CC_SpirFunction: return CXCallingConv_Unexposed;
+    case CC_SpirKernel: return CXCallingConv_Unexposed;
+      break;
     }
 #undef TCALLINGCONV
   }
@@ -802,7 +804,7 @@
   ASTContext &Ctx = cxtu::getASTUnit(GetTU(PT))->getASTContext();
   IdentifierInfo *II = &Ctx.Idents.get(S);
   DeclarationName FieldName(II);
-  RecordDecl::lookup_const_result Res = RD->lookup(FieldName);
+  RecordDecl::lookup_result Res = RD->lookup(FieldName);
   // If a field of the parent record is incomplete, lookup will fail.
   // and we would return InvalidFieldName instead of Incomplete.
   // But this erroneous results does protects again a hidden assertion failure
diff --git a/tools/libclang/Indexing.cpp b/tools/libclang/Indexing.cpp
index 20f4474..20df33e 100644
--- a/tools/libclang/Indexing.cpp
+++ b/tools/libclang/Indexing.cpp
@@ -697,13 +697,8 @@
 
   // FIXME: Only deserialize inclusion directives.
 
-  PreprocessingRecord::iterator I, E;
-  std::tie(I, E) = Unit.getLocalPreprocessingEntities();
-
   bool isModuleFile = Unit.isModuleFile();
-  for (; I != E; ++I) {
-    PreprocessedEntity *PPE = *I;
-
+  for (PreprocessedEntity *PPE : Unit.getLocalPreprocessingEntities()) {
     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
       SourceLocation Loc = ID->getSourceRange().getBegin();
       // Modules have synthetic main files as input, give an invalid location
diff --git a/tools/libclang/IndexingContext.h b/tools/libclang/IndexingContext.h
index 31fddfb..4da6aeb 100644
--- a/tools/libclang/IndexingContext.h
+++ b/tools/libclang/IndexingContext.h
@@ -245,8 +245,8 @@
   SmallVector<CXIdxAttrInfo *, 2> CXAttrs;
   unsigned ref_cnt;
 
-  AttrListInfo(const AttrListInfo &) LLVM_DELETED_FUNCTION;
-  void operator=(const AttrListInfo &) LLVM_DELETED_FUNCTION;
+  AttrListInfo(const AttrListInfo &) = delete;
+  void operator=(const AttrListInfo &) = delete;
 public:
   AttrListInfo(const Decl *D, IndexingContext &IdxCtx);
 
diff --git a/tools/scan-build/ccc-analyzer b/tools/scan-build/ccc-analyzer
index 4c8f648..aa02653 100755
--- a/tools/scan-build/ccc-analyzer
+++ b/tools/scan-build/ccc-analyzer
@@ -42,9 +42,17 @@
 my $DefaultCXXCompiler;
 my $IsCXX;
 
+# If on OSX, use xcrun to determine the SDK root.
+my $UseXCRUN = 0;
+
 if (`uname -a` =~ m/Darwin/) {
   $DefaultCCompiler = 'clang';
   $DefaultCXXCompiler = 'clang++';
+  # Older versions of OSX do not have xcrun to
+  # query the SDK location.
+  if (-x "/usr/bin/xcrun") {
+    $UseXCRUN = 1;
+  }
 } else {
   $DefaultCCompiler = 'gcc';
   $DefaultCXXCompiler = 'g++';
@@ -345,7 +353,6 @@
   '-imacros' => 1,
   '-iprefix' => 1,
   '-iquote' => 1,
-  '-isystem' => 1,
   '-iwithprefix' => 1,
   '-iwithprefixbefore' => 1
 );
@@ -478,6 +485,7 @@
 my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
 my %ArchsSeen;
 my $HadArch = 0;
+my $HasSDK = 0;
 
 # Process the arguments.
 foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
@@ -500,6 +508,12 @@
     next;
   }
 
+  # On OSX/iOS, record if an SDK path was specified.  This
+  # is innocuous for other platforms, so the check just happens.
+  if ($Arg =~ /^-isysroot/) {
+    $HasSDK = 1;
+  }
+
   # Options with possible arguments that should pass through to compiler.
   if (defined $CompileOptionMap{$ArgKey}) {
     my $Cnt = $CompileOptionMap{$ArgKey};
@@ -557,7 +571,7 @@
   }
 
   # Compile mode flags.
-  if ($Arg =~ /^-[D,I,U](.*)$/) {
+  if ($Arg =~ /^-[D,I,U,isystem](.*)$/) {
     my $Tmp = $Arg;
     if ($1 eq '') {
       # FIXME: Check if we are going off the end.
@@ -644,6 +658,15 @@
   }
 }
 
+# If we are on OSX and have an installation where the
+# default SDK is inferred by xcrun use xcrun to infer
+# the SDK.
+if (not $HasSDK and $UseXCRUN) {
+  my $sdk = `/usr/bin/xcrun --show-sdk-path -sdk macosx`;
+  chomp $sdk;
+  push @CompileOpts, "-isysroot", $sdk;
+}
+
 if ($Action eq 'compile' or $Action eq 'link') {
   my @Archs = keys %ArchsSeen;
   # Skip the file if we don't support the architectures specified.
diff --git a/tools/scan-build/scan-build b/tools/scan-build/scan-build
index 6f86a4d..d52d8f5 100755
--- a/tools/scan-build/scan-build
+++ b/tools/scan-build/scan-build
@@ -1221,104 +1221,104 @@
  -load-plugin [plugin library]
 ENDTEXT
 
-# Query clang for list of checkers that are enabled.
+  # Query clang for list of checkers that are enabled.
 
-# create a list to load the plugins via the 'Xclang' command line
-# argument
-my @PluginLoadCommandline_xclang;
-foreach my $param ( @PluginsToLoad ) {
-  push ( @PluginLoadCommandline_xclang, "-Xclang" );
-  push ( @PluginLoadCommandline_xclang, $param );
-}
-my %EnabledCheckers;
-foreach my $lang ("c", "objective-c", "objective-c++", "c++") {
-  pipe(FROM_CHILD, TO_PARENT);
-  my $pid = fork();
-  if ($pid == 0) {
-    close FROM_CHILD;
-    open(STDOUT,">&", \*TO_PARENT);
-    open(STDERR,">&", \*TO_PARENT);
-    exec $Clang, ( @PluginLoadCommandline_xclang, '--analyze', '-x', $lang, '-', '-###');
+  # create a list to load the plugins via the 'Xclang' command line
+  # argument
+  my @PluginLoadCommandline_xclang;
+  foreach my $param ( @PluginsToLoad ) {
+    push ( @PluginLoadCommandline_xclang, "-Xclang" );
+    push ( @PluginLoadCommandline_xclang, $param );
   }
-  close(TO_PARENT);
-  while(<FROM_CHILD>) {
-    foreach my $val (split /\s+/) {
-      $val =~ s/\"//g;
-      if ($val =~ /-analyzer-checker\=([^\s]+)/) {
-        $EnabledCheckers{$1} = 1;
-      }
+  my %EnabledCheckers;
+  foreach my $lang ("c", "objective-c", "objective-c++", "c++") {
+    pipe(FROM_CHILD, TO_PARENT);
+    my $pid = fork();
+    if ($pid == 0) {
+      close FROM_CHILD;
+      open(STDOUT,">&", \*TO_PARENT);
+      open(STDERR,">&", \*TO_PARENT);
+      exec $Clang, ( @PluginLoadCommandline_xclang, '--analyze', '-x', $lang, '-', '-###');
     }
-  }
-  waitpid($pid,0);
-  close(FROM_CHILD);
-}
-
-# Query clang for complete list of checkers.
-if (defined $Clang && -x $Clang) {
-  pipe(FROM_CHILD, TO_PARENT);
-  my $pid = fork();
-  if ($pid == 0) {
-    close FROM_CHILD;
-    open(STDOUT,">&", \*TO_PARENT);
-    open(STDERR,">&", \*TO_PARENT);
-    exec $Clang, ('-cc1', @PluginsToLoad , '-analyzer-checker-help');
-  }
-  close(TO_PARENT);
-  my $foundCheckers = 0;
-  while(<FROM_CHILD>) {
-    if (/CHECKERS:/) {
-      $foundCheckers = 1;
-      last;
-    }
-  }
-  if (!$foundCheckers) {
-    print "  *** Could not query Clang for the list of available checkers.";
-  }
-  else {
-    print("\nAVAILABLE CHECKERS:\n\n");
-    my $skip = 0;
+    close(TO_PARENT);
     while(<FROM_CHILD>) {
-      if (/experimental/) {
-        $skip = 1;
-        next;
-      }
-      if ($skip) {
-        next if (!/^\s\s[^\s]/);
-        $skip = 0;
-      }
-      s/^\s\s//;
-      if (/^([^\s]+)/) {
-        # Is the checker enabled?
-        my $checker = $1;
-        my $enabled = 0;
-        my $aggregate = "";
-        foreach my $domain (split /\./, $checker) {
-          $aggregate .= $domain;
-          if ($EnabledCheckers{$aggregate}) {
-            $enabled =1;
-            last;
-          }
-          # append a dot, if an additional domain is added in the next iteration
-          $aggregate .= ".";
+      foreach my $val (split /\s+/) {
+        $val =~ s/\"//g;
+        if ($val =~ /-analyzer-checker\=([^\s]+)/) {
+          $EnabledCheckers{$1} = 1;
         }
+      }
+    }
+    waitpid($pid,0);
+    close(FROM_CHILD);
+  }
 
-        if ($enabled) {
-          print " + ";
+  # Query clang for complete list of checkers.
+  if (defined $Clang && -x $Clang) {
+    pipe(FROM_CHILD, TO_PARENT);
+    my $pid = fork();
+    if ($pid == 0) {
+      close FROM_CHILD;
+      open(STDOUT,">&", \*TO_PARENT);
+      open(STDERR,">&", \*TO_PARENT);
+      exec $Clang, ('-cc1', @PluginsToLoad , '-analyzer-checker-help');
+    }
+    close(TO_PARENT);
+    my $foundCheckers = 0;
+    while(<FROM_CHILD>) {
+      if (/CHECKERS:/) {
+        $foundCheckers = 1;
+        last;
+      }
+    }
+    if (!$foundCheckers) {
+      print "  *** Could not query Clang for the list of available checkers.";
+    }
+    else {
+      print("\nAVAILABLE CHECKERS:\n\n");
+      my $skip = 0;
+      while(<FROM_CHILD>) {
+        if (/experimental/) {
+          $skip = 1;
+          next;
+        }
+        if ($skip) {
+          next if (!/^\s\s[^\s]/);
+          $skip = 0;
+        }
+        s/^\s\s//;
+        if (/^([^\s]+)/) {
+          # Is the checker enabled?
+          my $checker = $1;
+          my $enabled = 0;
+          my $aggregate = "";
+          foreach my $domain (split /\./, $checker) {
+            $aggregate .= $domain;
+            if ($EnabledCheckers{$aggregate}) {
+              $enabled =1;
+              last;
+            }
+            # append a dot, if an additional domain is added in the next iteration
+            $aggregate .= ".";
+          }
+
+          if ($enabled) {
+            print " + ";
+          }
+          else {
+            print "   ";
+          }
         }
         else {
           print "   ";
         }
+        print $_;
       }
-      else {
-        print "   ";
-      }
-      print $_;
+      print "\nNOTE: \"+\" indicates that an analysis is enabled by default.\n"
     }
-    print "\nNOTE: \"+\" indicates that an analysis is enabled by default.\n"
+    waitpid($pid,0);
+    close(FROM_CHILD);
   }
-  waitpid($pid,0);
-  close(FROM_CHILD);
-}
 
 print <<ENDTEXT
 
@@ -1533,6 +1533,7 @@
   }
 
   if ($arg eq "-no-failure-reports") {
+    shift @ARGV;
     $ENV{"CCC_REPORT_FAILURES"} = 0;
     next;
   }
diff --git a/unittests/AST/ASTVectorTest.cpp b/unittests/AST/ASTVectorTest.cpp
index 4b5d569..55c06d0 100644
--- a/unittests/AST/ASTVectorTest.cpp
+++ b/unittests/AST/ASTVectorTest.cpp
@@ -15,7 +15,6 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTVector.h"
 #include "clang/Basic/Builtins.h"
-
 #include "gtest/gtest.h"
 
 using namespace clang;
diff --git a/unittests/AST/EvaluateAsRValueTest.cpp b/unittests/AST/EvaluateAsRValueTest.cpp
index b5f9b32..820edbc 100644
--- a/unittests/AST/EvaluateAsRValueTest.cpp
+++ b/unittests/AST/EvaluateAsRValueTest.cpp
@@ -12,16 +12,14 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include <map>
-#include <string>
-
+#include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Tooling/Tooling.h"
 #include "gtest/gtest.h"
-
-#include "clang/AST/ASTConsumer.h"
+#include <map>
+#include <string>
 
 using namespace clang::tooling;
 
diff --git a/unittests/ASTMatchers/ASTMatchersTest.cpp b/unittests/ASTMatchers/ASTMatchersTest.cpp
index c88a197..0d27b5d 100644
--- a/unittests/ASTMatchers/ASTMatchersTest.cpp
+++ b/unittests/ASTMatchers/ASTMatchersTest.cpp
@@ -379,6 +379,21 @@
   EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
 }
 
+TEST(DeclarationMatcher, translationUnitDecl) {
+  const std::string Code = "int MyVar1;\n"
+                           "namespace NameSpace {\n"
+                           "int MyVar2;\n"
+                           "}  // namespace NameSpace\n";
+  EXPECT_TRUE(matches(
+      Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
+  EXPECT_FALSE(matches(
+      Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
+  EXPECT_TRUE(matches(
+      Code,
+      varDecl(hasName("MyVar2"),
+              hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
+}
+
 TEST(DeclarationMatcher, LinkageSpecification) {
   EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
   EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
@@ -2104,8 +2119,16 @@
   EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
   EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
   EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
+  EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
+  EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
+  EXPECT_TRUE(
+      matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
 
   EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
+  EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
+  EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
+  EXPECT_TRUE(
+      notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
 }
 
 TEST(Matcher, NullPtrLiteral) {
@@ -3136,6 +3159,12 @@
                       initListExpr(hasType(asString("int [2]")))));
   EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
                       initListExpr(hasType(recordDecl(hasName("B"))))));
+  EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
+                      "void f();"
+                      "S s[1] = { &f };",
+                      declRefExpr(to(functionDecl(hasName("f"))))));
+  EXPECT_TRUE(
+      matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
 }
 
 TEST(UsingDeclaration, MatchesUsingDeclarations) {
@@ -3857,6 +3886,11 @@
   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
 }
 
+TEST(TypeMatching, MatchesVoid) {
+  EXPECT_TRUE(
+      matches("struct S { void func(); };", methodDecl(returns(voidType()))));
+}
+
 TEST(TypeMatching, MatchesArrayTypes) {
   EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
   EXPECT_TRUE(matches("int a[42];", arrayType()));
@@ -4625,5 +4659,58 @@
           .bind("data")));
 }
 
+TEST(TypeDefDeclMatcher, Match) {
+  EXPECT_TRUE(matches("typedef int typedefDeclTest;",
+                      typedefDecl(hasName("typedefDeclTest"))));
+}
+
+// FIXME: Figure out how to specify paths so the following tests pass on Windows.
+#ifndef LLVM_ON_WIN32
+
+TEST(Matcher, IsExpansionInMainFileMatcher) {
+  EXPECT_TRUE(matches("class X {};",
+                      recordDecl(hasName("X"), isExpansionInMainFile())));
+  EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
+  FileContentMappings M;
+  M.push_back(std::make_pair("/other", "class X {};"));
+  EXPECT_TRUE(matchesConditionally("#include <other>\n",
+                                   recordDecl(isExpansionInMainFile()), false,
+                                   "-isystem/", M));
+}
+
+TEST(Matcher, IsExpansionInSystemHeader) {
+  FileContentMappings M;
+  M.push_back(std::make_pair("/other", "class X {};"));
+  EXPECT_TRUE(matchesConditionally(
+      "#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
+      "-isystem/", M));
+  EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
+                                   recordDecl(isExpansionInSystemHeader()),
+                                   false, "-I/", M));
+  EXPECT_TRUE(notMatches("class X {};",
+                         recordDecl(isExpansionInSystemHeader())));
+  EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
+}
+
+TEST(Matcher, IsExpansionInFileMatching) {
+  FileContentMappings M;
+  M.push_back(std::make_pair("/foo", "class A {};"));
+  M.push_back(std::make_pair("/bar", "class B {};"));
+  EXPECT_TRUE(matchesConditionally(
+      "#include <foo>\n"
+      "#include <bar>\n"
+      "class X {};",
+      recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
+      "-isystem/", M));
+  EXPECT_TRUE(matchesConditionally(
+      "#include <foo>\n"
+      "#include <bar>\n"
+      "class X {};",
+      recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
+      "-isystem/", M));
+}
+
+#endif // LLVM_ON_WIN32
+
 } // end namespace ast_matchers
 } // end namespace clang
diff --git a/unittests/ASTMatchers/ASTMatchersTest.h b/unittests/ASTMatchers/ASTMatchersTest.h
index 2e5b3da..a2ab9fe 100644
--- a/unittests/ASTMatchers/ASTMatchersTest.h
+++ b/unittests/ASTMatchers/ASTMatchersTest.h
@@ -22,6 +22,7 @@
 using clang::tooling::newFrontendActionFactory;
 using clang::tooling::runToolOnCodeWithArgs;
 using clang::tooling::FrontendActionFactory;
+using clang::tooling::FileContentMappings;
 
 class BoundNodesCallback {
 public:
@@ -58,10 +59,10 @@
 };
 
 template <typename T>
-testing::AssertionResult matchesConditionally(const std::string &Code,
-                                              const T &AMatcher,
-                                              bool ExpectMatch,
-                                              llvm::StringRef CompileArg) {
+testing::AssertionResult matchesConditionally(
+    const std::string &Code, const T &AMatcher, bool ExpectMatch,
+    llvm::StringRef CompileArg,
+    const FileContentMappings &VirtualMappedFiles = FileContentMappings()) {
   bool Found = false, DynamicFound = false;
   MatchFinder Finder;
   VerifyMatch VerifyFound(nullptr, &Found);
@@ -73,7 +74,8 @@
       newFrontendActionFactory(&Finder));
   // Some tests use typeof, which is a gnu extension.
   std::vector<std::string> Args(1, CompileArg);
-  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args)) {
+  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, "input.cc",
+                             VirtualMappedFiles)) {
     return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
   }
   if (Found != DynamicFound) {
diff --git a/unittests/Basic/CMakeLists.txt b/unittests/Basic/CMakeLists.txt
index b8f69bf..3cb3cb8 100644
--- a/unittests/Basic/CMakeLists.txt
+++ b/unittests/Basic/CMakeLists.txt
@@ -4,6 +4,7 @@
 
 add_clang_unittest(BasicTests
   CharInfoTest.cpp
+  DiagnosticTest.cpp
   FileManagerTest.cpp
   SourceManagerTest.cpp
   VirtualFileSystemTest.cpp
diff --git a/unittests/Basic/DiagnosticTest.cpp b/unittests/Basic/DiagnosticTest.cpp
new file mode 100644
index 0000000..fa2b56e
--- /dev/null
+++ b/unittests/Basic/DiagnosticTest.cpp
@@ -0,0 +1,49 @@
+//===- unittests/Basic/DiagnosticTest.cpp -- Diagnostic engine tests ------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+// Check that DiagnosticErrorTrap works with SuppressAllDiagnostics.
+TEST(DiagnosticTest, suppressAndTrap) {
+  DiagnosticsEngine Diags(new DiagnosticIDs(),
+                          new DiagnosticOptions,
+                          new IgnoringDiagConsumer());
+  Diags.setSuppressAllDiagnostics(true);
+
+  {
+    DiagnosticErrorTrap trap(Diags);
+
+    // Diag that would set UncompilableErrorOccurred and ErrorOccurred.
+    Diags.Report(diag::err_target_unknown_triple) << "unknown";
+
+    // Diag that would set UnrecoverableErrorOccurred and ErrorOccurred.
+    Diags.Report(diag::err_cannot_open_file) << "file" << "error";
+
+    // Diag that would set FatalErrorOccurred
+    // (via non-note following a fatal error).
+    Diags.Report(diag::warn_mt_message) << "warning";
+
+    EXPECT_TRUE(trap.hasErrorOccurred());
+    EXPECT_TRUE(trap.hasUnrecoverableErrorOccurred());
+  }
+
+  EXPECT_FALSE(Diags.hasErrorOccurred());
+  EXPECT_FALSE(Diags.hasFatalErrorOccurred());
+  EXPECT_FALSE(Diags.hasUncompilableErrorOccurred());
+  EXPECT_FALSE(Diags.hasUnrecoverableErrorOccurred());
+}
+
+}
diff --git a/unittests/Basic/FileManagerTest.cpp b/unittests/Basic/FileManagerTest.cpp
index e53213b..dd8cf24 100644
--- a/unittests/Basic/FileManagerTest.cpp
+++ b/unittests/Basic/FileManagerTest.cpp
@@ -10,8 +10,8 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/FileSystemStatCache.h"
-#include "gtest/gtest.h"
 #include "llvm/Config/llvm-config.h"
+#include "gtest/gtest.h"
 
 using namespace llvm;
 using namespace clang;
diff --git a/unittests/CodeGen/BufferSourceTest.cpp b/unittests/CodeGen/BufferSourceTest.cpp
index f9d0991..b2a8ba5 100644
--- a/unittests/CodeGen/BufferSourceTest.cpp
+++ b/unittests/CodeGen/BufferSourceTest.cpp
@@ -10,16 +10,16 @@
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/CodeGen/ModuleBuilder.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/Preprocessor.h"
-#include "clang/CodeGen/ModuleBuilder.h"
-#include "clang/Sema/Sema.h"
 #include "clang/Parse/ParseAST.h"
-#include "clang/Basic/TargetInfo.h"
+#include "clang/Sema/Sema.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/IR/LLVMContext.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/MemoryBuffer.h"
-#include "llvm/IR/LLVMContext.h"
 #include "gtest/gtest.h"
 
 using namespace llvm;
@@ -63,7 +63,6 @@
             compiler.getDiagnostics(),
             "EmitCXXGlobalInitFuncTest",
             compiler.getCodeGenOpts(),
-            compiler.getTargetOpts(),
             llvm::getGlobalContext())));
 
     compiler.createSema(clang::TU_Prefix,NULL);
diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp
index a6bbe16..9738877 100644
--- a/unittests/Format/FormatTest.cpp
+++ b/unittests/Format/FormatTest.cpp
@@ -67,6 +67,12 @@
     verifyFormat(llvm::Twine("void f() { " + text + " }").str());
   }
 
+  /// \brief Verify that clang-format does not crash on the given input.
+  void verifyNoCrash(llvm::StringRef Code,
+                     const FormatStyle &Style = getLLVMStyle()) {
+    format(Code, Style);
+  }
+
   int ReplacementCount;
 };
 
@@ -487,6 +493,11 @@
                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
                "}");
+  verifyFormat("if (a) {\n"
+               "} else if (\n"
+               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
+               "}",
+               getLLVMStyleWithColumns(62));
 }
 
 TEST_F(FormatTest, FormatsForLoop) {
@@ -745,10 +756,21 @@
                "case 3:\n"
                "case 4:\n"
                "case 5: return;\n"
+               "case 6: // comment\n"
+               "  return;\n"
+               "case 7:\n"
+               "  // comment\n"
+               "  return;\n"
                "default: y = 1; break;\n"
                "}",
                Style);
   verifyFormat("switch (a) {\n"
+               "#if FOO\n"
+               "case 0: return 0;\n"
+               "#endif\n"
+               "}",
+               Style);
+  verifyFormat("switch (a) {\n"
                "case 1: {\n"
                "}\n"
                "case 2: {\n"
@@ -987,6 +1009,14 @@
                    " // first\n"
                    "// at start\n"
                    "otherLine();"));
+  EXPECT_EQ("void f() {\n"
+            "  lineWith(); // comment\n"
+            "  // at start\n"
+            "}",
+            format("void              f() {\n"
+                   "  lineWith(); // comment\n"
+                   "  // at start\n"
+                   "}"));
 
   verifyFormat(
       "#define A                                                  \\\n"
@@ -1010,6 +1040,9 @@
                    "     // spanning two lines\n"
                    " x + 3) {\n"
                    "}"));
+
+  verifyNoCrash("/\\\n/");
+  verifyNoCrash("/\\\n* */");
 }
 
 TEST_F(FormatTest, KeepsParameterWithTrailingCommentsOnTheirOwnLine) {
@@ -2058,6 +2091,21 @@
                      "  // Information about aThirdDecentlyLongValue.\n"
                      "  aThirdDecentlyLongValue\n"
                      "};");
+  verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
+                     "  a = 1,\n"
+                     "  b = 2,\n"
+                     "  c = 3,\n"
+                     "};");
+  verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
+                     "  a = 1,\n"
+                     "  b = 2,\n"
+                     "  c = 3,\n"
+                     "};");
+  verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
+                     "  a = 1,\n"
+                     "  b = 2,\n"
+                     "  c = 3,\n"
+                     "};");
 }
 
 TEST_F(FormatTest, FormatsBitfields) {
@@ -2157,11 +2205,11 @@
       "    : \"a\"(value));");
   EXPECT_EQ(
       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
-      "    __asm {\n"
+      "  __asm {\n"
       "        mov     edx,[that] // vtable in edx\n"
       "        mov     eax,methodIndex\n"
       "        call    [edx][eax*4] // stdcall\n"
-      "    }\n"
+      "  }\n"
       "}",
       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
              "    __asm {\n"
@@ -2170,6 +2218,10 @@
              "        call    [edx][eax*4] // stdcall\n"
              "    }\n"
              "}"));
+  verifyFormat("void function() {\n"
+               "  // comment\n"
+               "  asm(\"\");\n"
+               "}");
 }
 
 TEST_F(FormatTest, FormatTryCatch) {
@@ -2192,6 +2244,29 @@
                "    throw;\n"
                "  }\n"
                "};\n");
+
+  // Incomplete try-catch blocks.
+  verifyFormat("try {} catch (");
+}
+
+TEST_F(FormatTest, FormatSEHTryCatch) {
+  verifyFormat("__try {\n"
+               "  int a = b * c;\n"
+               "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
+               "  // Do nothing.\n"
+               "}");
+
+  verifyFormat("__try {\n"
+               "  int a = b * c;\n"
+               "} __finally {\n"
+               "  // Do nothing.\n"
+               "}");
+
+  verifyFormat("DEBUG({\n"
+               "  __try {\n"
+               "  } __finally {\n"
+               "  }\n"
+               "});\n");
 }
 
 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
@@ -2226,6 +2301,20 @@
                "  // something\n"
                "}",
                Style);
+  verifyFormat("__try {\n"
+               "  // something\n"
+               "}\n"
+               "__finally {\n"
+               "  // something\n"
+               "}",
+               Style);
+  verifyFormat("@try {\n"
+               "  // something\n"
+               "}\n"
+               "@finally {\n"
+               "  // something\n"
+               "}",
+               Style);
   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
   verifyFormat("try\n"
                "{\n"
@@ -2251,13 +2340,16 @@
 TEST_F(FormatTest, FormatObjCTryCatch) {
   verifyFormat("@try {\n"
                "  f();\n"
-               "}\n"
-               "@catch (NSException e) {\n"
+               "} @catch (NSException e) {\n"
                "  @throw;\n"
-               "}\n"
-               "@finally {\n"
+               "} @finally {\n"
                "  exit(42);\n"
                "}");
+  verifyFormat("DEBUG({\n"
+               "  @try {\n"
+               "  } @finally {\n"
+               "  }\n"
+               "});\n");
 }
 
 TEST_F(FormatTest, StaticInitializers) {
@@ -2418,6 +2510,10 @@
             "\\na : b);",
             format("const char * c = STRINGIFY(\n"
                    "\\na : b);"));
+
+  verifyFormat("a\r\\");
+  verifyFormat("a\v\\");
+  verifyFormat("a\f\\");
 }
 
 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
@@ -2558,6 +2654,13 @@
   verifyFormat("#pragma omp threadprivate( \\\n"
                "    y)), // expected-warning",
                getLLVMStyleWithColumns(28));
+  verifyFormat("#d, = };");
+  verifyFormat("#if \"a");
+
+  verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
+  verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
+  verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
+  verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
 }
 
 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
@@ -2598,6 +2701,9 @@
   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
             format("SOME_WEIRD_LOG_MACRO\n"
                    "<< SomeThing;"));
+
+  verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
+               "(n, buffers))\n", getChromiumStyle(FormatStyle::LK_Cpp));
 }
 
 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
@@ -2775,6 +2881,17 @@
   EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
 }
 
+TEST_F(FormatTest, DontCrashOnBlockComments) {
+  EXPECT_EQ(
+      "int xxxxxxxxx; /* "
+      "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n"
+      "zzzzzz\n"
+      "0*/",
+      format("int xxxxxxxxx;                          /* "
+             "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzz\n"
+             "0*/"));
+}
+
 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
   verifyFormat("#define A \\\n"
                "  int v(  \\\n"
@@ -2867,6 +2984,12 @@
                "#if a\n"
                "#else\n"
                "#endif");
+
+  verifyFormat("void f(\n"
+               "#if A\n"
+               "    );\n"
+               "#else\n"
+               "#endif");
 }
 
 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
@@ -2895,11 +3018,19 @@
             "});",
             format(" functionCall ( {int i;int j;} );"));
   EXPECT_EQ("functionCall({\n"
-            "               int i;\n"
-            "               int j;\n"
-            "             },\n"
-            "             aaaa, bbbb, cccc);",
+            "  int i;\n"
+            "  int j;\n"
+            "}, aaaa, bbbb, cccc);",
             format(" functionCall ( {int i;int j;},  aaaa,   bbbb, cccc);"));
+  EXPECT_EQ("functionCall(\n"
+            "    {\n"
+            "      int i;\n"
+            "      int j;\n"
+            "    },\n"
+            "    aaaa, bbbb, // comment\n"
+            "    cccc);",
+            format(" functionCall ( {int i;int j;},  aaaa,   bbbb, // comment\n"
+                   "cccc);"));
   EXPECT_EQ("functionCall(aaaa, bbbb, { int i; });",
             format(" functionCall (aaaa,   bbbb, {int i;});"));
   EXPECT_EQ("functionCall(aaaa, bbbb, {\n"
@@ -2910,7 +3041,8 @@
   EXPECT_EQ("functionCall(aaaa, bbbb, { int i; });",
             format(" functionCall (aaaa,   bbbb, {int i;});"));
   verifyFormat(
-      "Aaa({\n"
+      "Aaa(\n"  // FIXME: There shouldn't be a linebreak here.
+      "    {\n"
       "      int i; // break\n"
       "    },\n"
       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
@@ -2992,10 +3124,11 @@
   FormatStyle Style = getGoogleStyle();
   Style.ColumnLimit = 45;
   verifyFormat("Debug(aaaaa, {\n"
-               "               if (aaaaaaaaaaaaaaaaaaaaaaaa)\n"
-               "                 return;\n"
-               "             },\n"
-               "      a);", Style);
+               "  if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
+               "}, a);",
+               Style);
+
+  verifyNoCrash("^{v^{a}}");
 }
 
 TEST_F(FormatTest, IndividualStatementsOfNestedBlocks) {
@@ -3236,40 +3369,44 @@
   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
   verifyFormat(
       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-      "             + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-      "             + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-      "             == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-      "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
-      "                + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+      "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+      "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-      "                * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-      "                > ccccccccccccccccccccccccccccccccccccccccc;",
+      "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "                    > ccccccccccccccccccccccccccccccccccccccccc;",
       Style);
   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "    * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "    + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
                Style);
   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "    + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "      * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
                Style);
   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "       * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "       + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
+               "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
                Style);
   verifyFormat("if () {\n"
                "} else if (aaaaa\n"
                "           && bbbbb // break\n"
-               "              > ccccc) {\n"
+               "                  > ccccc) {\n"
                "}",
                Style);
   verifyFormat("return (a)\n"
                "       // comment\n"
                "       + b;",
                Style);
+  verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+               "             + cc;",
+               Style);
 
   // Forced by comments.
   verifyFormat(
@@ -3290,13 +3427,46 @@
                Style);
 }
 
+TEST_F(FormatTest, NoOperandAlignment) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignOperands = false;
+  Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
+  verifyFormat(
+      "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+      "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+      "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+      "        > ccccccccccccccccccccccccccccccccccccccccc;",
+      Style);
+
+  verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+               "    + cc;",
+               Style);
+  verifyFormat("int a = aa\n"
+               "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
+               "        * cccccccccccccccccccccccccccccccccccc;",
+               Style);
+
+  Style.AlignAfterOpenBracket = false;
+  verifyFormat("return (a > b\n"
+               "    // comment1\n"
+               "    // comment2\n"
+               "    || c);",
+               Style);
+}
+
 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
   FormatStyle Style = getLLVMStyle();
   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
-               "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", Style);
-
+               "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+               Style);
 }
 
 TEST_F(FormatTest, ConstructorInitializers) {
@@ -4064,6 +4234,28 @@
       Style);
 }
 
+TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
+  FormatStyle Style = getLLVMStyleWithColumns(40);
+  verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
+               "          bbbbbbbbbbbbbbbbbbbbbb);",
+               Style);
+  Style.AlignAfterOpenBracket = true;
+  Style.AlignOperands = false;
+  verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
+               "          bbbbbbbbbbbbbbbbbbbbbb);",
+               Style);
+  Style.AlignAfterOpenBracket = false;
+  Style.AlignOperands = true;
+  verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
+               "          bbbbbbbbbbbbbbbbbbbbbb);",
+               Style);
+  Style.AlignAfterOpenBracket = false;
+  Style.AlignOperands = false;
+  verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
+               "    bbbbbbbbbbbbbbbbbbbbbb);",
+               Style);
+}
+
 TEST_F(FormatTest, BreaksConditionalExpressions) {
   verifyFormat(
       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
@@ -4472,6 +4664,9 @@
             format("NSString *const kString = @\"aaaa\"\n"
                    "\"bbbb\";",
                    Break));
+
+  Break.ColumnLimit = 0;
+  verifyFormat("const char *hello = \"hello llvm\";", Break);
 }
 
 TEST_F(FormatTest, AlignsPipes) {
@@ -4570,6 +4765,11 @@
                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
                "}");
+
+  // Handle 'endl'.
+  verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
+               "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
+  verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
 }
 
 TEST_F(FormatTest, UnderstandsEquals) {
@@ -4835,6 +5035,7 @@
 
   verifyFormat("f<int>();");
   verifyFormat("template <typename T> void f() {}");
+  verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
 
   // Not template parameters.
   verifyFormat("return a < b && c > d;");
@@ -4968,17 +5169,42 @@
 
   verifyFormat("using A::operator+;");
 
-  verifyFormat("Deleted &operator=(const Deleted &)& = default;");
-  verifyFormat("Deleted &operator=(const Deleted &)&& = delete;");
-  verifyGoogleFormat("Deleted& operator=(const Deleted&)& = default;");
-  verifyGoogleFormat("Deleted& operator=(const Deleted&)&& = delete;");
-
   verifyFormat("string // break\n"
                "operator()() & {}");
   verifyFormat("string // break\n"
                "operator()() && {}");
 }
 
+TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
+  verifyFormat("Deleted &operator=(const Deleted &)& = default;");
+  verifyFormat("Deleted &operator=(const Deleted &)&& = delete;");
+  verifyFormat("SomeType MemberFunction(const Deleted &)& = delete;");
+  verifyFormat("SomeType MemberFunction(const Deleted &)&& = delete;");
+  verifyFormat("Deleted &operator=(const Deleted &)&;");
+  verifyFormat("Deleted &operator=(const Deleted &)&&;");
+  verifyFormat("SomeType MemberFunction(const Deleted &)&;");
+  verifyFormat("SomeType MemberFunction(const Deleted &)&&;");
+
+  verifyGoogleFormat("Deleted& operator=(const Deleted&)& = default;");
+  verifyGoogleFormat("SomeType MemberFunction(const Deleted&)& = delete;");
+  verifyGoogleFormat("Deleted& operator=(const Deleted&)&;");
+  verifyGoogleFormat("SomeType MemberFunction(const Deleted&)&;");
+
+  FormatStyle Spaces = getLLVMStyle();
+  Spaces.SpacesInCStyleCastParentheses = true;
+  verifyFormat("Deleted &operator=(const Deleted &)& = default;", Spaces);
+  verifyFormat("SomeType MemberFunction(const Deleted &)& = delete;", Spaces);
+  verifyFormat("Deleted &operator=(const Deleted &)&;", Spaces);
+  verifyFormat("SomeType MemberFunction(const Deleted &)&;", Spaces);
+
+  Spaces.SpacesInCStyleCastParentheses = false;
+  Spaces.SpacesInParentheses = true;
+  verifyFormat("Deleted &operator=( const Deleted & )& = default;", Spaces);
+  verifyFormat("SomeType MemberFunction( const Deleted & )& = delete;", Spaces);
+  verifyFormat("Deleted &operator=( const Deleted & )&;", Spaces);
+  verifyFormat("SomeType MemberFunction( const Deleted & )&;", Spaces);
+}
+
 TEST_F(FormatTest, UnderstandsNewAndDelete) {
   verifyFormat("void f() {\n"
                "  A *a = new A;\n"
@@ -5068,6 +5294,8 @@
       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
 
+  verifyGoogleFormat("**outparam = 1;");
+  verifyGoogleFormat("*outparam = a * b;");
   verifyGoogleFormat("int main(int argc, char** argv) {}");
   verifyGoogleFormat("A<int*> a;");
   verifyGoogleFormat("A<int**> a;");
@@ -5378,6 +5606,11 @@
   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
 }
 
+TEST_F(FormatTest, FormatsPointersToArrayTypes) {
+  verifyFormat("A (*foo_)[6];");
+  verifyFormat("vector<int> (*foo_)[6];");
+}
+
 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
@@ -5492,6 +5725,8 @@
       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
       "                                  .aaaaaaa[0]\n"
       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
+
+  verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
 }
 
 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
@@ -5533,6 +5768,10 @@
   Style.AlwaysBreakBeforeMultilineStrings = true;
   Style.ColumnLimit = 0;
   verifyFormat("#import \"abc.h\"", Style);
+
+  // But 'import' might also be a regular C++ namespace.
+  verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
+               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
 }
 
 //===----------------------------------------------------------------------===//
@@ -5615,6 +5854,7 @@
 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
   verifyFormat("{");
   verifyFormat("#})");
+  verifyNoCrash("(/**/[:!] ?[).");
 }
 
 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
@@ -5703,6 +5943,11 @@
   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
   verifyFormat("Node n{1, Node{1000}, //\n"
                "       2};");
+  verifyFormat("Aaaa aaaaaaa{\n"
+               "    {\n"
+               "        aaaa,\n"
+               "    },\n"
+               "};");
 
   // In combination with BinPackParameters = false.
   FormatStyle NoBinPacking = getLLVMStyle();
@@ -5812,8 +6057,7 @@
       "             BracedList{ // comment 1 (Forcing interesting break)\n"
       "                         param1, param2,\n"
       "                         // comment 2\n"
-      "                         param3, param4\n"
-      "             });",
+      "                         param3, param4 });",
       ExtraSpaces);
   verifyFormat(
       "std::this_thread::sleep_for(\n"
@@ -5897,6 +6141,8 @@
   // No column layout should be used here.
   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
+
+  verifyNoCrash("a<,");
 }
 
 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
@@ -6682,6 +6928,7 @@
   // Whew!
 
   verifyFormat("return in[42];");
+  verifyFormat("for (auto v : in[1]) {\n}");
   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
                "}");
   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
@@ -7284,24 +7531,22 @@
   EXPECT_EQ("@\"NSString \"\n"
             "@\"literal\";",
             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
+
+  // This input makes clang-format try to split the incomplete unicode escape
+  // sequence, which used to lead to a crasher.
+  verifyNoCrash(
+      "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+      getLLVMStyleWithColumns(60));
 }
 
-TEST_F(FormatTest, BreaksRawStringLiterals) {
-  EXPECT_EQ("R\"x(raw )x\"\n"
-            "R\"x(literal)x\";",
-            format("R\"x(raw literal)x\";", getGoogleStyleWithColumns(15)));
-  EXPECT_EQ("uR\"x(raw )x\"\n"
-            "uR\"x(literal)x\";",
-            format("uR\"x(raw literal)x\";", getGoogleStyleWithColumns(16)));
-  EXPECT_EQ("u8R\"x(raw )x\"\n"
-            "u8R\"x(literal)x\";",
-            format("u8R\"x(raw literal)x\";", getGoogleStyleWithColumns(17)));
-  EXPECT_EQ("LR\"x(raw )x\"\n"
-            "LR\"x(literal)x\";",
-            format("LR\"x(raw literal)x\";", getGoogleStyleWithColumns(16)));
-  EXPECT_EQ("UR\"x(raw )x\"\n"
-            "UR\"x(literal)x\";",
-            format("UR\"x(raw literal)x\";", getGoogleStyleWithColumns(16)));
+TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
+  FormatStyle Style = getGoogleStyleWithColumns(15);
+  EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
+  EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
+  EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
+  EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
+  EXPECT_EQ("u8R\"x(raw literal)x\";",
+            format("u8R\"x(raw literal)x\";", Style));
 }
 
 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
@@ -7490,11 +7735,6 @@
             "\"00000000\"\n"
             "\"1\"",
             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
-  // FIXME: We probably don't need to care about escape sequences in raw
-  // literals.
-  EXPECT_EQ("R\"(\\x)\"\n"
-            "R\"(\\x00)\"\n",
-            format("R\"(\\x\\x00)\"\n", getGoogleStyleWithColumns(7)));
 }
 
 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
@@ -7682,11 +7922,10 @@
                Tab);
   verifyFormat("{\n"
                "\tQ({\n"
-               "\t\t  int a;\n"
-               "\t\t  someFunction(aaaaaaaaaa,\n"
-               "\t\t               bbbbbbbbb);\n"
-               "\t  },\n"
-               "\t  p);\n"
+               "\t\tint a;\n"
+               "\t\tsomeFunction(aaaaaaaa,\n"
+               "\t\t             bbbbbbb);\n"
+               "\t}, p);\n"
                "}",
                Tab);
   EXPECT_EQ("{\n"
@@ -8276,6 +8515,11 @@
                "  [object someMethod:@{ @\"a\" : @\"b\" }];\n"
                "}",
                AllmanBraceStyle);
+  verifyFormat("int f()\n"
+               "{ // comment\n"
+               "  return 42;\n"
+               "}",
+               AllmanBraceStyle);
 
   AllmanBraceStyle.ColumnLimit = 19;
   verifyFormat("void f() { int i; }", AllmanBraceStyle);
@@ -8561,7 +8805,9 @@
 TEST_F(FormatTest, ParsesConfigurationBools) {
   FormatStyle Style = {};
   Style.Language = FormatStyle::LK_Cpp;
+  CHECK_PARSE_BOOL(AlignAfterOpenBracket);
   CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
+  CHECK_PARSE_BOOL(AlignOperands);
   CHECK_PARSE_BOOL(AlignTrailingComments);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
   CHECK_PARSE_BOOL(AllowShortBlocksOnASingleLine);
@@ -8662,6 +8908,8 @@
               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
+  CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
+              AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
   // For backward compatibility:
@@ -9167,6 +9415,11 @@
                "double b; // align comments.",
                Style);
 
+  // Do not align operands.
+  EXPECT_EQ("ASSERT(aaaa\n"
+            "    || bbbb);",
+            format("ASSERT ( aaaa\n||bbbb);", Style));
+
   // Accept input's line breaks.
   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
             "    || bbbbbbbbbbbbbbb) {\n"
@@ -9262,25 +9515,34 @@
   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
                "});");
+  verifyFormat("Constructor()\n"
+               "    : Field([] { // comment\n"
+               "        int i;\n"
+               "      }) {}");
 
   // Lambdas with return types.
   verifyFormat("int c = []() -> int { return 2; }();\n");
   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
+  verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
+  verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
+  verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
+  verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
                "                   int j) -> int {\n"
                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
                "};");
 
   // Multiple lambdas in the same parentheses change indentation rules.
-  verifyFormat("SomeFunction([]() {\n"
-               "               int i = 42;\n"
-               "               return i;\n"
-               "             },\n"
-               "             []() {\n"
-               "               int j = 43;\n"
-               "               return j;\n"
-               "             });");
+  verifyFormat("SomeFunction(\n"
+               "    []() {\n"
+               "      int i = 42;\n"
+               "      return i;\n"
+               "    },\n"
+               "    []() {\n"
+               "      int j = 43;\n"
+               "      return j;\n"
+               "    });");
 
   // More complex introducers.
   verifyFormat("return [i, args...] {};");
@@ -9303,6 +9565,19 @@
   verifyFormat("void f() {\n"
                "  MACRO((const AA &a) { return 1; });\n"
                "}");
+
+  verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
+               "      doo_dah();\n"
+               "      doo_dah();\n"
+               "    })) {\n"
+               "}");
+  verifyFormat("auto lambda = []() {\n"
+               "  int a = 2\n"
+               "#if A\n"
+               "          + 2\n"
+               "#endif\n"
+               "      ;\n"
+               "};");
 }
 
 TEST_F(FormatTest, FormatsBlocks) {
@@ -9396,6 +9671,7 @@
                "    }\n"
                "  }\n"
                "});");
+  verifyFormat("Block b = ^int *(A *a, B *b) {}");
 
   FormatStyle FourIndent = getLLVMStyle();
   FourIndent.ObjCBlockIndentWidth = 4;
@@ -9501,6 +9777,29 @@
   verifyFormat("A<A<int>>();", Spaces);
 }
 
+TEST_F(FormatTest, TripleAngleBrackets) {
+  verifyFormat("f<<<1, 1>>>();");
+  verifyFormat("f<<<1, 1, 1, s>>>();");
+  verifyFormat("f<<<a, b, c, d>>>();");
+  EXPECT_EQ("f<<<1, 1>>>();",
+            format("f <<< 1, 1 >>> ();"));
+  verifyFormat("f<param><<<1, 1>>>();");
+  verifyFormat("f<1><<<1, 1>>>();");
+  EXPECT_EQ("f<param><<<1, 1>>>();",
+            format("f< param > <<< 1, 1 >>> ();"));
+  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+               "aaaaaaaaaaa<<<\n    1, 1>>>();");
+}
+
+TEST_F(FormatTest, MergeLessLessAtEnd) {
+  verifyFormat("<<");
+  EXPECT_EQ("< < <", format("\\\n<<<"));
+  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+               "aaallvm::outs() <<");
+  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+               "aaaallvm::outs()\n    <<");
+}
+
 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
   std::string code = "#if A\n"
                      "#if B\n"
diff --git a/unittests/Format/FormatTestJS.cpp b/unittests/Format/FormatTestJS.cpp
index 6ee150c..55e89da 100644
--- a/unittests/Format/FormatTestJS.cpp
+++ b/unittests/Format/FormatTestJS.cpp
@@ -94,7 +94,10 @@
 
 TEST_F(FormatTestJS, ES6DestructuringAssignment) {
   verifyFormat("var [a, b, c] = [1, 2, 3];");
-  verifyFormat("var {a, b} = {a: 1, b: 2};");
+  verifyFormat("var {a, b} = {\n"
+               "  a: 1,\n"
+               "  b: 2\n"
+               "};");
 }
 
 TEST_F(FormatTestJS, ContainerLiterals) {
@@ -131,20 +134,25 @@
                "      //\n"
                "      a\n"
                "};");
+  verifyFormat("var obj = {\n"
+               "  fooooooooo: function(x) {\n"
+               "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
+               "  }\n"
+               "};");
 }
 
 TEST_F(FormatTestJS, SpacesInContainerLiterals) {
   verifyFormat("var arr = [1, 2, 3];");
-  verifyFormat("var obj = {a: 1, b: 2, c: 3};");
+  verifyFormat("f({a: 1, b: 2, c: 3});");
 
   verifyFormat("var object_literal_with_long_name = {\n"
                "  a: 'aaaaaaaaaaaaaaaaaa',\n"
                "  b: 'bbbbbbbbbbbbbbbbbb'\n"
                "};");
 
-  verifyFormat("var obj = {a: 1, b: 2, c: 3};",
+  verifyFormat("f({a: 1, b: 2, c: 3});",
                getChromiumStyle(FormatStyle::LK_JavaScript));
-  verifyFormat("someVariable = {'a': [{}]};");
+  verifyFormat("f({'a': [{}]});");
 }
 
 TEST_F(FormatTestJS, SingleQuoteStrings) {
@@ -158,6 +166,22 @@
                "});  // goog.scope");
 }
 
+TEST_F(FormatTestJS, GoogModules) {
+  verifyFormat("goog.module('this.is.really.absurdly.long');",
+               getGoogleJSStyleWithColumns(40));
+  verifyFormat("goog.require('this.is.really.absurdly.long');",
+               getGoogleJSStyleWithColumns(40));
+  verifyFormat("goog.provide('this.is.really.absurdly.long');",
+               getGoogleJSStyleWithColumns(40));
+  verifyFormat("var long = goog.require('this.is.really.absurdly.long');",
+               getGoogleJSStyleWithColumns(40));
+
+  // These should be wrapped normally.
+  verifyFormat(
+      "var MyLongClassName =\n"
+      "    goog.module.get('my.long.module.name.followedBy.MyLongClassName');");
+}
+
 TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
   verifyFormat("function outer1(a, b) {\n"
                "  function inner1(a, b) { return a; }\n"
@@ -182,14 +206,13 @@
                "    style: {direction: ''}\n"
                "  }\n"
                "};");
-  // FIXME: The formatting here probably isn't ideal.
   EXPECT_EQ("abc = xyz ?\n"
             "          function() {\n"
             "            return 1;\n"
             "          } :\n"
             "          function() {\n"
-            "  return -1;\n"
-            "};",
+            "            return -1;\n"
+            "          };",
             format("abc=xyz?function(){return 1;}:function(){return -1;};"));
 
   verifyFormat("var closure = goog.bind(\n"
@@ -211,13 +234,18 @@
                "    };\n"
                "  }\n"
                "};");
+  verifyFormat("{\n"
+               "  var someVariable = function(x) {\n"
+               "    return x.zIsTooLongForOneLineWithTheDeclarationLine();\n"
+               "  };\n"
+               "}");
 
-  verifyFormat("var x = {a: function() { return 1; }};",
-               getGoogleJSStyleWithColumns(38));
-  verifyFormat("var x = {\n"
+  verifyFormat("f({a: function() { return 1; }});",
+               getGoogleJSStyleWithColumns(33));
+  verifyFormat("f({\n"
                "  a: function() { return 1; }\n"
-               "};",
-               getGoogleJSStyleWithColumns(37));
+               "});",
+               getGoogleJSStyleWithColumns(32));
 
   verifyFormat("return {\n"
                "  a: function SomeFunction() {\n"
@@ -225,6 +253,23 @@
                "    return 1;\n"
                "  }\n"
                "};");
+  verifyFormat("this.someObject.doSomething(aaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
+               "    .then(goog.bind(function(aaaaaaaaaaa) {\n"
+               "      someFunction();\n"
+               "      someFunction();\n"
+               "    }, this), aaaaaaaaaaaaaaaaa);");
+
+  // FIXME: This is not ideal yet.
+  verifyFormat("someFunction(goog.bind(\n"
+               "                 function() {\n"
+               "                   doSomething();\n"
+               "                   doSomething();\n"
+               "                 },\n"
+               "                 this),\n"
+               "             goog.bind(function() {\n"
+               "               doSomething();\n"
+               "               doSomething();\n"
+               "             }, this));");
 }
 
 TEST_F(FormatTestJS, InliningFunctionLiterals) {
@@ -312,7 +357,10 @@
 
   verifyFormat("getSomeLongPromise()\n"
                "    .then(function(value) { body(); })\n"
-               "    .thenCatch(function(error) { body(); });");
+               "    .thenCatch(function(error) {\n"
+               "      body();\n"
+               "      body();\n"
+               "    });");
   verifyFormat("getSomeLongPromise()\n"
                "    .then(function(value) {\n"
                "      body();\n"
@@ -322,6 +370,11 @@
                "      body();\n"
                "      body();\n"
                "    });");
+
+  // FIXME: This is bad, but it used to be formatted correctly by accident.
+  verifyFormat("getSomeLongPromise().then(function(value) {\n"
+               "  body();\n"
+               "}).thenCatch(function(error) { body(); });");
 }
 
 TEST_F(FormatTestJS, ReturnStatements) {
@@ -345,6 +398,8 @@
 
   // But, of course, "catch" is a perfectly fine function name in JavaScript.
   verifyFormat("someObject.catch();");
+  verifyFormat("someObject.new();");
+  verifyFormat("someObject.delete();");
 }
 
 TEST_F(FormatTestJS, StringLiteralConcatenation) {
@@ -427,11 +482,136 @@
   verifyFormat("var regex =\n"
                "    /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
                getGoogleJSStyleWithColumns(60));
+  verifyFormat("var regex = /\\xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/;",
+               getGoogleJSStyleWithColumns(50));
 }
 
 TEST_F(FormatTestJS, RegexLiteralExamples) {
   verifyFormat("var regex = search.match(/(?:\?|&)times=([^?&]+)/i);");
 }
 
+TEST_F(FormatTestJS, TypeAnnotations) {
+  verifyFormat("var x: string;");
+  verifyFormat("function x(): string {\n  return 'x';\n}");
+  verifyFormat("function x(y: string): string {\n  return 'x';\n}");
+  verifyFormat("for (var y: string in x) {\n  x();\n}");
+  verifyFormat("((a: string, b: number): string => a + b);");
+  verifyFormat("var x: (y: number) => string;");
+  verifyFormat("var x: P<string, (a: number) => string>;");
+}
+
+TEST_F(FormatTestJS, ClassDeclarations) {
+  verifyFormat("class C {\n  x: string = 12;\n}");
+  verifyFormat("class C {\n  x(): string => 12;\n}");
+  verifyFormat("class C {\n  ['x' + 2]: string = 12;\n}");
+  verifyFormat("class C {\n  private x: string = 12;\n}");
+  verifyFormat("class C {\n  private static x: string = 12;\n}");
+  verifyFormat("class C {\n  static x(): string { return 'asd'; }\n}");
+  verifyFormat("class C extends P implements I {}");
+}
+
+TEST_F(FormatTestJS, MetadataAnnotations) {
+  verifyFormat("@A\nclass C {\n}");
+  verifyFormat("@A({arg: 'value'})\nclass C {\n}");
+  verifyFormat("@A\n@B\nclass C {\n}");
+  verifyFormat("class C {\n  @A x: string;\n}");
+  verifyFormat("class C {\n"
+               "  @A\n"
+               "  private x(): string {\n"
+               "    return 'y';\n"
+               "  }\n"
+               "}");
+  verifyFormat("class X {}\n"
+               "class Y {}");
+}
+
+TEST_F(FormatTestJS, Modules) {
+  verifyFormat("import SomeThing from 'some/module.js';");
+  verifyFormat("import {X, Y} from 'some/module.js';");
+  verifyFormat("import {\n"
+               "  VeryLongImportsAreAnnoying,\n"
+               "  VeryLongImportsAreAnnoying,\n"
+               "  VeryLongImportsAreAnnoying,\n"
+               "  VeryLongImportsAreAnnoying\n"
+               "} from 'some/module.js';");
+  verifyFormat("import {\n"
+               "  X,\n"
+               "  Y,\n"
+               "} from 'some/module.js';");
+  verifyFormat("import {\n"
+               "  X,\n"
+               "  Y,\n"
+               "} from 'some/long/module.js';",
+               getGoogleJSStyleWithColumns(20));
+  verifyFormat("import {X as myLocalX, Y as myLocalY} from 'some/module.js';");
+  verifyFormat("import * as lib from 'some/module.js';");
+  verifyFormat("var x = {\n  import: 1\n};\nx.import = 2;");
+
+  verifyFormat("export function fn() {\n"
+               "  return 'fn';\n"
+               "}");
+  verifyFormat("export const x = 12;");
+  verifyFormat("export default class X {}");
+  verifyFormat("export {X, Y} from 'some/module.js';");
+  verifyFormat("export {\n"
+               "  X,\n"
+               "  Y,\n"
+               "} from 'some/module.js';");
+  verifyFormat("export class C {\n"
+               "  x: number;\n"
+               "  y: string;\n"
+               "}");
+  verifyFormat("export class X { y: number; }");
+  verifyFormat("export default class X { y: number }");
+  verifyFormat("export default function() {\n  return 1;\n}");
+  verifyFormat("export var x = 12;");
+  verifyFormat("export var x: number = 12;");
+  verifyFormat("export const y = {\n"
+               "  a: 1,\n"
+               "  b: 2\n"
+               "};");
+}
+
+TEST_F(FormatTestJS, TemplateStrings) {
+  // Keeps any whitespace/indentation within the template string.
+  EXPECT_EQ("var x = `hello\n"
+            "     ${  name    }\n"
+            "  !`;",
+            format("var x    =    `hello\n"
+                   "     ${  name    }\n"
+                   "  !`;"));
+
+  // FIXME: +1 / -1 offsets are to work around clang-format miscalculating
+  // widths for unknown tokens that are not whitespace (e.g. '`'). Remove when
+  // the code is corrected.
+
+  verifyFormat("var x =\n"
+               "    `hello ${world}` >= some();",
+               getGoogleJSStyleWithColumns(34)); // Barely doesn't fit.
+  verifyFormat("var x = `hello ${world}` >= some();",
+               getGoogleJSStyleWithColumns(35 + 1)); // Barely fits.
+  EXPECT_EQ("var x = `hello\n"
+            "  ${world}` >=\n"
+            "        some();",
+            format("var x =\n"
+                   "    `hello\n"
+                   "  ${world}` >= some();",
+                   getGoogleJSStyleWithColumns(21))); // Barely doesn't fit.
+  EXPECT_EQ("var x = `hello\n"
+            "  ${world}` >= some();",
+            format("var x =\n"
+                   "    `hello\n"
+                   "  ${world}` >= some();",
+                   getGoogleJSStyleWithColumns(22))); // Barely fits.
+
+  verifyFormat("var x =\n    `h`;", getGoogleJSStyleWithColumns(13 - 1));
+  EXPECT_EQ(
+      "var x =\n    `multi\n  line`;",
+      format("var x = `multi\n  line`;", getGoogleJSStyleWithColumns(14 - 1)));
+
+  // Two template strings.
+  verifyFormat("var x = `hello` == `hello`;");
+}
+
 } // end namespace tooling
 } // end namespace clang
diff --git a/unittests/Format/FormatTestJava.cpp b/unittests/Format/FormatTestJava.cpp
index cb96756..8d6daa6 100644
--- a/unittests/Format/FormatTestJava.cpp
+++ b/unittests/Format/FormatTestJava.cpp
@@ -54,6 +54,46 @@
   verifyFormat("someObject.and();");
 }
 
+TEST_F(FormatTestJava, UnderstandsCasts) {
+  verifyFormat("a[b >> 1] = (byte) (c() << 4);");
+}
+
+TEST_F(FormatTestJava, FormatsInstanceOfLikeOperators) {
+  FormatStyle Style = getStyleWithColumns(50);
+  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+               "    instanceof bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+               Style);
+  Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
+  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaa instanceof\n"
+               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
+               Style);
+}
+
+TEST_F(FormatTestJava, Chromium) {
+  verifyFormat("class SomeClass {\n"
+               "    void f() {}\n"
+               "    int g() {\n"
+               "        return 0;\n"
+               "    }\n"
+               "    void h() {\n"
+               "        while (true) f();\n"
+               "        for (;;) f();\n"
+               "        if (true) f();\n"
+               "    }\n"
+               "}",
+               getChromiumStyle(FormatStyle::LK_Java));
+}
+
+TEST_F(FormatTestJava, QualifiedNames) {
+  verifyFormat("public some.package.Type someFunction( // comment\n"
+               "    int parameter) {}");
+}
+
+TEST_F(FormatTestJava, ClassKeyword) {
+  verifyFormat("SomeClass.class.getName();");
+  verifyFormat("Class c = SomeClass.class;");
+}
+
 TEST_F(FormatTestJava, ClassDeclarations) {
   verifyFormat("public class SomeClass {\n"
                "  private int a;\n"
@@ -89,13 +129,11 @@
                getStyleWithColumns(60));
   verifyFormat("@SomeAnnotation()\n"
                "abstract class aaaaaaaaaaaa\n"
-               "    extends bbbbbbbbbbbbbbb implements cccccccccccc {\n"
-               "}",
+               "    extends bbbbbbbbbbbbbbb implements cccccccccccc {}",
                getStyleWithColumns(76));
   verifyFormat("@SomeAnnotation()\n"
                "abstract class aaaaaaaaa<a>\n"
-               "    extends bbbbbbbbbbbb<b> implements cccccccccccc {\n"
-               "}",
+               "    extends bbbbbbbbbbbb<b> implements cccccccccccc {}",
                getStyleWithColumns(76));
   verifyFormat("interface SomeInterface<A> extends Foo, Bar {\n"
                "  void doStuff(int theStuff);\n"
@@ -123,31 +161,26 @@
                "}");
   verifyFormat("public class SomeClass {\n"
                "  enum SomeThing { ABC, CDE }\n"
-               "  void f() {\n"
-               "  }\n"
+               "  void f() {}\n"
                "}");
   verifyFormat("public class SomeClass implements SomeInterface {\n"
                "  enum SomeThing { ABC, CDE }\n"
-               "  void f() {\n"
-               "  }\n"
+               "  void f() {}\n"
                "}");
   verifyFormat("enum SomeThing {\n"
                "  ABC,\n"
                "  CDE;\n"
-               "  void f() {\n"
-               "  }\n"
+               "  void f() {}\n"
                "}");
   verifyFormat("enum SomeThing {\n"
                "  ABC(1, \"ABC\"),\n"
                "  CDE(2, \"CDE\");\n"
-               "  Something(int i, String s) {\n"
-               "  }\n"
+               "  Something(int i, String s) {}\n"
                "}");
   verifyFormat("enum SomeThing {\n"
-               "  ABC(new int[]{1, 2}),\n"
-               "  CDE(new int[]{2, 3});\n"
-               "  Something(int[] i) {\n"
-               "  }\n"
+               "  ABC(new int[] {1, 2}),\n"
+               "  CDE(new int[] {2, 3});\n"
+               "  Something(int[] i) {}\n"
                "}");
   verifyFormat("public enum SomeThing {\n"
                "  ABC {\n"
@@ -161,8 +194,7 @@
                "      return \"CDE\";\n"
                "    }\n"
                "  };\n"
-               "  public void f() {\n"
-               "  }\n"
+               "  public void f() {}\n"
                "}");
   verifyFormat("private enum SomeEnum implements Foo<?, B> {\n"
                "  ABC {\n"
@@ -180,32 +212,53 @@
                "}");
 }
 
+TEST_F(FormatTestJava, ArrayInitializers) {
+  verifyFormat("new int[] {1, 2, 3, 4};");
+  verifyFormat("new int[] {\n"
+               "    1, 2, 3, 4,\n"
+               "};");
+
+  FormatStyle Style = getStyleWithColumns(65);
+  Style.Cpp11BracedListStyle = false;
+  verifyFormat(
+      "expected = new int[] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n"
+      "  100, 100, 100, 100, 100, 100, 100, 100, 100, 100 };",
+      Style);
+}
+
 TEST_F(FormatTestJava, ThrowsDeclarations) {
   verifyFormat("public void doSooooooooooooooooooooooooooomething()\n"
-               "    throws LooooooooooooooooooooooooooooongException {\n}");
+               "    throws LooooooooooooooooooooooooooooongException {}");
+  verifyFormat("public void doSooooooooooooooooooooooooooomething()\n"
+               "    throws LoooooooooongException, LooooooooooongException {}");
 }
 
 TEST_F(FormatTestJava, Annotations) {
   verifyFormat("@Override\n"
-               "public String toString() {\n}");
+               "public String toString() {}");
   verifyFormat("@Override\n"
                "@Nullable\n"
-               "public String getNameIfPresent() {\n}");
+               "public String getNameIfPresent() {}");
+  verifyFormat("@Override // comment\n"
+               "@Nullable\n"
+               "public String getNameIfPresent() {}");
+  verifyFormat("@java.lang.Override // comment\n"
+               "@Nullable\n"
+               "public String getNameIfPresent() {}");
 
   verifyFormat("@SuppressWarnings(value = \"unchecked\")\n"
-               "public void doSomething() {\n}");
+               "public void doSomething() {}");
   verifyFormat("@SuppressWarnings(value = \"unchecked\")\n"
                "@Author(name = \"abc\")\n"
-               "public void doSomething() {\n}");
+               "public void doSomething() {}");
 
   verifyFormat("DoSomething(new A() {\n"
                "  @Override\n"
-               "  public String toString() {\n"
-               "  }\n"
+               "  public String toString() {}\n"
                "});");
 
-  verifyFormat("void SomeFunction(@Nullable String something) {\n"
-               "}");
+  verifyFormat("void SomeFunction(@Nullable String something) {}");
+  verifyFormat("void SomeFunction(@org.llvm.Nullable String something) {}");
 
   verifyFormat("@Partial @Mock DataLoader loader;");
   verifyFormat("@SuppressWarnings(value = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n"
@@ -213,6 +266,33 @@
 
   verifyFormat("@SomeAnnotation(\"With some really looooooooooooooong text\")\n"
                "private static final long something = 0L;");
+  verifyFormat("@org.llvm.Qualified(\"With some really looooooooooong text\")\n"
+               "private static final long something = 0L;");
+  verifyFormat("@Mock\n"
+               "DataLoader loooooooooooooooooooooooader =\n"
+               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+               getStyleWithColumns(60));
+  verifyFormat("@org.llvm.QualifiedMock\n"
+               "DataLoader loooooooooooooooooooooooader =\n"
+               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
+               getStyleWithColumns(60));
+  verifyFormat("@Test(a)\n"
+               "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
+               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa);");
+  verifyFormat("@SomeAnnotation(\n"
+               "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa)\n"
+               "int i;",
+               getStyleWithColumns(50));
+  verifyFormat("@Test\n"
+               "ReturnType doSomething(\n"
+               "    String aaaaaaaaaaaaa, String bbbbbbbbbbbbbbb) {}",
+               getStyleWithColumns(60));
+  verifyFormat("{\n"
+               "  boolean someFunction(\n"
+               "      @Param(aaaaaaaaaaaaaaaa) String aaaaa,\n"
+               "      String bbbbbbbbbbbbbbb) {}\n"
+               "}",
+               getStyleWithColumns(60));
 }
 
 TEST_F(FormatTestJava, Generics) {
@@ -223,17 +303,24 @@
   verifyFormat("A.<B>doSomething();");
 
   verifyFormat("@Override\n"
-               "public Map<String, ?> getAll() {\n}");
+               "public Map<String, ?> getAll() {}");
 
-  verifyFormat("public <R> ArrayList<R> get() {\n}");
-  verifyFormat("protected <R> ArrayList<R> get() {\n}");
-  verifyFormat("private <R> ArrayList<R> get() {\n}");
-  verifyFormat("public static <R> ArrayList<R> get() {\n}");
+  verifyFormat("public <R> ArrayList<R> get() {}");
+  verifyFormat("protected <R> ArrayList<R> get() {}");
+  verifyFormat("private <R> ArrayList<R> get() {}");
+  verifyFormat("public static <R> ArrayList<R> get() {}");
+  verifyFormat("public static native <R> ArrayList<R> get();");
+  verifyFormat("public final <X> Foo foo() {}");
+  verifyFormat("public abstract <X> Foo foo();");
   verifyFormat("<T extends B> T getInstance(Class<T> type);");
   verifyFormat("Function<F, ? extends T> function;");
 
   verifyFormat("private Foo<X, Y>[] foos;");
   verifyFormat("Foo<X, Y>[] foos = this.foos;");
+  verifyFormat("return (a instanceof List<?>)\n"
+               "    ? aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
+               "    : aaaaaaaaaaaaaaaaaaaaaaa;",
+               getStyleWithColumns(60));
 
   verifyFormat(
       "SomeLoooooooooooooooooooooongType name =\n"
@@ -245,7 +332,7 @@
 
 TEST_F(FormatTestJava, StringConcatenation) {
   verifyFormat("String someString = \"abc\"\n"
-               "                    + \"cde\";");
+               "    + \"cde\";");
 }
 
 TEST_F(FormatTestJava, TryCatchFinally) {
@@ -274,25 +361,41 @@
                "}");
 }
 
+TEST_F(FormatTestJava, TryWithResources) {
+  verifyFormat("try (SomeResource rs = someFunction()) {\n"
+               "  Something();\n"
+               "}");
+  verifyFormat("try (SomeResource rs = someFunction()) {\n"
+               "  Something();\n"
+               "} catch (SomeException e) {\n"
+               "  HandleException(e);\n"
+               "}");
+}
+
 TEST_F(FormatTestJava, SynchronizedKeyword) {
   verifyFormat("synchronized (mData) {\n"
                "  // ...\n"
                "}");
 }
 
+TEST_F(FormatTestJava, PackageDeclarations) {
+  verifyFormat("package some.really.loooooooooooooooooooooong.package;",
+               getStyleWithColumns(50));
+}
+
 TEST_F(FormatTestJava, ImportDeclarations) {
   verifyFormat("import some.really.loooooooooooooooooooooong.imported.Class;",
                getStyleWithColumns(50));
+  verifyFormat("import static some.really.looooooooooooooooong.imported.Class;",
+               getStyleWithColumns(50));
 }
 
 TEST_F(FormatTestJava, MethodDeclarations) {
   verifyFormat("void methodName(Object arg1,\n"
-               "    Object arg2, Object arg3) {\n"
-               "}",
+               "    Object arg2, Object arg3) {}",
                getStyleWithColumns(40));
   verifyFormat("void methodName(\n"
-               "    Object arg1, Object arg2) {\n"
-               "}",
+               "    Object arg1, Object arg2) {}",
                getStyleWithColumns(40));
 }
 
@@ -315,6 +418,74 @@
                "    .bbbbbbbbbbbbbbbbbbb()\n"
                "    .ccccccccccccccccccc();",
                getStyleWithColumns(40));
+  verifyFormat("return aaaaaaaaaaaaaaaaaaa()\n"
+               "    .bbbbbbbbbbbbbbbbbbb(\n"
+               "         ccccccccccccccc)\n"
+               "    .ccccccccccccccccccc();",
+               getStyleWithColumns(40));
+}
+
+TEST_F(FormatTestJava, FormatsInnerBlocks) {
+  verifyFormat("someObject.someFunction(new Runnable() {\n"
+               "  @Override\n"
+               "  public void run() {\n"
+               "    System.out.println(42);\n"
+               "  }\n"
+               "}, someOtherParameter);");
+  verifyFormat("someFunction(new Runnable() {\n"
+               "  public void run() {\n"
+               "    System.out.println(42);\n"
+               "  }\n"
+               "});");
+  verifyFormat("someObject.someFunction(\n"
+               "    new Runnable() {\n"
+               "      @Override\n"
+               "      public void run() {\n"
+               "        System.out.println(42);\n"
+               "      }\n"
+               "    },\n"
+               "    new Runnable() {\n"
+               "      @Override\n"
+               "      public void run() {\n"
+               "        System.out.println(43);\n"
+               "      }\n"
+               "    },\n"
+               "    someOtherParameter);");
+}
+
+TEST_F(FormatTestJava, FormatsLambdas) {
+  verifyFormat("(aaaaaaaaaa, bbbbbbbbbb) -> aaaaaaaaaa + bbbbbbbbbb;");
+  verifyFormat("(aaaaaaaaaa, bbbbbbbbbb)\n"
+               "    -> aaaaaaaaaa + bbbbbbbbbb;",
+               getStyleWithColumns(40));
+  verifyFormat("Runnable someLambda = () -> DoSomething();");
+  verifyFormat("Runnable someLambda = () -> {\n"
+               "  DoSomething();\n"
+               "}");
+
+  verifyFormat("Runnable someLambda =\n"
+               "    (int aaaaa) -> DoSomething(aaaaa);",
+               getStyleWithColumns(40));
+}
+
+TEST_F(FormatTestJava, BreaksStringLiterals) {
+  // FIXME: String literal breaking is currently disabled for Java and JS, as it
+  // requires strings to be merged using "+" which we don't support.
+  EXPECT_EQ("\"some text other\";",
+            format("\"some text other\";", getStyleWithColumns(14)));
+}
+
+TEST_F(FormatTestJava, AlignsBlockComments) {
+  EXPECT_EQ("/*\n"
+            " * Really multi-line\n"
+            " * comment.\n"
+            " */\n"
+            "void f() {}",
+            format("  /*\n"
+                   "   * Really multi-line\n"
+                   "   * comment.\n"
+                   "   */\n"
+                   "  void f() {}"));
 }
 
 } // end namespace tooling
diff --git a/unittests/Tooling/ToolingTest.cpp b/unittests/Tooling/ToolingTest.cpp
index 98b7008..5a93e38 100644
--- a/unittests/Tooling/ToolingTest.cpp
+++ b/unittests/Tooling/ToolingTest.cpp
@@ -19,6 +19,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Config/llvm-config.h"
 #include "gtest/gtest.h"
+#include <algorithm>
 #include <string>
 
 namespace clang {
@@ -260,25 +261,6 @@
   EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
 }
 
-struct CheckSyntaxOnlyAdjuster: public ArgumentsAdjuster {
-  bool &Found;
-  bool &Ran;
-
-  CheckSyntaxOnlyAdjuster(bool &Found, bool &Ran) : Found(Found), Ran(Ran) { }
-
-  virtual CommandLineArguments
-  Adjust(const CommandLineArguments &Args) override {
-    Ran = true;
-    for (unsigned I = 0, E = Args.size(); I != E; ++I) {
-      if (Args[I] == "-fsyntax-only") {
-        Found = true;
-        break;
-      }
-    }
-    return Args;
-  }
-};
-
 TEST(ClangToolTest, ArgumentAdjusters) {
   FixedCompilationDatabase Compilations("/", std::vector<std::string>());
 
@@ -290,15 +272,22 @@
 
   bool Found = false;
   bool Ran = false;
-  Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
+  ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
+      [&Found, &Ran](const CommandLineArguments &Args) {
+    Ran = true;
+    if (std::find(Args.begin(), Args.end(), "-fsyntax-only") != Args.end())
+      Found = true;
+    return Args;
+  };
+  Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
   Tool.run(Action.get());
   EXPECT_TRUE(Ran);
   EXPECT_TRUE(Found);
 
   Ran = Found = false;
   Tool.clearArgumentsAdjusters();
-  Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
-  Tool.appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster());
+  Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
+  Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
   Tool.run(Action.get());
   EXPECT_TRUE(Ran);
   EXPECT_FALSE(Found);
diff --git a/unittests/libclang/LibclangTest.cpp b/unittests/libclang/LibclangTest.cpp
index ee56e22..a218814 100644
--- a/unittests/libclang/LibclangTest.cpp
+++ b/unittests/libclang/LibclangTest.cpp
@@ -8,11 +8,11 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang-c/Index.h"
-#include "gtest/gtest.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
+#include "gtest/gtest.h"
 #include <fstream>
 #include <set>
 #define DEBUG_TYPE "libclang-test"
diff --git a/utils/TableGen/ClangAttrEmitter.cpp b/utils/TableGen/ClangAttrEmitter.cpp
index 10b70fc..83629ec 100644
--- a/utils/TableGen/ClangAttrEmitter.cpp
+++ b/utils/TableGen/ClangAttrEmitter.cpp
@@ -12,8 +12,8 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/TableGen/Error.h"
@@ -1207,7 +1207,7 @@
 static unsigned
 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
                      const FlattenedSpelling &Spelling) {
-  assert(SpellingList.size() && "Spelling list is empty!");
+  assert(!SpellingList.empty() && "Spelling list is empty!");
 
   for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
     const FlattenedSpelling &S = SpellingList[Index];
@@ -1231,7 +1231,7 @@
     std::vector<FlattenedSpelling> Spellings = 
       GetFlattenedSpellings(*Accessor);
     std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
-    assert(SpellingList.size() &&
+    assert(!SpellingList.empty() &&
            "Attribute with empty spelling list can't have accessors!");
 
     OS << "  bool " << Name << "() const { return SpellingListIndex == ";
@@ -1387,6 +1387,7 @@
     llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
     .Case("IdentifierArgument", true)
     .Case("EnumArgument", true)
+    .Case("VariadicEnumArgument", true)
     .Default(false);
 }
 
@@ -1920,9 +1921,6 @@
   }
 
   OS << "switch (Syntax) {\n";
-  OS << "case AttrSyntax::Generic:\n";
-  OS << "  return llvm::StringSwitch<int>(Name)\n";
-  GenerateHasAttrSpellingStringSwitch(Attrs, OS);
   OS << "case AttrSyntax::GNU:\n";
   OS << "  return llvm::StringSwitch<int>(Name)\n";
   GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
@@ -2187,7 +2185,8 @@
     Namespace = 1U << 11,
     Field = 1U << 12,
     CXXMethod = 1U << 13,
-    ObjCProtocol = 1U << 14
+    ObjCProtocol = 1U << 14,
+    Enum = 1U << 15
   };
   uint32_t SubMask = 0;
 
@@ -2221,6 +2220,7 @@
                    .Case("Namespace", Namespace)
                    .Case("Field", Field)
                    .Case("CXXMethod", CXXMethod)
+                   .Case("Enum", Enum)
                    .Default(0);
     if (!V) {
       // Something wasn't in our mapping, so be helpful and let the developer
@@ -2239,6 +2239,7 @@
     case Var:   return "ExpectedVariable";
     case Param: return "ExpectedParameter";
     case Class: return "ExpectedClass";
+    case Enum:  return "ExpectedEnum";
     case CXXMethod:
       // FIXME: Currently, this maps to ExpectedMethod based on existing code,
       // but should map to something a bit more accurate at some point.
@@ -2392,6 +2393,8 @@
   std::string FnName = "check", Test;
   for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
     std::string Part = (*I)->getValueAsString("Name");
+    if ((*I)->getValueAsBit("Negated"))
+      Test += "!";
     Test += "S.LangOpts." + Part;
     if (I + 1 != E)
       Test += " || ";
diff --git a/utils/TableGen/NeonEmitter.cpp b/utils/TableGen/NeonEmitter.cpp
index a78ae9c..d243672 100644
--- a/utils/TableGen/NeonEmitter.cpp
+++ b/utils/TableGen/NeonEmitter.cpp
@@ -34,11 +34,11 @@
 #include "llvm/TableGen/Record.h"
 #include "llvm/TableGen/SetTheory.h"
 #include "llvm/TableGen/TableGenBackend.h"
-#include <string>
-#include <sstream>
-#include <vector>
-#include <map>
 #include <algorithm>
+#include <map>
+#include <sstream>
+#include <string>
+#include <vector>
 using namespace llvm;
 
 namespace {
@@ -1393,7 +1393,7 @@
     }
   }
 
-  assert(Lines.size() && "Empty def?");
+  assert(!Lines.empty() && "Empty def?");
   if (!RetVar.getType().isVoid())
     Lines.back().insert(0, RetVar.getName() + " = ");
 
diff --git a/www/analyzer/potential_checkers.html b/www/analyzer/potential_checkers.html
index 7ac8c5c..101e3c6 100644
--- a/www/analyzer/potential_checkers.html
+++ b/www/analyzer/potential_checkers.html
@@ -104,6 +104,32 @@
 </pre></div></div></td>
 <td class="aligned"></td></tr>
 
+<tr><td><div class="namedescr expandable"><span class="name">
+memory.ZeroAlloc</span><span class="lang">
+(C, C++)</span><div class="descr">
+Allocation of zero bytes.
+<br>Note: an enhancement to <span class="name">unix.Malloc</span>.
+<br>Note: <span class="name">unix.API</span> perform C-checks for zero 
+allocation. This should be moved to <span class="name">unix.Malloc</span>.
+<p>Source: C++03 3.7.3.1p2; C++11 3.7.4.1p2.</p></div></div></td>
+<td><div class="exampleContainer expandable">
+<div class="example"><pre>
+#include &lt;stdlib.h&gt;
+
+void test() {
+  int *p = malloc(0); // warn
+  free(p);
+}
+</pre></div>
+<div class="example"><pre>
+void test() {
+  int *p = new int[0]; // warn
+  delete[] p;
+}
+</pre></div></div></td>
+<td class="aligned"><a href="http://reviews.llvm.org/D6178">
+D6178</a></td></tr>
+
 </table>
 
 <!-- ======================= constructors/destructors ====================== -->
@@ -461,7 +487,7 @@
 <p>Source: C++03 3.7.3.1p2; C++11 3.7.4.1p2.</p></div></div></td>
 <td><div class="exampleContainer expandable">
 <div class="example"><pre>
-#include &lt;memory&gt;
+#include &lt;stdlib.h&gt;
 
 void test() {
   int *p = (int *)malloc(0);
diff --git a/www/cxx_dr_status.html b/www/cxx_dr_status.html
index 8b123ea..e70604f 100644
--- a/www/cxx_dr_status.html
+++ b/www/cxx_dr_status.html
@@ -1490,7 +1490,7 @@
   </tr>
   <tr class="open" id="242">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#242">242</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Interpretation of old-style casts</td>
     <td align="center">Not resolved</td>
   </tr>
@@ -1921,11 +1921,11 @@
     <td>Class with single conversion function to integral as array size in <TT>new</TT></td>
     <td class="full" align="center">Duplicate of <a href="#299">299</a> (C++11 onwards)</td>
   </tr>
-  <tr id="314">
+  <tr class="open" id="314">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#314">314</a></td>
-    <td>ready</td>
+    <td>review</td>
     <td><TT>template</TT> in base class specifier</td>
-    <td class="none" align="center">Duplicate of <a href="#1710">1710</a></td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr id="315">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#315">315</a></td>
@@ -2017,11 +2017,11 @@
     <td>Evaluation of friends of templates</td>
     <td class="full" align="center">Clang 3.5</td>
   </tr>
-  <tr class="open" id="330">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#330">330</a></td>
-    <td>open</td>
+  <tr id="330">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#330">330</a></td>
+    <td>DR</td>
     <td>Qualification conversions and pointers to arrays of pointers</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="331">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#331">331</a></td>
@@ -2095,11 +2095,11 @@
     <td>Terminology: "indirection" versus "dereference"</td>
     <td class="na" align="center">N/A</td>
   </tr>
-  <tr id="343">
+  <tr class="open" id="343">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#343">343</a></td>
-    <td>ready</td>
+    <td>review</td>
     <td>Make <TT>template</TT> optional in contexts that require a type</td>
-    <td class="none" align="center">No</td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr id="344">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#344">344</a></td>
@@ -2396,8 +2396,8 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="393">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#393">393</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#393">393</a></td>
+    <td>DR</td>
     <td>Pointer to array of unknown bound in template argument list in parameter</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -2663,7 +2663,7 @@
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#437">437</a></td>
     <td>CD1</td>
     <td>Is type of class allowed in member function exception specification?</td>
-    <td class="none" align="center">No</td>
+    <td class="none" align="center">Superseded by <a href="#1308">1308</a></td>
   </tr>
   <tr id="438">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#438">438</a></td>
@@ -3339,11 +3339,11 @@
     <td>Non-deducible parameters in partial specializations</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="550">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#550">550</a></td>
-    <td>open</td>
+  <tr id="550">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#550">550</a></td>
+    <td>dup</td>
     <td>Pointer to array of unknown bound in parameter declarations</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="551">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#551">551</a></td>
@@ -3365,7 +3365,7 @@
   </tr>
   <tr class="open" id="554">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#554">554</a></td>
-    <td>drafting</td>
+    <td>open</td>
     <td>Definition of &#8220;declarative region&#8221; and &#8220;scope&#8221;</td>
     <td align="center">Not resolved</td>
   </tr>
@@ -3586,8 +3586,8 @@
     <td class="full" align="center">Yes</td>
   </tr>
   <tr id="591">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#591">591</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#591">591</a></td>
+    <td>DR</td>
     <td>When a dependent base class is the current instantiation</td>
     <td class="none" align="center">No</td>
   </tr>
@@ -3694,8 +3694,8 @@
     <td class="full" align="center">Yes</td>
   </tr>
   <tr id="609">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#609">609</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#609">609</a></td>
+    <td>DR</td>
     <td>What is a &#8220;top-level&#8221; cv-qualifier?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -5613,11 +5613,11 @@
     <td>Nested types without linkage</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="967">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#967">967</a></td>
-    <td>open</td>
+  <tr id="967">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#967">967</a></td>
+    <td>NAD</td>
     <td>Exception specification of replacement allocation function</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="968">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#968">968</a></td>
@@ -5733,11 +5733,11 @@
     <td>Transitivity of <I>using-directive</I>s versus qualified lookup</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="987">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#987">987</a></td>
-    <td>open</td>
+  <tr id="987">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#987">987</a></td>
+    <td>DR</td>
     <td>Which declarations introduce namespace members?</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="988">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#988">988</a></td>
@@ -5937,11 +5937,11 @@
     <td>Implicitly-defined copy constructors and explicit base class constructors</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1021">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1021">1021</a></td>
-    <td>drafting</td>
+  <tr id="1021">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1021">1021</a></td>
+    <td>DR</td>
     <td>Definitions of namespace members</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1022">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1022">1022</a></td>
@@ -6099,11 +6099,11 @@
     <td>When is <TT>typeid</TT> value-dependent?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1048">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1048">1048</a></td>
-    <td>open</td>
+  <tr id="1048">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1048">1048</a></td>
+    <td>CD3</td>
     <td><TT>auto</TT> deduction and lambda return type deduction.</td>
-    <td align="center">Not resolved</td>
+    <td class="full" align="center">Clang 3.6</td>
   </tr>
   <tr class="open" id="1049">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1049">1049</a></td>
@@ -7535,7 +7535,7 @@
   </tr>
   <tr id="1287">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1287">1287</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Direct initialization vs &#8220;implicit&#8221; conversion in reference binding</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -7564,8 +7564,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1292">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1292">1292</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1292">1292</a></td>
+    <td>DR</td>
     <td>Dependent calls with <I>braced-init-list</I>s containing a pack expansion</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -7605,11 +7605,11 @@
     <td>Incorrect example in overload resolution</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1299">
+  <tr class="open" id="1299">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1299">1299</a></td>
-    <td>ready</td>
+    <td>drafting</td>
     <td>&#8220;Temporary objects&#8221; vs &#8220;temporary expressions&#8221;</td>
-    <td class="none" align="center">Unknown</td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr id="1300">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1300">1300</a></td>
@@ -7655,7 +7655,7 @@
   </tr>
   <tr id="1307">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1307">1307</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Overload resolution based on size of array <I>initializer-list</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -7665,11 +7665,11 @@
     <td>Completeness of class type within an <I>exception-specification</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1309">
+  <tr id="1309">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1309">1309</a></td>
-    <td>drafting</td>
+    <td>ready</td>
     <td>Incorrect note regarding lookup of a member of the current instantiation</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1310">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1310">1310</a></td>
@@ -7840,8 +7840,8 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1338">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1338">1338</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1338">1338</a></td>
+    <td>DR</td>
     <td>Aliasing and allocation functions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -7877,7 +7877,7 @@
   </tr>
   <tr id="1344">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1344">1344</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Adding new special member functions to a class via default arguments</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -7905,11 +7905,11 @@
     <td>Use of <TT>auto</TT> in a <I>trailing-return-type</I></td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1349">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1349">1349</a></td>
-    <td>drafting</td>
+  <tr id="1349">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1349">1349</a></td>
+    <td>dup</td>
     <td>Consistency of alias template redeclarations</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1350">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1350">1350</a></td>
@@ -7917,11 +7917,11 @@
     <td>Incorrect exception specification for inherited constructors</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1351">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1351">1351</a></td>
-    <td>review</td>
+  <tr id="1351">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1351">1351</a></td>
+    <td>DR</td>
     <td>Problems with implicitly-declared <I>exception-specification</I>s</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1352">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1352">1352</a></td>
@@ -7947,11 +7947,11 @@
     <td>Aggregates and &#8220;user-provided&#8221; constructors</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1356">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1356">1356</a></td>
-    <td>review</td>
+  <tr id="1356">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1356">1356</a></td>
+    <td>DR</td>
     <td>Exception specifications of copy assignment operators with virtual bases</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1357">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1357">1357</a></td>
@@ -8069,7 +8069,7 @@
   </tr>
   <tr id="1376">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1376">1376</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td><TT>static_cast</TT> of temporary to rvalue reference</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8194,8 +8194,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1397">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1397">1397</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1397">1397</a></td>
+    <td>DR</td>
     <td>Class completeness in non-static data member initializers</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8315,7 +8315,7 @@
   </tr>
   <tr id="1417">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1417">1417</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Pointers/references to functions with cv-qualifiers or <I>ref-qualifier</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8357,7 +8357,7 @@
   </tr>
   <tr id="1424">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1424">1424</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>When must sub-object destructors be accessible?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8459,7 +8459,7 @@
   </tr>
   <tr id="1441">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1441">1441</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Unclear wording for signal handler restrictions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8488,8 +8488,8 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1446">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1446">1446</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1446">1446</a></td>
+    <td>DR</td>
     <td>Member function with no <I>ref-qualifier</I> and non-member function with rvalue reference</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8573,7 +8573,7 @@
   </tr>
   <tr id="1460">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1460">1460</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>What is an empty union?</td>
     <td class="full" align="center">Clang 3.5</td>
   </tr>
@@ -8601,23 +8601,23 @@
     <td>Negative array bound in a <I>new-expression</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1465">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1465">1465</a></td>
-    <td>review</td>
+  <tr id="1465">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1465">1465</a></td>
+    <td>DR</td>
     <td><TT>noexcept</TT> and <TT>std::bad_array_new_length</TT></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1466">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1466">1466</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Visible sequences of side effects are redundant</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1467">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1467">1467</a></td>
-    <td>drafting</td>
+  <tr id="1467">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1467">1467</a></td>
+    <td>DR</td>
     <td>List-initialization of aggregate from same-type object</td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN (C++11 onwards)</td>
   </tr>
   <tr class="open" id="1468">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1468">1468</a></td>
@@ -8716,8 +8716,8 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1484">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1484">1484</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1484">1484</a></td>
+    <td>DR</td>
     <td>Unused local classes of function templates</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8751,11 +8751,11 @@
     <td>Is value-initialization of an array constant initialization?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1490">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1490">1490</a></td>
-    <td>drafting</td>
+  <tr id="1490">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1490">1490</a></td>
+    <td>DR</td>
     <td>List-initialization from a string literal</td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN (C++11 onwards)</td>
   </tr>
   <tr id="1491">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1491">1491</a></td>
@@ -8764,14 +8764,14 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1492">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1492">1492</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1492">1492</a></td>
+    <td>DR</td>
     <td>Exception specifications on template destructors</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1493">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1493">1493</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Criteria for move-construction</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8861,13 +8861,13 @@
   </tr>
   <tr id="1508">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1508">1508</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Template initializer-list constructors</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1509">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1509">1509</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Definition of &#8220;non-template function&#8221;</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -8897,7 +8897,7 @@
   </tr>
   <tr id="1514">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1514">1514</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Ambiguity between enumeration definition and zero-length bit-field</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9119,13 +9119,13 @@
   </tr>
   <tr id="1551">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1551">1551</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Wording problems in <I>using-declaration</I> specification</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1552">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1552">1552</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1552">1552</a></td>
+    <td>DR</td>
     <td><I>exception-specification</I>s and defaulted special member functions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9160,8 +9160,8 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1558">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1558">1558</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1558">1558</a></td>
+    <td>DR</td>
     <td>Unused arguments in alias template specializations</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9185,7 +9185,7 @@
   </tr>
   <tr id="1562">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1562">1562</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Non-static data member initializers and union <I>ctor-initializer</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9215,7 +9215,7 @@
   </tr>
   <tr id="1567">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1567">1567</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Inheriting constructors and copy/move constructors</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9227,31 +9227,31 @@
   </tr>
   <tr id="1569">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1569">1569</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Deducing a function parameter pack before ellipsis</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1570">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1570">1570</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Address of subobject as non-type template argument</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1571">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1571">1571</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1571">1571</a></td>
+    <td>DR</td>
     <td>cv-qualification for indirect reference binding via conversion function</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1572">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1572">1572</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1572">1572</a></td>
+    <td>DR</td>
     <td>Incorrect example for rvalue reference binding via conversion function</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1573">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1573">1573</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1573">1573</a></td>
+    <td>DR</td>
     <td>Inherited constructor characteristics</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9263,13 +9263,13 @@
   </tr>
   <tr id="1575">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1575">1575</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Incorrect definition of &#8220;strict pointer safety&#8221;</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1576">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1576">1576</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Discarded-value volatile xvalues</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9287,7 +9287,7 @@
   </tr>
   <tr id="1579">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1579">1579</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Return by converting move constructor</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9311,15 +9311,15 @@
   </tr>
   <tr id="1583">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1583">1583</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Incorrect example of unspecified behavior</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1584">
+  <tr class="open" id="1584">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584">1584</a></td>
-    <td>ready</td>
+    <td>open</td>
     <td>Deducing function types from cv-qualified types</td>
-    <td class="none" align="center">Unknown</td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr id="1585">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1585">1585</a></td>
@@ -9335,7 +9335,7 @@
   </tr>
   <tr id="1587">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1587">1587</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td><TT>constexpr</TT> initialization and nested anonymous unions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9345,33 +9345,33 @@
     <td>Deducing cv-qualified <TT>auto</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1589">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1589">1589</a></td>
-    <td>drafting</td>
+  <tr id="1589">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1589">1589</a></td>
+    <td>DR</td>
     <td>Ambiguous ranking of list-initialization sequences</td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN (C++11 onwards)</td>
   </tr>
   <tr class="open" id="1590">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1590">1590</a></td>
-    <td>review</td>
+    <td>drafting</td>
     <td>Bypassing non-copy/move constructor copying</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1591">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1591">1591</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1591">1591</a></td>
+    <td>DR</td>
     <td>Deducing array bound and element type from initializer list</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1592">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1592">1592</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>When do template parameters match?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1593">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1593">1593</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>&#8220;Parameter type&#8221; of special member functions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9383,13 +9383,13 @@
   </tr>
   <tr id="1595">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1595">1595</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Constructors &#8220;involved in&#8221; subobject initialization</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1596">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1596">1596</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1596">1596</a></td>
+    <td>DR</td>
     <td>Non-array objects as <TT>array[1]</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9401,7 +9401,7 @@
   </tr>
   <tr id="1598">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1598">1598</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Criterion for equality of pointers to members</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9412,14 +9412,14 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1600">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1600">1600</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1600">1600</a></td>
+    <td>DR</td>
     <td>Erroneous reference initialization in example</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1601">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1601">1601</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Promotion of enumeration with fixed underlying type</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9429,15 +9429,15 @@
     <td>Linkage of specialization vs linkage of template arguments</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1603">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1603">1603</a></td>
-    <td>review</td>
+  <tr id="1603">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1603">1603</a></td>
+    <td>DR</td>
     <td>Errors resulting from giving unnamed namespaces internal linkage</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1604">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1604">1604</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Double temporaries in reference initialization</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9455,13 +9455,13 @@
   </tr>
   <tr id="1607">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1607">1607</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Lambdas in template parameters</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1608">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1608">1608</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Operator lookup in trailing return type</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9479,31 +9479,31 @@
   </tr>
   <tr id="1611">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1611">1611</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Deleted default constructor for abstract class</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1612">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1612">1612</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Implicit lambda capture and anonymous unions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1613">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1613">1613</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Constant expressions and lambda capture</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1614">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1614">1614</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1614">1614</a></td>
+    <td>DR</td>
     <td>Address of pure virtual function vs odr-use</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1615">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1615">1615</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1615">1615</a></td>
+    <td>DR</td>
     <td>Alignment of types, variables, and members</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9521,7 +9521,7 @@
   </tr>
   <tr id="1618">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1618">1618</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Gratuitously-unsigned underlying enum type</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9587,21 +9587,21 @@
   </tr>
   <tr id="1629">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1629">1629</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Can a closure class be a literal type?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1630">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1630">1630</a></td>
-    <td>drafting</td>
+  <tr id="1630">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1630">1630</a></td>
+    <td>DR</td>
     <td>Multiple default constructor templates</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1631">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1631">1631</a></td>
-    <td>drafting</td>
+  <tr id="1631">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1631">1631</a></td>
+    <td>DR</td>
     <td>Incorrect overload resolution for single-element <I>initializer-list</I></td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN (C++11 onwards)</td>
   </tr>
   <tr class="open" id="1632">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1632">1632</a></td>
@@ -9609,11 +9609,11 @@
     <td>Lambda capture in member initializers</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1633">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1633">1633</a></td>
-    <td>review</td>
+  <tr id="1633">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1633">1633</a></td>
+    <td>DR</td>
     <td>Copy-initialization in member initialization</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1634">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1634">1634</a></td>
@@ -9645,11 +9645,11 @@
     <td>Declaring an explicit specialization of a scoped enumeration</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1639">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1639">1639</a></td>
-    <td>review</td>
+  <tr id="1639">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1639">1639</a></td>
+    <td>DR</td>
     <td><I>exception-specification</I>s and pointer/pointer-to-member expressions</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1640">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1640">1640</a></td>
@@ -9701,13 +9701,13 @@
   </tr>
   <tr id="1648">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1648">1648</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td><TT>thread_local</TT> vs block extern declarations</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1649">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1649">1649</a></td>
-    <td>DRWP</td>
+    <td>C++14</td>
     <td>Error in the syntax of <I>mem-initializer-list</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9717,18 +9717,18 @@
     <td>Class prvalues in reference initialization</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1651">
+  <tr class="open" id="1651">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1651">1651</a></td>
-    <td>ready</td>
-    <td>Lifetime extension of temporary via reference to subobject</td>
-    <td class="none" align="center">Unknown</td>
-  </tr>
-  <tr class="open" id="1652">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1652">1652</a></td>
     <td>drafting</td>
-    <td>Object addresses in <TT>constexpr</TT> expressions</td>
+    <td>Lifetime extension of temporary via reference to subobject</td>
     <td align="center">Not resolved</td>
   </tr>
+  <tr id="1652">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1652">1652</a></td>
+    <td>ready</td>
+    <td>Object addresses in <TT>constexpr</TT> expressions</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
   <tr class="open" id="1653">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1653">1653</a></td>
     <td>drafting</td>
@@ -9761,7 +9761,7 @@
   </tr>
   <tr id="1658">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1658">1658</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Deleted default constructor for abstract class via destructor</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9773,7 +9773,7 @@
   </tr>
   <tr id="1660">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1660">1660</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td><I>member-declaration</I> requirements and unnamed bit-fields</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9785,7 +9785,7 @@
   </tr>
   <tr id="1662">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1662">1662</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Capturing function parameter packs</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9797,7 +9797,7 @@
   </tr>
   <tr id="1664">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1664">1664</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Argument-dependent lookup of lambdas used in default arguments</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9809,7 +9809,7 @@
   </tr>
   <tr id="1666">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1666">1666</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Address constant expressions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9827,7 +9827,7 @@
   </tr>
   <tr id="1669">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1669">1669</a></td>
-    <td>accepted</td>
+    <td>C++14</td>
     <td><TT>auto</TT> return type for <TT>main</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9843,21 +9843,21 @@
     <td>Unclear rules for deduction with cv-qualification</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1672">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1672">1672</a></td>
-    <td>drafting</td>
+  <tr id="1672">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1672">1672</a></td>
+    <td>DR</td>
     <td>Layout compatibility with multiple empty bases</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1673">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1673">1673</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Clarifying overload resolution for the second step of copy-initialization</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1674">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1674">1674</a></td>
-    <td>accepted</td>
+    <td>C++14</td>
     <td>Return type deduction for address of function</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9899,7 +9899,7 @@
   </tr>
   <tr id="1681">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1681">1681</a></td>
-    <td>accepted</td>
+    <td>C++14</td>
     <td><I>init-capture</I>s and nested lambdas</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9917,9 +9917,9 @@
   </tr>
   <tr id="1684">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1684">1684</a></td>
-    <td>accepted</td>
+    <td>C++14</td>
     <td>Static <TT>constexpr</TT> member functions for non-literal classes</td>
-    <td class="none" align="center">Unknown</td>
+    <td class="full" align="center">Clang 3.6</td>
   </tr>
   <tr id="1685">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1685">1685</a></td>
@@ -9928,14 +9928,14 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1686">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1686">1686</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1686">1686</a></td>
+    <td>DR</td>
     <td>Which variables are &#8220;explicitly declared <TT>const</TT>?&#8221;</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1687">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1687">1687</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Conversions of operands of built-in operators</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -9947,51 +9947,51 @@
   </tr>
   <tr id="1689">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1689">1689</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Syntactic nonterminal for operand of <TT>alignas</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1690">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1690">1690</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Associated namespace for local type</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1691">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1691">1691</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Argument-dependent lookup and opaque enumerations</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1692">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1692">1692</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Associated namespaces of doubly-nested classes</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1693">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1693">1693</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Superfluous semicolons in class definitions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1694">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1694">1694</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1694">1694</a></td>
+    <td>DR</td>
     <td>Restriction on reference to temporary as a constant expression</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1695">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1695">1695</a></td>
-    <td>drafting</td>
+  <tr id="1695">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1695">1695</a></td>
+    <td>NAD</td>
     <td>Lifetime extension via <I>init-capture</I></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1696">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1696">1696</a></td>
-    <td>drafting</td>
+  <tr id="1696">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1696">1696</a></td>
+    <td>DR</td>
     <td>Temporary lifetime and non-static data member initializers</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1697">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1697">1697</a></td>
@@ -10042,8 +10042,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1705">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1705">1705</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1705">1705</a></td>
+    <td>DR</td>
     <td>Unclear specification of &#8220;more specialized&#8221;</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10055,15 +10055,15 @@
   </tr>
   <tr id="1707">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1707">1707</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td><TT>template</TT> in <I>elaborated-type-specifier</I> without <I>nested-name-specifier</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1708">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1708">1708</a></td>
-    <td>review</td>
+  <tr id="1708">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1708">1708</a></td>
+    <td>DR</td>
     <td>overly-strict requirements for names with C language linkage</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1709">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1709">1709</a></td>
@@ -10071,11 +10071,11 @@
     <td>Stringizing raw string literals containing newline</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr id="1710">
+  <tr class="open" id="1710">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1710">1710</a></td>
-    <td>ready</td>
+    <td>review</td>
     <td>Missing <TT>template</TT> keyword in <I>class-or-decltype</I></td>
-    <td class="none" align="center">Unknown</td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1711">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1711">1711</a></td>
@@ -10084,8 +10084,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1712">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1712">1712</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1712">1712</a></td>
+    <td>DR</td>
     <td><TT>constexpr</TT> variable template declarations</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10101,21 +10101,21 @@
     <td>odr-use of <TT>this</TT> from a local class</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1715">
+  <tr class="open" id="1715">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1715">1715</a></td>
-    <td>ready</td>
+    <td>drafting</td>
     <td>Access and inherited constructor templates</td>
-    <td class="none" align="center">Unknown</td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr id="1716">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1716">1716</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>When are default arguments evaluated?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1717">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1717">1717</a></td>
-    <td>accepted</td>
+    <td>C++14</td>
     <td>Missing specification of type of binary literal</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10125,11 +10125,11 @@
     <td>Macro invocation spanning end-of-file</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1719">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1719">1719</a></td>
-    <td>drafting</td>
+  <tr id="1719">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1719">1719</a></td>
+    <td>DR</td>
     <td>Layout compatibility and cv-qualification revisited</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1720">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1720">1720</a></td>
@@ -10205,7 +10205,7 @@
   </tr>
   <tr id="1732">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1732">1732</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Defining types in <I>condition</I>s and range-based <TT>for</TT> statements</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10235,31 +10235,31 @@
   </tr>
   <tr id="1737">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1737">1737</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Type dependence of call to a member of the current instantiation</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1738">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1738">1738</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Explicit instantiation/specialization of inheriting constructor templates</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1739">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1739">1739</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Conversion of floating point to enumeration</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1740">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1740">1740</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Disambiguation of <TT>noexcept</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1741">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1741">1741</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>odr-use of class object in lvalue-to-rvalue conversion</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10275,11 +10275,11 @@
     <td><I>init-capture</I>s in nested lambdas</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1744">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1744">1744</a></td>
-    <td>review</td>
+  <tr id="1744">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1744">1744</a></td>
+    <td>DR</td>
     <td>Unordered initialization for variable template specializations</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1745">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1745">1745</a></td>
@@ -10289,21 +10289,21 @@
   </tr>
   <tr id="1746">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1746">1746</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Are volatile scalar types trivially copyable?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1747">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1747">1747</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Constant initialization of reference to function</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1748">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1748">1748</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1748">1748</a></td>
+    <td>DR</td>
     <td>Placement new with a null pointer</td>
-    <td class="none" align="center">Unknown</td>
+    <td class="svn" align="center">SVN</td>
   </tr>
   <tr id="1749">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1749">1749</a></td>
@@ -10312,26 +10312,26 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1750">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1750">1750</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1750">1750</a></td>
+    <td>DR</td>
     <td>&#8220;Argument&#8221; vs &#8220;parameter&#8221;</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1751">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1751">1751</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1751">1751</a></td>
+    <td>DR</td>
     <td>Non-trivial operations vs non-trivial initialization</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1752">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1752">1752</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1752">1752</a></td>
+    <td>DR</td>
     <td>Right-recursion in <I>mem-initializer-list</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1753">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1753">1753</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1753">1753</a></td>
+    <td>DR</td>
     <td><I>decltype-specifier</I> in <I>nested-name-specifier</I> of destructor</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10347,33 +10347,33 @@
     <td>Out-of-class partial specializations of member templates</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1756">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1756">1756</a></td>
-    <td>review</td>
+  <tr id="1756">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1756">1756</a></td>
+    <td>DR</td>
     <td>Direct-list-initialization of a non-class object</td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN (C++11 onwards)</td>
   </tr>
   <tr id="1757">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1757">1757</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1757">1757</a></td>
+    <td>DR</td>
     <td>Const integral subobjects</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1758">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1758">1758</a></td>
-    <td>open</td>
+  <tr id="1758">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1758">1758</a></td>
+    <td>DR</td>
     <td>Explicit conversion in copy/move list initialization</td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN (C++11 onwards)</td>
   </tr>
   <tr id="1759">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1759">1759</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>UTF-8 code units in plain <TT>char</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1760">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1760">1760</a></td>
-    <td>accepted</td>
+    <td>C++14</td>
     <td>Access of member corresponding to <I>init-capture</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10385,7 +10385,7 @@
   </tr>
   <tr id="1762">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1762">1762</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Reserved identifier used in <I>literal-operator-id</I> example</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10397,25 +10397,25 @@
   </tr>
   <tr id="1764">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1764">1764</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Hiding of function from using-declaration by signature</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1765">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1765">1765</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Overflow of enumeration used as enumerator value</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1766">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1766">1766</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1766">1766</a></td>
+    <td>DR</td>
     <td>Values outside the range of the values of an enumeration</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1767">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1767">1767</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Scoped enumeration in a <TT>switch</TT> statement</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10427,13 +10427,13 @@
   </tr>
   <tr id="1769">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1769">1769</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Catching a base class of the exception object</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1770">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1770">1770</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Type matching of non-type template parameters and arguments</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10445,25 +10445,25 @@
   </tr>
   <tr id="1772">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1772">1772</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td><TT>__func__</TT> in a lambda body</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1773">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1773">1773</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Out-of-lifetime lvalue-to-rvalue conversion</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1774">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1774">1774</a></td>
-    <td>drafting</td>
+  <tr id="1774">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1774">1774</a></td>
+    <td>DR</td>
     <td>Discrepancy between subobject destruction and stack unwinding</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1775">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1775">1775</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Undefined behavior of line splice in raw string literal</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10474,26 +10474,26 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1777">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1777">1777</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1777">1777</a></td>
+    <td>DR</td>
     <td>Empty pack expansion in <I>dynamic-exception-specification</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1778">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1778">1778</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td><I>exception-specification</I> in explicitly-defaulted functions</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1779">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1779">1779</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1779">1779</a></td>
+    <td>DR</td>
     <td>Type dependency of <TT>__func__</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1780">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1780">1780</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1780">1780</a></td>
+    <td>DR</td>
     <td>Explicit instantiation/specialization of generic lambda <TT>operator()</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10504,8 +10504,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1782">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1782">1782</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1782">1782</a></td>
+    <td>DR</td>
     <td>Form of initialization for <TT>nullptr_t</TT> to <TT>bool</TT> conversion</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10529,21 +10529,21 @@
   </tr>
   <tr id="1786">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1786">1786</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Effect of merging allocations on memory leakage</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1787">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1787">1787</a></td>
-    <td>DR</td>
+    <td>C++14</td>
     <td>Uninitialized <TT>unsigned char</TT> values</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1788">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1788">1788</a></td>
-    <td>review</td>
+  <tr id="1788">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1788">1788</a></td>
+    <td>DR</td>
     <td>Sized deallocation of array of non-class type</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1789">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1789">1789</a></td>
@@ -10552,14 +10552,14 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1790">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1790">1790</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1790">1790</a></td>
+    <td>extension</td>
     <td>Ellipsis following function parameter pack</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1791">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1791">1791</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1791">1791</a></td>
+    <td>DR</td>
     <td>Incorrect restrictions on <I>cv-qualifier-seq</I> and <I>ref-qualifier</I></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10570,32 +10570,32 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1793">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1793">1793</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1793">1793</a></td>
+    <td>DR</td>
     <td><TT>thread_local</TT> in explicit specializations</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1794">
+  <tr class="open" id="1794">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1794">1794</a></td>
-    <td>ready</td>
+    <td>review</td>
     <td><TT>template</TT> keyword and alias templates</td>
-    <td class="none" align="center">Unknown</td>
-  </tr>
-  <tr class="open" id="1795">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1795">1795</a></td>
-    <td>drafting</td>
-    <td>Disambiguating <I>original-namespace-definition</I> and <I>extension-namespace-definition</I></td>
     <td align="center">Not resolved</td>
   </tr>
+  <tr id="1795">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1795">1795</a></td>
+    <td>DR</td>
+    <td>Disambiguating <I>original-namespace-definition</I> and <I>extension-namespace-definition</I></td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
   <tr id="1796">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1796">1796</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1796">1796</a></td>
+    <td>DR</td>
     <td>Is all-bits-zero for null characters a meaningful requirement?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1797">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1797">1797</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1797">1797</a></td>
+    <td>DR</td>
     <td>Are all bit patterns of <TT>unsigned char</TT> distinct numbers?</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10606,14 +10606,14 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1799">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1799">1799</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1799">1799</a></td>
+    <td>DR</td>
     <td><TT>mutable</TT> and non-explicit const qualification</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1800">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1800">1800</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1800">1800</a></td>
+    <td>DR</td>
     <td>Pointer to member of nested anonymous union</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10624,8 +10624,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1802">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1802">1802</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1802">1802</a></td>
+    <td>DR</td>
     <td><TT>char16_t</TT> string literals and surrogate pairs</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10636,26 +10636,26 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1804">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1804">1804</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1804">1804</a></td>
+    <td>DR</td>
     <td>Partial specialization and friendship</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1805">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1805">1805</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1805">1805</a></td>
+    <td>DR</td>
     <td>Conversions of array operands in <I>conditional-expression</I>s</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1806">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1806">1806</a></td>
-    <td>review</td>
+  <tr id="1806">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1806">1806</a></td>
+    <td>DR</td>
     <td>Virtual bases and move-assignment</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1807">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1807">1807</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1807">1807</a></td>
+    <td>DR</td>
     <td>Order of destruction of array elements after an exception</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10666,58 +10666,58 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1809">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1809">1809</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1809">1809</a></td>
+    <td>DR</td>
     <td>Narrowing and template argument deduction</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1810">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1810">1810</a></td>
-    <td>review</td>
+  <tr id="1810">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1810">1810</a></td>
+    <td>DR</td>
     <td>Invalid <I>ud-suffix</I>es</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1811">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1811">1811</a></td>
-    <td>tentatively ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1811">1811</a></td>
+    <td>DR</td>
     <td>Lookup of deallocation function in a virtual destructor definition</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1812">
+  <tr class="open" id="1812">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1812">1812</a></td>
-    <td>ready</td>
+    <td>review</td>
     <td>Omission of <TT>template</TT> in a <I>typename-specifier</I></td>
-    <td class="none" align="center">Unknown</td>
-  </tr>
-  <tr class="open" id="1813">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1813">1813</a></td>
-    <td>drafting</td>
-    <td>Direct vs indirect bases in standard-layout classes</td>
     <td align="center">Not resolved</td>
   </tr>
+  <tr id="1813">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1813">1813</a></td>
+    <td>DR</td>
+    <td>Direct vs indirect bases in standard-layout classes</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
   <tr id="1814">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1814">1814</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1814">1814</a></td>
+    <td>DR</td>
     <td>Default arguments in <I>lambda-expression</I>s</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1815">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1815">1815</a></td>
-    <td>drafting</td>
+  <tr id="1815">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1815">1815</a></td>
+    <td>DR</td>
     <td>Lifetime extension in aggregate initialization</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1816">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1816">1816</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1816">1816</a></td>
+    <td>DR</td>
     <td>Unclear specification of bit-field values</td>
     <td class="none" align="center">Unknown</td>
   </tr>
-  <tr id="1817">
+  <tr class="open" id="1817">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1817">1817</a></td>
-    <td>ready</td>
+    <td>drafting</td>
     <td>Linkage specifications and nested scopes</td>
-    <td class="none" align="center">Unknown</td>
+    <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1818">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1818">1818</a></td>
@@ -10725,11 +10725,11 @@
     <td>Visibility and inherited language linkage</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1819">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1819">1819</a></td>
-    <td>review</td>
+  <tr id="1819">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1819">1819</a></td>
+    <td>DR</td>
     <td>Acceptable scopes for definition of partial specialization</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1820">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1820">1820</a></td>
@@ -10749,15 +10749,15 @@
     <td>Lookup of parameter names in <I>lambda-expression</I>s</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1823">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1823">1823</a></td>
-    <td>review</td>
+  <tr id="1823">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1823">1823</a></td>
+    <td>DR</td>
     <td>String literal uniqueness in inline functions</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1824">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1824">1824</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1824">1824</a></td>
+    <td>DR</td>
     <td>Completeness of return type vs point of instantiation</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10792,8 +10792,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1830">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1830">1830</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1830">1830</a></td>
+    <td>DR</td>
     <td>Repeated specifiers</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10804,8 +10804,8 @@
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1832">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1832">1832</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1832">1832</a></td>
+    <td>DR</td>
     <td>Casting to incomplete enumeration</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10816,8 +10816,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1834">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1834">1834</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1834">1834</a></td>
+    <td>DR</td>
     <td>Constant initialization binding a reference to an xvalue</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10839,11 +10839,11 @@
     <td>Use of <TT>this</TT> in <TT>friend</TT> and local class declarations</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1838">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1838">1838</a></td>
-    <td>drafting</td>
+  <tr id="1838">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1838">1838</a></td>
+    <td>DR</td>
     <td>Definition via <I>unqualified-id</I> and <I>using-declaration</I></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1839">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1839">1839</a></td>
@@ -10870,8 +10870,8 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1843">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1843">1843</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1843">1843</a></td>
+    <td>DR</td>
     <td>Bit-field in conditional operator with <TT>throw</TT> operand</td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10887,11 +10887,11 @@
     <td>Point of instantiation of a variable template specialization</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1846">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1846">1846</a></td>
-    <td>review</td>
+  <tr id="1846">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1846">1846</a></td>
+    <td>DR</td>
     <td>Declaring explicitly-defaulted implicitly-deleted functions</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1847">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1847">1847</a></td>
@@ -10899,11 +10899,11 @@
     <td>Clarifying compatibility during partial ordering</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1848">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1848">1848</a></td>
-    <td>open</td>
+  <tr id="1848">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1848">1848</a></td>
+    <td>DR</td>
     <td>Parenthesized constructor and destructor declarators</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1849">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1849">1849</a></td>
@@ -10912,20 +10912,20 @@
     <td align="center">Not resolved</td>
   </tr>
   <tr id="1850">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1850">1850</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1850">1850</a></td>
+    <td>DR</td>
     <td>Differences between definition context and point of instantiation</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1851">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1851">1851</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1851">1851</a></td>
+    <td>DR</td>
     <td><TT>decltype(auto)</TT> in <I>new-expression</I>s</td>
     <td class="none" align="center">Unknown</td>
   </tr>
   <tr id="1852">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1852">1852</a></td>
-    <td>ready</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1852">1852</a></td>
+    <td>DR</td>
     <td>Wording issues regarding <TT>decltype(auto)</TT></td>
     <td class="none" align="center">Unknown</td>
   </tr>
@@ -10937,15 +10937,15 @@
   </tr>
   <tr class="open" id="1854">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1854">1854</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Disallowing use of implicitly-deleted functions</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1855">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1855">1855</a></td>
-    <td>open</td>
+  <tr id="1855">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1855">1855</a></td>
+    <td>dup</td>
     <td>Out-of-lifetime access to nonstatic data members</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1856">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1856">1856</a></td>
@@ -10955,195 +10955,195 @@
   </tr>
   <tr class="open" id="1857">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1857">1857</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Additional questions about bits</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1858">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1858">1858</a></td>
-    <td>open</td>
+  <tr id="1858">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1858">1858</a></td>
+    <td>DR</td>
     <td>Comparing pointers to union members</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1859">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1859">1859</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>UTF-16 in <TT>char16_t</TT> string literals</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1860">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1860">1860</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>What is a &#8220;direct member?&#8221;</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1861">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1861">1861</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Values of a bit-field</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1862">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1862">1862</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Determining &#8220;corresponding members&#8221; for friendship</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1863">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1863">1863</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Requirements on thrown object type to support <TT>std::current_exception()</TT></td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1864">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1864">1864</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1864">1864</a></td>
+    <td>extension</td>
     <td>List-initialization of array objects</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1865">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1865">1865</a></td>
-    <td>open</td>
+  <tr id="1865">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1865">1865</a></td>
+    <td>DR</td>
     <td>Pointer arithmetic and multi-level qualification conversions</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1866">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1866">1866</a></td>
-    <td>open</td>
+  <tr id="1866">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1866">1866</a></td>
+    <td>DR</td>
     <td>Initializing variant members with non-trivial destructors</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1867">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1867">1867</a></td>
-    <td>open</td>
+  <tr id="1867">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1867">1867</a></td>
+    <td>NAD</td>
     <td>Function/expression ambiguity with qualified parameter name</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1868">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1868">1868</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Meaning of &#8220;placeholder type&#8221;</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1869">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1869">1869</a></td>
-    <td>open</td>
+  <tr id="1869">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1869">1869</a></td>
+    <td>NAD</td>
     <td><TT>thread_local</TT> vs <I>linkage-specification</I>s</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1870">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1870">1870</a></td>
-    <td>open</td>
+  <tr id="1870">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1870">1870</a></td>
+    <td>DR</td>
     <td>Contradictory wording about definitions vs explicit specialization/instantiation</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1871">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1871">1871</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1871">1871</a></td>
+    <td>extension</td>
     <td>Non-identifier characters in <I>ud-suffix</I></td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1872">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1872">1872</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Instantiations of <TT>constexpr</TT> templates that cannot appear in constant expressions</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1873">
+  <tr id="1873">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1873">1873</a></td>
-    <td>open</td>
+    <td>ready</td>
     <td>Protected member access from derived class friends</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1874">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1874">1874</a></td>
-    <td>open</td>
+  <tr id="1874">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1874">1874</a></td>
+    <td>DR</td>
     <td>Type vs non-type template parameters with <TT>class</TT> keyword</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1875">
+  <tr id="1875">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1875">1875</a></td>
-    <td>open</td>
+    <td>ready</td>
     <td>Reordering declarations in class scope</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1876">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1876">1876</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1876">1876</a></td>
+    <td>extension</td>
     <td>Preventing explicit specialization</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1877">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1877">1877</a></td>
-    <td>open</td>
+  <tr id="1877">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1877">1877</a></td>
+    <td>DR</td>
     <td>Return type deduction from <TT>return</TT> with no operand</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1878">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1878">1878</a></td>
-    <td>open</td>
+  <tr id="1878">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1878">1878</a></td>
+    <td>DR</td>
     <td><TT>operator auto</TT> template</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1879">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1879">1879</a></td>
-    <td>open</td>
+  <tr id="1879">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1879">1879</a></td>
+    <td>NAD</td>
     <td>Inadequate definition of alignment requirement</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1880">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1880">1880</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>When are parameter objects destroyed?</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1881">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1881">1881</a></td>
-    <td>open</td>
+  <tr id="1881">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1881">1881</a></td>
+    <td>DR</td>
     <td>Standard-layout classes and unnamed bit-fields</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1882">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1882">1882</a></td>
-    <td>open</td>
+  <tr id="1882">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1882">1882</a></td>
+    <td>DR</td>
     <td>Reserved names without library use</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1883">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1883">1883</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Protected access to constructors in <I>mem-initializer</I>s</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1884">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1884">1884</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Unclear requirements for same-named external-linkage entities</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1885">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1885">1885</a></td>
-    <td>open</td>
+  <tr id="1885">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1885">1885</a></td>
+    <td>DR</td>
     <td>Return value of a function is underspecified</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1886">
+  <tr id="1886">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1886">1886</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Language linkage for <TT>main()</TT></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1887">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1887">1887</a></td>
-    <td>open</td>
+  <tr id="1887">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1887">1887</a></td>
+    <td>DR</td>
     <td>Problems with <TT>::</TT> as <I>nested-name-specifier</I></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1888">
+  <tr id="1888">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1888">1888</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Implicitly-declared default constructors and <TT>explicit</TT></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1889">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1889">1889</a></td>
@@ -11153,26 +11153,26 @@
   </tr>
   <tr class="open" id="1890">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1890">1890</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Member type depending on definition of member function</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1891">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1891">1891</a></td>
-    <td>open</td>
+  <tr id="1891">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1891">1891</a></td>
+    <td>DR</td>
     <td>Move constructor/assignment for closure class</td>
-    <td align="center">Not resolved</td>
+    <td class="full" align="center">Clang 3.6</td>
   </tr>
-  <tr class="open" id="1892">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1892">1892</a></td>
-    <td>open</td>
+  <tr id="1892">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1892">1892</a></td>
+    <td>DR</td>
     <td>Use of <TT>auto</TT> in function type</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1893">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1893">1893</a></td>
-    <td>open</td>
-    <td>Function-syle cast with <I>braced-init-list</I>s and empty pack expansions</td>
+    <td>drafting</td>
+    <td>Function-style cast with <I>braced-init-list</I>s and empty pack expansions</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1894">
@@ -11183,51 +11183,51 @@
   </tr>
   <tr class="open" id="1895">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1895">1895</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Deleted conversions in conditional operator operands</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1896">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1896">1896</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Repeated alias templates</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1897">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1897">1897</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>ODR vs alternative tokens</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1898">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1898">1898</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Use of &#8220;equivalent&#8221; in overload resolution</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1899">
+  <tr id="1899">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1899">1899</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Value-dependent constant expressions</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1900">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1900">1900</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Do <TT>friend</TT> declarations count as &#8220;previous declarations&#8221;?</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1901">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1901">1901</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td><I>punctuator</I> referenced but not defined</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1902">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1902">1902</a></td>
-    <td>open</td>
+  <tr id="1902">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1902">1902</a></td>
+    <td>DR</td>
     <td>What makes a conversion &#8220;otherwise ill-formed&#8221;?</td>
-    <td align="center">Not resolved</td>
+    <td class="svn" align="center">SVN</td>
   </tr>
   <tr class="open" id="1903">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1903">1903</a></td>
@@ -11235,21 +11235,21 @@
     <td>What declarations are introduced by a non-member <I>using-declaration</I>?</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1904">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1904">1904</a></td>
-    <td>open</td>
+  <tr id="1904">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1904">1904</a></td>
+    <td>NAD</td>
     <td>Default template arguments for members of class templates</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1905">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1905">1905</a></td>
-    <td>open</td>
+  <tr id="1905">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/">1905</a></td>
+    <td>MAD</td>
     <td>Dependent types and injected-class-names</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1906">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1906">1906</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Name lookup in member <TT>friend</TT> declaration</td>
     <td align="center">Not resolved</td>
   </tr>
@@ -11261,61 +11261,61 @@
   </tr>
   <tr class="open" id="1908">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1908">1908</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Dual destructor lookup and <I>template-id</I>s</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1909">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1909">1909</a></td>
-    <td>open</td>
+  <tr id="1909">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1909">1909</a></td>
+    <td>DR</td>
     <td>Member class template with the same name as the class</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1910">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1910">1910</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>&#8220;Shall&#8221; requirement applied to runtime behavior</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1911">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1911">1911</a></td>
-    <td>open</td>
+  <tr id="1911">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1911">1911</a></td>
+    <td>DR</td>
     <td><TT>constexpr</TT> constructor with non-literal base class</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1912">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1912">1912</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1912">1912</a></td>
+    <td>extension</td>
     <td><I>exception-specification</I> of defaulted function</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1913">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1913">1913</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td><TT>decltype((x))</TT> in <I>lambda-expression</I>s</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1914">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1914">1914</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1914">1914</a></td>
+    <td>extension</td>
     <td>Duplicate standard attributes</td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1915">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1915">1915</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1915">1915</a></td>
+    <td>extension</td>
     <td>Potentially-invoked destructors in non-throwing constructors</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1916">
+  <tr id="1916">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1916">1916</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>&#8220;Same cv-unqualified type&#8221;</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1917">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1917">1917</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>decltype-qualified enumeration names</td>
     <td align="center">Not resolved</td>
   </tr>
@@ -11331,53 +11331,53 @@
     <td>Overload resolution for <TT>!</TT> with explicit conversion operator</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1920">
+  <tr id="1920">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1920">1920</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Qualification mismatch in <I>pseudo-destructor-name</I></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1921">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1921">1921</a></td>
-    <td>open</td>
+  <tr id="1921">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1921">1921</a></td>
+    <td>NAD</td>
     <td><TT>constexpr</TT> constructors and point of initialization of <TT>const</TT> variables</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1922">
+  <tr id="1922">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1922">1922</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Injected class template names and default arguments</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1923">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1923">1923</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1923">1923</a></td>
+    <td>extension</td>
     <td>Lvalues of type <TT>void</TT></td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1924">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1924">1924</a></td>
-    <td>open</td>
+    <td>drafting</td>
     <td>Definition of &#8220;literal&#8221; and kinds of literals</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1925">
+  <tr id="1925">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1925">1925</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Bit-field prvalues</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1926">
+  <tr id="1926">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1926">1926</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td>Potential results of subscript operator</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
-  <tr class="open" id="1927">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1927">1927</a></td>
-    <td>open</td>
+  <tr id="1927">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1927">1927</a></td>
+    <td>dup</td>
     <td>Lifetime of temporaries in <I>init-capture</I>s</td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1928">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1928">1928</a></td>
@@ -11385,24 +11385,648 @@
     <td>Triviality of deleted special member functions</td>
     <td align="center">Not resolved</td>
   </tr>
-  <tr class="open" id="1929">
+  <tr id="1929">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1929">1929</a></td>
-    <td>open</td>
+    <td>tentatively ready</td>
     <td><TT>template</TT> keyword following namespace <I>nested-name-specifier</I></td>
-    <td align="center">Not resolved</td>
+    <td class="none" align="center">Unknown</td>
   </tr>
   <tr class="open" id="1930">
     <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1930">1930</a></td>
-    <td>open</td>
+    <td>review</td>
     <td><I>init-declarator-list</I> vs <I>member-declarator-list</I></td>
     <td align="center">Not resolved</td>
   </tr>
   <tr class="open" id="1931">
-    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1931">1931</a></td>
-    <td>open</td>
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1931">1931</a></td>
+    <td>extension</td>
     <td>Default-constructible and copy-assignable closure types</td>
     <td align="center">Not resolved</td>
   </tr>
+  <tr class="open" id="1932">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1932">1932</a></td>
+    <td>drafting</td>
+    <td>Bit-field results of conditional operators</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1933">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1933">1933</a></td>
+    <td>NAD</td>
+    <td>Implementation limit for <I>initializer-list</I> elements</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1934">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1934">1934</a></td>
+    <td>extension</td>
+    <td>Relaxing <I>exception-specification</I> compatibility requirements</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1935">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1935">1935</a></td>
+    <td>drafting</td>
+    <td>Reuse of placement arguments in deallocation</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1936">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1936">1936</a></td>
+    <td>drafting</td>
+    <td>Dependent <I>qualified-id</I>s</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1937">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1937">1937</a></td>
+    <td>drafting</td>
+    <td>Incomplete specification of function pointer from lambda</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1938">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1938">1938</a></td>
+    <td>drafting</td>
+    <td>Should hosted/freestanding be implementation-defined?</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1939">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1939">1939</a></td>
+    <td>drafting</td>
+    <td>Argument conversions to nondeduced parameter types revisited</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1940">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1940">1940</a></td>
+    <td>DR</td>
+    <td><TT>static_assert</TT> in anonymous unions</td>
+    <td class="full" align="center">Yes</td>
+  </tr>
+  <tr class="open" id="1941">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1941">1941</a></td>
+    <td>drafting</td>
+    <td>SFINAE and inherited constructor default arguments</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1942">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1942">1942</a></td>
+    <td>tentatively ready</td>
+    <td>Incorrect reference to <I>trailing-return-type</I></td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1943">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1943">1943</a></td>
+    <td>open</td>
+    <td>Unspecified meaning of &#8220;bit&#8221;</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1944">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1944">1944</a></td>
+    <td>open</td>
+    <td>New C incompatibilities</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1945">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1945">1945</a></td>
+    <td>open</td>
+    <td>Friend declarations naming members of class templates in non-templates</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1946">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1946">1946</a></td>
+    <td>open</td>
+    <td><I>exception-specification</I>s vs pointer dereference</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1947">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1947">1947</a></td>
+    <td>NAD</td>
+    <td>Digit separators following non-octal prefix</td>
+    <td class="full" align="center">Yes</td>
+  </tr>
+  <tr id="1948">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1948">1948</a></td>
+    <td>NAD</td>
+    <td><I>exception-specification</I> of replacement global <TT>new</TT></td>
+    <td class="full" align="center">Yes</td>
+  </tr>
+  <tr class="open" id="1949">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1949">1949</a></td>
+    <td>drafting</td>
+    <td>&#8220;sequenced after&#8221; instead of &#8220;sequenced before&#8221;</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1950">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1950">1950</a></td>
+    <td>NAD</td>
+    <td>Restructuring description of ranks of conversion sequences</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1951">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1951">1951</a></td>
+    <td>drafting</td>
+    <td>Cv-qualification and literal types</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1952">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1952">1952</a></td>
+    <td>drafting</td>
+    <td>Constant expressions and library undefined behavior</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1953">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1953">1953</a></td>
+    <td>open</td>
+    <td>Data races and common initial sequence</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1954">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1954">1954</a></td>
+    <td>open</td>
+    <td><TT>typeid</TT> null dereference check in subexpressions</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1955">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1955">1955</a></td>
+    <td>review</td>
+    <td><TT>#elif</TT> with invalid controlling expression</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1956">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1956">1956</a></td>
+    <td>tentatively ready</td>
+    <td>Reuse of storage of automatic variables</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1957">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1957">1957</a></td>
+    <td>extension</td>
+    <td><TT>decltype(auto)</TT> with direct-list-initialization</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1958">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1958">1958</a></td>
+    <td>drafting</td>
+    <td><TT>decltype(auto)</TT> with parenthesized initializer</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1959">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1959">1959</a></td>
+    <td>drafting</td>
+    <td>Inadvertently inherited copy constructor</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1960">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1960">1960</a></td>
+    <td>NAD</td>
+    <td>Visibility of entity named in class-scope <I>using-declaration</I></td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1961">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1961">1961</a></td>
+    <td>concurrency</td>
+    <td>Potentially-concurrent actions within a signal handler</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1962">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1962">1962</a></td>
+    <td>open</td>
+    <td>Type of <TT>__func__</TT></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1963">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1963">1963</a></td>
+    <td>drafting</td>
+    <td>Implementation-defined identifier characters</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1964">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1964">1964</a></td>
+    <td>NAD</td>
+    <td><I>opaque-enum-declaration</I> in <I>alias-declaration</I>?</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1965">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1965">1965</a></td>
+    <td>open</td>
+    <td>Explicit casts to reference types</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1966">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1966">1966</a></td>
+    <td>drafting</td>
+    <td>Colon following enumeration <I>elaborated-type-specifier</I></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1967">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1967">1967</a></td>
+    <td>drafting</td>
+    <td>Temporary lifetime and move-elision</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1968">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1968">1968</a></td>
+    <td>NAD</td>
+    <td>Address of <TT>typeid</TT> in constant expressions</td>
+    <td class="full" align="center">Yes</td>
+  </tr>
+  <tr class="open" id="1969">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1969">1969</a></td>
+    <td>open</td>
+    <td>Missing exclusion of <TT>~S</TT> as an ordinary function name</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1970">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1970">1970</a></td>
+    <td>NAD</td>
+    <td>Ambiguity resolution for <TT>(T())*x</TT></td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr id="1971">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1971">1971</a></td>
+    <td>tentatively ready</td>
+    <td>Unclear disambiguation of destructor and <TT>operator~</TT></td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1972">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1972">1972</a></td>
+    <td>open</td>
+    <td>Identifier character restrictions in non-<I>identifier</I>s</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1973">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1973">1973</a></td>
+    <td>drafting</td>
+    <td>Which <I>parameter-declaration-clause</I> in a <I>lambda-expression</I>?</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1974">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1974">1974</a></td>
+    <td>open</td>
+    <td>Redundant specification of non-type <I>typename-specifier</I></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1975">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1975">1975</a></td>
+    <td>drafting</td>
+    <td>Permissible declarations for <I>exception-specification</I>s</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1976">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1976">1976</a></td>
+    <td>NAD</td>
+    <td>Ambiguity of <I>namespace-alias</I>es</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1977">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1977">1977</a></td>
+    <td>drafting</td>
+    <td>Contradictory results of failed destructor lookup</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1978">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1978">1978</a></td>
+    <td>drafting</td>
+    <td>Redundant description of explicit constructor use</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1979">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1979">1979</a></td>
+    <td>open</td>
+    <td>Alias template specialization in template member definition</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1980">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1980">1980</a></td>
+    <td>drafting</td>
+    <td>Equivalent but not functionally-equivalent redeclarations</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1981">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1981">1981</a></td>
+    <td>drafting</td>
+    <td>Implicit contextual conversions and <TT>explicit</TT></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1982">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1982">1982</a></td>
+    <td>NAD</td>
+    <td>Deduction extending parameter pack</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1983">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1983">1983</a></td>
+    <td>drafting</td>
+    <td>Inappropriate use of <I>virt-specifier</I></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1984">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1984">1984</a></td>
+    <td>NAD</td>
+    <td>Lossless narrowing conversions</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr id="1985">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1985">1985</a></td>
+    <td>NAD</td>
+    <td>Unknown bound array member with <I>brace-or-equal-initializer</I></td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr id="1986">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1986">1986</a></td>
+    <td>ready</td>
+    <td>odr-use and delayed initialization</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr id="1987">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1987">1987</a></td>
+    <td>NAD</td>
+    <td><TT>constexpr</TT> static data members across translation units</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1988">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1988">1988</a></td>
+    <td>drafting</td>
+    <td>Ambiguity between dependent and non-dependent bases in implicit member access</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1989">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1989">1989</a></td>
+    <td>drafting</td>
+    <td>Insufficient restrictions on parameters of postfix operators</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1990">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1990">1990</a></td>
+    <td>drafting</td>
+    <td>Ambiguity due to optional <I>decl-specifier-seq</I></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1991">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1991">1991</a></td>
+    <td>open</td>
+    <td>Inheriting constructors vs default arguments</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1992">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1992">1992</a></td>
+    <td>drafting</td>
+    <td><TT>new (std::nothrow) int[N]</TT> can throw</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1993">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1993">1993</a></td>
+    <td>open</td>
+    <td>Use of <TT>template&lt;&gt;</TT> defining member of explicit specialization</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1994">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1994">1994</a></td>
+    <td>dup</td>
+    <td>Confusing wording regarding multiple <TT>template&lt;&gt;</TT> prefixes</td>
+    <td class="none" align="center">Duplicate of <a href="#529">529</a></td>
+  </tr>
+  <tr class="open" id="1995">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1995">1995</a></td>
+    <td>open</td>
+    <td><I>exception-specification</I>s and non-type template parameters</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1996">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1996">1996</a></td>
+    <td>open</td>
+    <td>Reference list-initialization ignores conversion functions</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="1997">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1997">1997</a></td>
+    <td>drafting</td>
+    <td>Placement new and previous initialization</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="1998">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1998">1998</a></td>
+    <td>NAD</td>
+    <td>Additional sources of xvalue expressions</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="1999">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1999">1999</a></td>
+    <td>drafting</td>
+    <td>Representation of source characters as universal-character-names</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2000">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2000">2000</a></td>
+    <td>drafting</td>
+    <td><I>header-name</I> outside <TT>#include</TT> directive</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2001">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2001">2001</a></td>
+    <td>drafting</td>
+    <td><I>non-directive</I> is underspecified</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2002">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2002">2002</a></td>
+    <td>open</td>
+    <td>White space within preprocessing directives</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2003">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2003">2003</a></td>
+    <td>drafting</td>
+    <td>Zero-argument macros incorrectly specified</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2004">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2004">2004</a></td>
+    <td>drafting</td>
+    <td>Unions with mutable members in constant expressions</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="2005">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#2005">2005</a></td>
+    <td>NAD</td>
+    <td>Incorrect <TT>constexpr</TT> reference initialization requirements</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="2006">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2006">2006</a></td>
+    <td>drafting</td>
+    <td>Cv-qualified <TT>void</TT> types</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2007">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2007">2007</a></td>
+    <td>drafting</td>
+    <td>Argument-dependent lookup for <TT>operator=</TT></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2008">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2008">2008</a></td>
+    <td>review</td>
+    <td>Default <I>template-argument</I>s underspecified</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2009">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2009">2009</a></td>
+    <td>open</td>
+    <td>Unclear specification of class scope</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2010">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2010">2010</a></td>
+    <td>open</td>
+    <td><I>exception-specification</I>s and conversion operators</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2011">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2011">2011</a></td>
+    <td>review</td>
+    <td>Unclear effect of reference capture of reference</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2012">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2012">2012</a></td>
+    <td>open</td>
+    <td>Lifetime of references</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2013">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2013">2013</a></td>
+    <td>drafting</td>
+    <td>Pointer subtraction in large array</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="2014">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#2014">2014</a></td>
+    <td>NAD</td>
+    <td>Unneeded deallocation signatures</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="2015">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2015">2015</a></td>
+    <td>drafting</td>
+    <td>odr-use of deleted virtual functions</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2016">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2016">2016</a></td>
+    <td>drafting</td>
+    <td>Confusing wording in description of conversion function</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2017">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2017">2017</a></td>
+    <td>drafting</td>
+    <td>Flowing off end is not equivalent to no-expression return</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2018">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2018">2018</a></td>
+    <td>open</td>
+    <td>Qualification conversion vs reference binding</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2019">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2019">2019</a></td>
+    <td>drafting</td>
+    <td>Member references omitted from description of storage duration</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2020">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2020">2020</a></td>
+    <td>drafting</td>
+    <td>Inadequate description of odr-use of implicitly-invoked functions</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="2021">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#2021">2021</a></td>
+    <td>dup</td>
+    <td>Function template redeclaration via alias template</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="2022">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2022">2022</a></td>
+    <td>drafting</td>
+    <td>Copy elision in constant expressions</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2023">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2023">2023</a></td>
+    <td>open</td>
+    <td>Composite reference result type of conditional operator</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2024">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2024">2024</a></td>
+    <td>open</td>
+    <td>Dependent types and unexpanded parameter packs</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2025">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2025">2025</a></td>
+    <td>open</td>
+    <td>Declaration matching via alias templates</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2026">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2026">2026</a></td>
+    <td>drafting</td>
+    <td>Zero-initialization and <TT>constexpr</TT></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2027">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2027">2027</a></td>
+    <td>drafting</td>
+    <td>Unclear requirements for multiple <TT>alignas</TT> specifiers</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2028">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2028">2028</a></td>
+    <td>drafting</td>
+    <td>Converting constructors in rvalue reference initialization</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr id="2029">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#2029">2029</a></td>
+    <td>dup</td>
+    <td>Abstract class return type in <TT>decltype</TT> operand</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr id="2030">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#2030">2030</a></td>
+    <td>NAD</td>
+    <td>Access of injected-class-name with template arguments</td>
+    <td class="none" align="center">Unknown</td>
+  </tr>
+  <tr class="open" id="2031">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2031">2031</a></td>
+    <td>drafting</td>
+    <td>Missing incompatibility for <TT>&amp;&amp;</TT></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2032">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2032">2032</a></td>
+    <td>open</td>
+    <td>Default <I>template-argument</I>s of variable templates</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2033">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2033">2033</a></td>
+    <td>open</td>
+    <td>Redundant restriction on partial specialization argument</td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2034">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2034">2034</a></td>
+    <td>open</td>
+    <td>Deprecating <TT>uncaught_exception()</TT></td>
+    <td align="center">Not resolved</td>
+  </tr>
+  <tr class="open" id="2035">
+    <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2035">2035</a></td>
+    <td>open</td>
+    <td>Multi-section example is confusing</td>
+    <td align="center">Not resolved</td>
+  </tr>
 </table>
 
 </div>
diff --git a/www/cxx_status.html b/www/cxx_status.html
index cdb05a1..4c767d1 100644
--- a/www/cxx_status.html
+++ b/www/cxx_status.html
@@ -447,7 +447,7 @@
     <tr>
       <td>Binary literals</td>
       <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3472.pdf">N3472</a></td>
-      <td class="full" align="center">Yes</td>
+      <td class="full" align="center">Clang 2.9</td>
     </tr>
     <tr>
       <td>decltype(auto)</td>
@@ -501,9 +501,19 @@
     <tr>
       <td>C++ Sized Deallocation</td>
       <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3778.html">N3778</a></td>
-      <td class="full" align="center">Clang 3.4</td>
+      <td class="full" align="center">Clang 3.4 <a href="#n3778">(6)</a></td>
     </tr>
 </table>
+<p>
+<span id="n3778">(6): In Clang SVN, using sized deallocation in C++14 mode requires linking either
+libc++ 3.7 or later, or libstdc++ 5 or later. Alternatively, you can use the
+<code>-Xclang -fdefine-sized-deallocation</code> compiler option to enable the implementation from
+Clang 3.4 through Clang 3.6, where weak definitions of sized deallocation functions are implicitly
+generated (by the compiler). You can also use the <code>-Xclang -fno-sized-deallocation</code> option 
+to disable sized deallocation. Note that both of these flags are temporary provisions and may go away
+soon.
+</span>
+</p>
 
 <h2 id="cxx17">C++1z implementation status</h2>
 
@@ -533,39 +543,54 @@
     <!-- Rapperswil papers -->
     <tr>
       <td>Disabling trigraph expansion by default</td>
-      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3981.html">N3981</a></td>
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4086.html">N4086</a></td>
       <td class="full" align="center">Clang 3.5</td>
     </tr>
+    <!--
+    <tr>
+      <td rowspan="2">Terse range-based for loops (removed from C++1z)</td>
+      <td rowspan="2"><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3994.htm">N3994</a></td>
+      <td class="none" align="center">Clang 3.5: Yes</td>
+    </tr>
     <tr>
-      <td>Terse range-based for loops</td>
-      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3994.htm">N3994</a></td>
-      <td class="full" align="center">Clang 3.5</td>
+      <td class="svn" align="center">SVN: No</td>
     </tr>
+    -->
     <tr>
       <td><tt>typename</tt> in a template template parameter</td>
       <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4051.html">N4051</a></td>
       <td class="full" align="center">Clang 3.5</td>
     </tr>
+    <tr>
+      <td>New <tt>auto</tt> rules for direct-list-initialization
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3922.html">N3922</a></td>
+      <td class="none" align="center">No</td>
+    </tr>
     <!-- Urbana papers -->
     <tr>
       <td>Fold expressions</td>
-      <td><!--<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4295.html">-->N4295<!--</a>--></td>
-      <td class="svn" align="center">SVN</td>
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4295.html">N4295</a></td>
+      <td class="svn" align="center">Clang 3.6</td>
     </tr>
     <tr>
       <td><tt>u8</tt> character literals</td>
-      <td><!--<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4267.html">-->N4267<!--</a>--></td>
-      <td class="svn" align="center">SVN</td>
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4267.html">N4267</a></td>
+      <td class="svn" align="center">Clang 3.6</td>
     </tr>
     <tr>
       <td>Nested namespace definition</td>
-      <td><!--<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4230.html">-->N4230<!--</a>--></td>
-      <td class="svn" align="center">SVN</td>
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4230.html">N4230</a></td>
+      <td class="svn" align="center">Clang 3.6</td>
     </tr>
     <tr>
       <td>Attributes for namespaces and enumerators</td>
-      <td><!--<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4266.html">-->N4266<!--</a>--></td>
-      <td class="svn" align="center">SVN</td>
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4266.html">N4266</a></td>
+      <td class="svn" align="center">Clang 3.6</td>
+    </tr>
+    <tr>
+      <td>Allow constant evaluation for all non-type template arguments</td>
+      <td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4268.html">N4268</a></td>
+      <td class="svn" align="center">Clang 3.6</td>
     </tr>
 </table>
 
@@ -590,8 +615,8 @@
       </td>
     </tr>
     <tr>
-      <td class="full" align="center">
-        SVN (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4200">N4200</a>)</a>
+      <td class="svn" align="center">
+        Clang 3.6 (<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4200">N4200</a>)</a>
       </td>
     </tr>
     <tr>
diff --git a/www/make_cxx_dr_status b/www/make_cxx_dr_status
index 4ae769d..db31635 100755
--- a/www/make_cxx_dr_status
+++ b/www/make_cxx_dr_status
@@ -102,10 +102,10 @@
   if status == 'unknown':
     avail = 'Unknown'
     avail_style = ' class="none"'
-  elif status == '3.6':
+  elif status == '3.7':
     avail = 'SVN'
     avail_style = ' class="svn"'
-  elif status in ('3.1', '3.2', '3.3', '3.4', '3.5'):
+  elif status in ('3.1', '3.2', '3.3', '3.4', '3.5', '3.6'):
     avail = 'Clang %s' % status
     avail_style = ' class="full"'
   elif status == 'yes':